anakin87 commited on
Commit
efcf35e
โ€ข
1 Parent(s): 1c93286
Files changed (2) hide show
  1. README.md +6 -5
  2. app.py +122 -40
README.md CHANGED
@@ -1,13 +1,14 @@
1
  ---
2
  title: Phi 3.5 Mini ITA
3
- emoji: ๐Ÿ’ฌ
4
- colorFrom: yellow
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 4.36.1
8
  app_file: app.py
9
- pinned: false
10
  license: mit
 
11
  ---
12
 
13
  An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
1
  ---
2
  title: Phi 3.5 Mini ITA
3
+ emoji: ๐Ÿ’ฌ๐Ÿ‡ฎ๐Ÿ‡น
4
+ colorFrom: green
5
+ colorTo: red
6
  sdk: gradio
7
+ sdk_version: 4.39.0
8
  app_file: app.py
9
+ pinned: true
10
  license: mit
11
+ short_description: Chat with an Italian Small Model
12
  ---
13
 
14
  An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
app.py CHANGED
@@ -1,63 +1,145 @@
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
3
 
 
 
 
 
 
 
 
 
4
  """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
 
 
 
 
 
 
 
35
  top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
 
38
 
39
- response += token
40
- yield response
 
 
41
 
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
  additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
  gr.Slider(
 
 
 
 
 
 
 
 
52
  minimum=0.1,
 
 
 
 
 
 
 
53
  maximum=1.0,
54
- value=0.95,
55
  step=0.05,
56
- label="Top-p (nucleus sampling)",
57
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  ],
 
59
  )
60
 
 
 
 
 
61
 
62
  if __name__ == "__main__":
63
- demo.launch()
 
1
+ import os
2
+ from threading import Thread
3
+ from typing import Iterator
4
+
5
  import gradio as gr
6
+ import spaces
7
+ import torch
8
+ from transformers import AutoModelForCausalLM, GemmaTokenizerFast, TextIteratorStreamer
9
 
10
+ DESCRIPTION = """\
11
+ # Gemma 2 9B IT
12
+
13
+ Gemma 2 is Google's latest iteration of open LLMs.
14
+ This is a demo of [`google/gemma-2-9b-it`](https://huggingface.co/google/gemma-2-9b-it), fine-tuned for instruction following.
15
+ For more details, please check [our post](https://huggingface.co/blog/gemma2).
16
+
17
+ ๐Ÿ‘‰ Looking for a larger and more powerful version? Try the 27B version in [HuggingChat](https://huggingface.co/chat/models/google/gemma-2-27b-it).
18
  """
 
 
 
19
 
20
+ MAX_MAX_NEW_TOKENS = 2048
21
+ DEFAULT_MAX_NEW_TOKENS = 1024
22
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
23
 
24
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
 
 
 
 
 
 
 
25
 
26
+ model_id = "anakin87/Phi-3.5-mini-ITA"
27
+ tokenizer = GemmaTokenizerFast.from_pretrained(model_id)
28
+ model = AutoModelForCausalLM.from_pretrained(
29
+ model_id,
30
+ device_map="auto",
31
+ torch_dtype=torch.bfloat16,
32
+ )
33
+ model.config.sliding_window = 4096
34
+ model.eval()
35
 
 
36
 
37
+ @spaces.GPU(duration=90)
38
+ def generate(
39
+ message: str,
40
+ chat_history: list[tuple[str, str]],
41
+ max_new_tokens: int = 1024,
42
+ temperature: float = 0.6,
43
+ top_p: float = 0.9,
44
+ top_k: int = 50,
45
+ repetition_penalty: float = 1.2,
46
+ ) -> Iterator[str]:
47
+ conversation = []
48
+ for user, assistant in chat_history:
49
+ conversation.extend(
50
+ [
51
+ {"role": "user", "content": user},
52
+ {"role": "assistant", "content": assistant},
53
+ ]
54
+ )
55
+ conversation.append({"role": "user", "content": message})
56
 
57
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
58
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
59
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
60
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
61
+ input_ids = input_ids.to(model.device)
62
+
63
+ streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
64
+ generate_kwargs = dict(
65
+ {"input_ids": input_ids},
66
+ streamer=streamer,
67
+ max_new_tokens=max_new_tokens,
68
+ do_sample=True,
69
  top_p=top_p,
70
+ top_k=top_k,
71
+ temperature=temperature,
72
+ num_beams=1,
73
+ repetition_penalty=repetition_penalty,
74
+ )
75
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
76
+ t.start()
77
 
78
+ outputs = []
79
+ for text in streamer:
80
+ outputs.append(text)
81
+ yield "".join(outputs)
82
 
83
+
84
+ chat_interface = gr.ChatInterface(
85
+ fn=generate,
 
 
86
  additional_inputs=[
 
 
 
87
  gr.Slider(
88
+ label="Max new tokens",
89
+ minimum=1,
90
+ maximum=MAX_MAX_NEW_TOKENS,
91
+ step=1,
92
+ value=DEFAULT_MAX_NEW_TOKENS,
93
+ ),
94
+ gr.Slider(
95
+ label="Temperature",
96
  minimum=0.1,
97
+ maximum=4.0,
98
+ step=0.1,
99
+ value=0.6,
100
+ ),
101
+ gr.Slider(
102
+ label="Top-p (nucleus sampling)",
103
+ minimum=0.05,
104
  maximum=1.0,
 
105
  step=0.05,
106
+ value=0.9,
107
  ),
108
+ gr.Slider(
109
+ label="Top-k",
110
+ minimum=1,
111
+ maximum=1000,
112
+ step=1,
113
+ value=50,
114
+ ),
115
+ gr.Slider(
116
+ label="Repetition penalty",
117
+ minimum=1.0,
118
+ maximum=2.0,
119
+ step=0.05,
120
+ value=1.2,
121
+ ),
122
+ ],
123
+ stop_btn=None,
124
+ examples=[
125
+ ["Ciao! Come stai?"],
126
+ ["Puoi spiegarmi brevemente cos'รจ il linguaggio di programmazione Python?"],
127
+ ["Spiega la trama di Cenerentola in una frase."],
128
+ ["Quante ore ci vogliono a un uomo per mangiare un elicottero?"],
129
+ ["Scrivi un articolo di 100 parole sui 'Benefici dell'open-source nella ricerca sull'intelligenza artificiale'"],
130
+ ["Hello there! How are you doing?"],
131
+ ["Can you explain briefly to me what is the Python programming language?"],
132
+ ["Explain the plot of Cinderella in a sentence."],
133
+ ["How many hours does it take a man to eat a Helicopter?"],
134
+ ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
135
  ],
136
+ cache_examples=False,
137
  )
138
 
139
+ with gr.Blocks(css="style.css", fill_height=True) as demo:
140
+ gr.Markdown(DESCRIPTION)
141
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
142
+ chat_interface.render()
143
 
144
  if __name__ == "__main__":
145
+ demo.queue(max_size=20).launch()