shenzhi-wang commited on
Commit
892f733
1 Parent(s): b7464bd

[launch] launch space for Gemma-2-27B-Chinese-Chat

Browse files
Files changed (2) hide show
  1. app.py +114 -47
  2. requirements.txt +4 -1
app.py CHANGED
@@ -1,62 +1,129 @@
 
 
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__":
 
1
+ from threading import Thread
2
+
3
  import gradio as gr
4
+ import spaces
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
 
7
+
8
+ TITLE = "<h1><center>Chat with Gemma-2-27B-Chinese-Chat</center></h1>"
9
+
10
+ DESCRIPTION = "<h3><center>Visit <a href='https://huggingface.co/shenzhi-wang/Gemma-2-27B-Chinese-Chat' target='_blank'>our model page</a> for details.</center></h3>"
11
+
12
+ DEFAULT_SYSTEM = "You are a helpful assistant."
13
+
14
+ TOOL_EXAMPLE = '''You have access to the following tools:
15
+ ```python
16
+ def generate_password(length: int, include_symbols: Optional[bool]):
17
+ """
18
+ Generate a random password.
19
+ Args:
20
+ length (int): The length of the password
21
+ include_symbols (Optional[bool]): Include symbols in the password
22
+ """
23
+ pass
24
+ ```
25
+ Write "Action:" followed by a list of actions in JSON that you want to call, e.g.
26
+ Action:
27
+ ```json
28
+ [
29
+ {
30
+ "name": "tool name (one of [generate_password])",
31
+ "arguments": "the input to the tool"
32
+ }
33
+ ]
34
+ ```
35
+ '''
36
+
37
+ CSS = """
38
+ .duplicate-button {
39
+ margin: auto !important;
40
+ color: white !important;
41
+ background: black !important;
42
+ border-radius: 100vh !important;
43
+ }
44
  """
 
 
 
45
 
46
 
47
+ tokenizer = AutoTokenizer.from_pretrained("shenzhi-wang/Gemma-2-27B-Chinese-Chat")
48
+ model = AutoModelForCausalLM.from_pretrained("shenzhi-wang/Gemma-2-27B-Chinese-Chat", device_map="auto")
 
 
 
 
 
 
 
49
 
 
 
 
 
 
50
 
51
+ @spaces.GPU
52
+ def stream_chat(message: str, history: list, system: str, temperature: float, max_new_tokens: int):
53
+ conversation = [{"role": "system", "content": system or DEFAULT_SYSTEM}]
54
+ for prompt, answer in history:
55
+ conversation.extend([{"role": "user", "content": prompt}, {"role": "assistant", "content": answer}])
56
 
57
+ conversation.append({"role": "user", "content": message})
58
 
59
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt").to(
60
+ model.device
61
+ )
62
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
63
+
64
+ generate_kwargs = dict(
65
+ input_ids=input_ids,
66
+ streamer=streamer,
67
+ max_new_tokens=max_new_tokens,
68
  temperature=temperature,
69
+ do_sample=True,
70
+ )
71
+ if temperature == 0:
72
+ generate_kwargs["do_sample"] = False
73
 
74
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
75
+ t.start()
76
 
77
+ output = ""
78
+ for new_token in streamer:
79
+ output += new_token
80
+ yield output
81
+
82
+
83
+ chatbot = gr.Chatbot(height=450)
84
+
85
+ with gr.Blocks(css=CSS) as demo:
86
+ gr.HTML(TITLE)
87
+ gr.HTML(DESCRIPTION)
88
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_classes="duplicate-button")
89
+ gr.ChatInterface(
90
+ fn=stream_chat,
91
+ chatbot=chatbot,
92
+ fill_height=True,
93
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
94
+ additional_inputs=[
95
+ gr.Text(
96
+ value="",
97
+ label="System",
98
+ render=False,
99
+ ),
100
+ gr.Slider(
101
+ minimum=0,
102
+ maximum=1,
103
+ step=0.1,
104
+ value=0.8,
105
+ label="Temperature",
106
+ render=False,
107
+ ),
108
+ gr.Slider(
109
+ minimum=128,
110
+ maximum=4096,
111
+ step=1,
112
+ value=1024,
113
+ label="Max new tokens",
114
+ render=False,
115
+ ),
116
+ ],
117
+ examples=[
118
+ ["我的蓝牙耳机坏了,我该去看牙科还是耳鼻喉科?", ""],
119
+ ["7年前,妈妈年龄是儿子的6倍,儿子今年12岁,妈妈今年多少岁?", ""],
120
+ ["我的笔记本找不到了。", "扮演诸葛亮和我对话。"],
121
+ ["我想要一个新的密码,长度为8位,包含特殊符号。", TOOL_EXAMPLE],
122
+ ["How are you today?", "You are Taylor Swift, use beautiful lyrics to answer questions."],
123
+ ["用C++实现KMP算法,并加上中文注释", ""],
124
+ ],
125
+ cache_examples=False,
126
+ )
127
 
128
 
129
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -1 +1,4 @@
1
- huggingface_hub==0.22.2
 
 
 
 
1
+ huggingface_hub==0.22.2
2
+ transformers>=4.42.3
3
+ accelerate
4
+ tiktoken