5to9 commited on
Commit
74ffc36
1 Parent(s): 92c6271

0.2 adding cloned space

Browse files
Files changed (3) hide show
  1. README.md +2 -2
  2. app.py +192 -47
  3. requirements.txt +6 -1
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
  title: Bot Royale
3
- emoji: 💬
4
  colorFrom: yellow
5
  colorTo: purple
6
  sdk: gradio
@@ -10,4 +10,4 @@ pinned: false
10
  license: apache-2.0
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: Bot Royale
3
+ emoji: 🥊
4
  colorFrom: yellow
5
  colorTo: purple
6
  sdk: gradio
 
10
  license: apache-2.0
11
  ---
12
 
13
+ A chatbot arena battle royale, based on a script by Mohamed Rashad for the [Arabic Chatbot Arena](MohamedRashad/Arabic-Chatbot-Arena). 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,208 @@
 
 
 
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 spaces
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
3
+ import torch
4
  import gradio as gr
5
+ import logging
6
+ from huggingface_hub import login
7
+ import os
8
 
9
+ from threading import Thread
10
+ import subprocess
11
+ subprocess.run('pip install -U flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
12
+
13
+ logging.basicConfig(level=logging.DEBUG)
14
+
15
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
16
+ login(token=HF_TOKEN)
17
+
18
+ models_available = [
19
+ "Aleph-Alpha/Pharia-1-LLM-7B-control-hf",
20
+ "mistralai/Mistral-7B-Instruct-v0.3",
21
+ ]
22
+
23
+ tokenizer_a, model_a = None, None
24
+ tokenizer_b, model_b = None, None
25
+ torch_dtype = torch.bfloat16
26
+ attn_implementation = "flash_attention_2"
27
 
28
+ def load_model_a(model_id):
29
+ global tokenizer_a, model_a
30
+ tokenizer_a = AutoTokenizer.from_pretrained(model_id)
31
+ logging.debug(f"model A: {tokenizer_a.eos_token}")
32
+ try:
33
+ model_a = AutoModelForCausalLM.from_pretrained(
34
+ model_id,
35
+ torch_dtype=torch_dtype,
36
+ device_map="auto",
37
+ attn_implementation=attn_implementation,
38
+ trust_remote_code=True,
39
+ ).eval()
40
+ except Exception as e:
41
+ logging.debug(f"Using default attention implementation in {model_id}")
42
+ logging.debug(f"Error: {e}")
43
+ model_a = AutoModelForCausalLM.from_pretrained(
44
+ model_id,
45
+ torch_dtype=torch_dtype,
46
+ device_map="auto",
47
+ trust_remote_code=True,
48
+ ).eval()
49
+ model_a.tie_weights()
50
+ return gr.update(label=model_id)
51
+
52
+ def load_model_b(model_id):
53
+ global tokenizer_b, model_b
54
+ tokenizer_b = AutoTokenizer.from_pretrained(model_id)
55
+ logging.debug(f"model B: {tokenizer_b.eos_token}")
56
+ try:
57
+ model_b = AutoModelForCausalLM.from_pretrained(
58
+ model_id,
59
+ torch_dtype=torch_dtype,
60
+ device_map="auto",
61
+ attn_implementation=attn_implementation,
62
+ trust_remote_code=True,
63
+ ).eval()
64
+ except Exception as e:
65
+ logging.debug(f"Error: {e}")
66
+ logging.debug(f"Using default attention implementation in {model_id}")
67
+ model_b = AutoModelForCausalLM.from_pretrained(
68
+ model_id,
69
+ torch_dtype=torch_dtype,
70
+ device_map="auto",
71
+ trust_remote_code=True,
72
+ ).eval()
73
+ model_b.tie_weights()
74
+ return gr.update(label=model_id)
75
 
76
+ @spaces.GPU()
77
+ def generate_both(system_prompt, input_text, chatbot_a, chatbot_b, max_new_tokens=2048, temperature=0.2, top_p=0.9, repetition_penalty=1.1):
 
 
 
 
 
 
 
78
 
79
+ text_streamer_a = TextIteratorStreamer(tokenizer_a, skip_prompt=True)
80
+ text_streamer_b = TextIteratorStreamer(tokenizer_b, skip_prompt=True)
 
 
 
81
 
82
+ system_prompt_list = [{"role": "system", "content": system_prompt}] if system_prompt else []
83
+ input_text_list = [{"role": "user", "content": input_text}]
84
 
85
+ chat_history_a = []
86
+ for user, assistant in chatbot_a:
87
+ chat_history_a.append({"role": "user", "content": user})
88
+ chat_history_a.append({"role": "assistant", "content": assistant})
89
 
90
+ chat_history_b = []
91
+ for user, assistant in chatbot_b:
92
+ chat_history_b.append({"role": "user", "content": user})
93
+ chat_history_b.append({"role": "assistant", "content": assistant})
94
+
95
+ base_messages = system_prompt_list + chat_history_a + input_text_list
96
+ new_messages = system_prompt_list + chat_history_b + input_text_list
97
+
98
+ input_ids_a = tokenizer_a.apply_chat_template(
99
+ base_messages,
100
+ add_generation_prompt=True,
101
+ return_tensors="pt"
102
+ ).to(model_a.device)
103
+
104
+ input_ids_b = tokenizer_b.apply_chat_template(
105
+ new_messages,
106
+ add_generation_prompt=True,
107
+ return_tensors="pt"
108
+ ).to(model_b.device)
109
+
110
+ generation_kwargs_a = dict(
111
+ input_ids=input_ids_a,
112
+ streamer=text_streamer_a,
113
+ max_new_tokens=max_new_tokens,
114
+ pad_token_id=tokenizer_a.eos_token_id,
115
+ do_sample=True,
116
+ temperature=temperature,
117
+ top_p=top_p,
118
+ repetition_penalty=repetition_penalty,
119
+ )
120
+ generation_kwargs_b = dict(
121
+ input_ids=input_ids_b,
122
+ streamer=text_streamer_b,
123
+ max_new_tokens=max_new_tokens,
124
+ pad_token_id=tokenizer_b.eos_token_id,
125
+ do_sample=True,
126
  temperature=temperature,
127
  top_p=top_p,
128
+ repetition_penalty=repetition_penalty,
129
+ )
130
 
131
+ thread_a = Thread(target=model_a.generate, kwargs=generation_kwargs_a)
132
+ thread_b = Thread(target=model_b.generate, kwargs=generation_kwargs_b)
133
 
134
+ thread_a.start()
135
+ thread_b.start()
136
+
137
+ chatbot_a.append([input_text, ""])
138
+ chatbot_b.append([input_text, ""])
139
+
140
+ finished_a = False
141
+ finished_b = False
142
+
143
+ while not (finished_a and finished_b):
144
+ if not finished_a:
145
+ try:
146
+ text_a = next(text_streamer_a)
147
+ if tokenizer_a.eos_token in text_a:
148
+ eot_location = text_a.find(tokenizer_a.eos_token)
149
+ text_a = text_a[:eot_location]
150
+ finished_a = True
151
+ chatbot_a[-1][-1] += text_a
152
+ yield chatbot_a, chatbot_b
153
+ except StopIteration:
154
+ finished_a = True
155
+
156
+ if not finished_b:
157
+ try:
158
+ text_b = next(text_streamer_b)
159
+ if tokenizer_b.eos_token in text_b:
160
+ eot_location = text_b.find(tokenizer_b.eos_token)
161
+ text_b = text_b[:eot_location]
162
+ finished_b = True
163
+ chatbot_b[-1][-1] += text_b
164
+ yield chatbot_a, chatbot_b
165
+ except StopIteration:
166
+ finished_b = True
167
+
168
+ return chatbot_a, chatbot_b
169
+
170
+ def clear():
171
+ return [], []
172
+
173
+ arena_notes = """## Important Notes:
174
+ - Sometimes an error may occur when generating the response, in this case, please try again.
175
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
+ with gr.Blocks() as demo:
178
+ with gr.Column():
179
+ gr.HTML("<center><h1>🤖le Royale</h1></center>")
180
+ gr.Markdown(arena_notes)
181
+ system_prompt = gr.Textbox(lines=1, label="System Prompt", value="أنت متحدث لبق باللغة العربية!", rtl=True, text_align="right", show_copy_button=True)
182
+ with gr.Row(variant="panel"):
183
+ with gr.Column():
184
+ model_dropdown_a = gr.Dropdown(label="Model A", choices=models_available, value=None)
185
+ chatbot_a = gr.Chatbot(label="Model A", rtl=True, likeable=True, show_copy_button=True, height=500)
186
+ with gr.Column():
187
+ model_dropdown_b = gr.Dropdown(label="Model B", choices=models_available, value=None)
188
+ chatbot_b = gr.Chatbot(label="Model B", rtl=True, likeable=True, show_copy_button=True, height=500)
189
+ with gr.Row(variant="panel"):
190
+ with gr.Column(scale=1):
191
+ submit_btn = gr.Button(value="Generate", variant="primary")
192
+ clear_btn = gr.Button(value="Clear", variant="secondary")
193
+ input_text = gr.Textbox(lines=1, label="", value="مرحبا", rtl=True, text_align="right", scale=3, show_copy_button=True)
194
+ with gr.Accordion(label="Generation Configurations", open=False):
195
+ max_new_tokens = gr.Slider(minimum=128, maximum=4096, value=2048, label="Max New Tokens", step=128)
196
+ temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, label="Temperature", step=0.01)
197
+ top_p = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, label="Top-p", step=0.01)
198
+ repetition_penalty = gr.Slider(minimum=0.1, maximum=2.0, value=1.1, label="Repetition Penalty", step=0.1)
199
+
200
+ model_dropdown_a.change(load_model_a, inputs=[model_dropdown_a], outputs=[chatbot_a])
201
+ model_dropdown_b.change(load_model_b, inputs=[model_dropdown_b], outputs=[chatbot_b])
202
+
203
+ input_text.submit(generate_both, inputs=[system_prompt, input_text, chatbot_a, chatbot_b, max_new_tokens, temperature, top_p, repetition_penalty], outputs=[chatbot_a, chatbot_b])
204
+ submit_btn.click(generate_both, inputs=[system_prompt, input_text, chatbot_a, chatbot_b, max_new_tokens, temperature, top_p, repetition_penalty], outputs=[chatbot_a, chatbot_b])
205
+ clear_btn.click(clear, outputs=[chatbot_a, chatbot_b])
206
 
207
  if __name__ == "__main__":
208
+ demo.queue().launch()
requirements.txt CHANGED
@@ -1 +1,6 @@
1
- huggingface_hub==0.22.2
 
 
 
 
 
 
1
+ huggingface_hub==0.22.2
2
+ transformers==4.44.1
3
+ torch
4
+ accelerate==0.33.0
5
+ sentencepiece==0.2.0
6
+ spaces