ehristoforu commited on
Commit
807b486
1 Parent(s): eedaccf

Upload 4 files

Browse files
Files changed (4) hide show
  1. app (13).py +254 -0
  2. model (1).py +57 -0
  3. requirements (14).txt +9 -0
  4. style (2).css +16 -0
app (13).py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Iterator
3
+
4
+ import gradio as gr
5
+
6
+ from model import run
7
+
8
+ HF_PUBLIC = os.environ.get("HF_PUBLIC", False)
9
+
10
+ DEFAULT_SYSTEM_PROMPT = "You are CodeLlama. You are AI-assistant, you are polite, give only truthful information and are based on the CodeLLaMA-34B model from Meta. You can communicate in different languages equally well."
11
+ MAX_MAX_NEW_TOKENS = 4096
12
+ DEFAULT_MAX_NEW_TOKENS = 1024
13
+ MAX_INPUT_TOKEN_LENGTH = 4000
14
+
15
+ DESCRIPTION = """
16
+ # CodeLlama-34B Chat
17
+
18
+ 💻 This Space demonstrates model [CodeLlama-34b-Instruct](https://huggingface.co/codellama/CodeLlama-34b-Instruct-hf) by Meta, a Code Llama model with 34B parameters fine-tuned for chat instructions and specialized on code tasks. Feel free to play with it, or duplicate to run generations without a queue! If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://huggingface.co/inference-endpoints).
19
+
20
+ 🔎 For more details about the Code Llama family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/codellama) or [the paper](https://huggingface.co/papers/2308.12950).
21
+
22
+ 🏃🏻 Check out our [Playground](https://huggingface.co/spaces/codellama/codellama-playground) for a super-fast code completion demo that leverages a streaming [inference endpoint](https://huggingface.co/inference-endpoints).
23
+
24
+ """
25
+
26
+ def clear_and_save_textbox(message: str) -> tuple[str, str]:
27
+ return '', message
28
+
29
+
30
+ def display_input(message: str,
31
+ history: list[tuple[str, str]]) -> list[tuple[str, str]]:
32
+ history.append((message, ''))
33
+ return history
34
+
35
+
36
+ def delete_prev_fn(
37
+ history: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], str]:
38
+ try:
39
+ message, _ = history.pop()
40
+ except IndexError:
41
+ message = ''
42
+ return history, message or ''
43
+
44
+
45
+ def generate(
46
+ message: str,
47
+ history_with_input: list[tuple[str, str]],
48
+ system_prompt: str,
49
+ max_new_tokens: int,
50
+ temperature: float,
51
+ top_p: float,
52
+ top_k: int,
53
+ ) -> Iterator[list[tuple[str, str]]]:
54
+ if max_new_tokens > MAX_MAX_NEW_TOKENS:
55
+ raise ValueError
56
+
57
+ history = history_with_input[:-1]
58
+ generator = run(message, history, system_prompt, max_new_tokens, temperature, top_p, top_k)
59
+ try:
60
+ first_response = next(generator)
61
+ yield history + [(message, first_response)]
62
+ except StopIteration:
63
+ yield history + [(message, '')]
64
+ for response in generator:
65
+ yield history + [(message, response)]
66
+
67
+
68
+ def process_example(message: str) -> tuple[str, list[tuple[str, str]]]:
69
+ generator = generate(message, [], DEFAULT_SYSTEM_PROMPT, 1024, 1, 0.95, 50)
70
+ for x in generator:
71
+ pass
72
+ return '', x
73
+
74
+
75
+ def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
76
+ input_token_length = len(message) + len(chat_history)
77
+ if input_token_length > MAX_INPUT_TOKEN_LENGTH:
78
+ raise gr.Error(f'The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again.')
79
+
80
+
81
+ with gr.Blocks(css='style.css') as demo:
82
+ gr.Markdown(DESCRIPTION)
83
+ gr.DuplicateButton(value='Duplicate Space for private use',
84
+ elem_id='duplicate-button')
85
+
86
+ with gr.Group():
87
+ chatbot = gr.Chatbot(label='Playground')
88
+ with gr.Row():
89
+ textbox = gr.Textbox(
90
+ container=False,
91
+ show_label=False,
92
+ placeholder='Hi, CodeLlama!',
93
+ scale=10,
94
+ )
95
+ submit_button = gr.Button('Submit',
96
+ variant='primary',
97
+ scale=1,
98
+ min_width=0)
99
+ with gr.Row():
100
+ retry_button = gr.Button('🔄 Retry', variant='secondary')
101
+ undo_button = gr.Button('↩️ Undo', variant='secondary')
102
+ clear_button = gr.Button('🗑️ Clear', variant='secondary')
103
+
104
+ saved_input = gr.State()
105
+
106
+ with gr.Accordion(label='⚙️ Advanced options', open=False):
107
+ system_prompt = gr.Textbox(label='System prompt',
108
+ value=DEFAULT_SYSTEM_PROMPT,
109
+ lines=5,
110
+ interactive=False)
111
+ max_new_tokens = gr.Slider(
112
+ label='Max new tokens',
113
+ minimum=1,
114
+ maximum=MAX_MAX_NEW_TOKENS,
115
+ step=1,
116
+ value=DEFAULT_MAX_NEW_TOKENS,
117
+ )
118
+ temperature = gr.Slider(
119
+ label='Temperature',
120
+ minimum=0.1,
121
+ maximum=4.0,
122
+ step=0.1,
123
+ value=0.1,
124
+ )
125
+ top_p = gr.Slider(
126
+ label='Top-p (nucleus sampling)',
127
+ minimum=0.05,
128
+ maximum=1.0,
129
+ step=0.05,
130
+ value=0.9,
131
+ )
132
+ top_k = gr.Slider(
133
+ label='Top-k',
134
+ minimum=1,
135
+ maximum=1000,
136
+ step=1,
137
+ value=10,
138
+ )
139
+
140
+
141
+
142
+ textbox.submit(
143
+ fn=clear_and_save_textbox,
144
+ inputs=textbox,
145
+ outputs=[textbox, saved_input],
146
+ api_name=False,
147
+ queue=False,
148
+ ).then(
149
+ fn=display_input,
150
+ inputs=[saved_input, chatbot],
151
+ outputs=chatbot,
152
+ api_name=False,
153
+ queue=False,
154
+ ).then(
155
+ fn=check_input_token_length,
156
+ inputs=[saved_input, chatbot, system_prompt],
157
+ api_name=False,
158
+ queue=False,
159
+ ).success(
160
+ fn=generate,
161
+ inputs=[
162
+ saved_input,
163
+ chatbot,
164
+ system_prompt,
165
+ max_new_tokens,
166
+ temperature,
167
+ top_p,
168
+ top_k,
169
+ ],
170
+ outputs=chatbot,
171
+ api_name=False,
172
+ )
173
+
174
+ button_event_preprocess = submit_button.click(
175
+ fn=clear_and_save_textbox,
176
+ inputs=textbox,
177
+ outputs=[textbox, saved_input],
178
+ api_name=False,
179
+ queue=False,
180
+ ).then(
181
+ fn=display_input,
182
+ inputs=[saved_input, chatbot],
183
+ outputs=chatbot,
184
+ api_name=False,
185
+ queue=False,
186
+ ).then(
187
+ fn=check_input_token_length,
188
+ inputs=[saved_input, chatbot, system_prompt],
189
+ api_name=False,
190
+ queue=False,
191
+ ).success(
192
+ fn=generate,
193
+ inputs=[
194
+ saved_input,
195
+ chatbot,
196
+ system_prompt,
197
+ max_new_tokens,
198
+ temperature,
199
+ top_p,
200
+ top_k,
201
+ ],
202
+ outputs=chatbot,
203
+ api_name=False,
204
+ )
205
+
206
+ retry_button.click(
207
+ fn=delete_prev_fn,
208
+ inputs=chatbot,
209
+ outputs=[chatbot, saved_input],
210
+ api_name=False,
211
+ queue=False,
212
+ ).then(
213
+ fn=display_input,
214
+ inputs=[saved_input, chatbot],
215
+ outputs=chatbot,
216
+ api_name=False,
217
+ queue=False,
218
+ ).then(
219
+ fn=generate,
220
+ inputs=[
221
+ saved_input,
222
+ chatbot,
223
+ system_prompt,
224
+ max_new_tokens,
225
+ temperature,
226
+ top_p,
227
+ top_k,
228
+ ],
229
+ outputs=chatbot,
230
+ api_name=False,
231
+ )
232
+
233
+ undo_button.click(
234
+ fn=delete_prev_fn,
235
+ inputs=chatbot,
236
+ outputs=[chatbot, saved_input],
237
+ api_name=False,
238
+ queue=False,
239
+ ).then(
240
+ fn=lambda x: x,
241
+ inputs=[saved_input],
242
+ outputs=textbox,
243
+ api_name=False,
244
+ queue=False,
245
+ )
246
+
247
+ clear_button.click(
248
+ fn=lambda: ([], ''),
249
+ outputs=[chatbot, saved_input],
250
+ queue=False,
251
+ api_name=False,
252
+ )
253
+
254
+ demo.queue(max_size=32).launch(share=HF_PUBLIC, show_api=False)
model (1).py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Iterator
3
+
4
+ from text_generation import Client
5
+
6
+ model_id = 'codellama/CodeLlama-34b-Instruct-hf'
7
+
8
+ API_URL = "https://api-inference.huggingface.co/models/" + model_id
9
+ HF_TOKEN = os.environ.get("HF_READ_TOKEN", None)
10
+
11
+ client = Client(
12
+ API_URL,
13
+ headers={"Authorization": f"Bearer {HF_TOKEN}"},
14
+ )
15
+ EOS_STRING = "</s>"
16
+ EOT_STRING = "<EOT>"
17
+
18
+
19
+ def get_prompt(message: str, chat_history: list[tuple[str, str]],
20
+ system_prompt: str) -> str:
21
+ texts = [f'<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n']
22
+ # The first user input is _not_ stripped
23
+ do_strip = False
24
+ for user_input, response in chat_history:
25
+ user_input = user_input.strip() if do_strip else user_input
26
+ do_strip = True
27
+ texts.append(f'{user_input} [/INST] {response.strip()} </s><s>[INST] ')
28
+ message = message.strip() if do_strip else message
29
+ texts.append(f'{message} [/INST]')
30
+ return ''.join(texts)
31
+
32
+
33
+ def run(message: str,
34
+ chat_history: list[tuple[str, str]],
35
+ system_prompt: str,
36
+ max_new_tokens: int = 1024,
37
+ temperature: float = 0.1,
38
+ top_p: float = 0.9,
39
+ top_k: int = 50) -> Iterator[str]:
40
+ prompt = get_prompt(message, chat_history, system_prompt)
41
+
42
+ generate_kwargs = dict(
43
+ max_new_tokens=max_new_tokens,
44
+ do_sample=True,
45
+ top_p=top_p,
46
+ top_k=top_k,
47
+ temperature=temperature,
48
+ )
49
+ stream = client.generate_stream(prompt, **generate_kwargs)
50
+ output = ""
51
+ for response in stream:
52
+ if any([end_token in response.token.text for end_token in [EOS_STRING, EOT_STRING]]):
53
+ return output
54
+ else:
55
+ output += response.token.text
56
+ yield output
57
+ return output
requirements (14).txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ accelerate
2
+ bitsandbytes
3
+ gradio
4
+ protobuf
5
+ scipy
6
+ sentencepiece
7
+ torch
8
+ text_generation
9
+ git+https://github.com/huggingface/transformers@main
style (2).css ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ h1 {
2
+ text-align: center;
3
+ }
4
+
5
+ #duplicate-button {
6
+ margin: auto;
7
+ color: white;
8
+ background: #1565c0;
9
+ border-radius: 100vh;
10
+ }
11
+
12
+ #component-0 {
13
+ max-width: 900px;
14
+ margin: auto;
15
+ padding-top: 1.5rem;
16
+ }