Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,340 +1,280 @@
|
|
1 |
-
import os
|
2 |
-
from transformers import AutoTokenizer, AutoConfig
|
3 |
-
from optimum.intel.openvino import OVModelForCausalLM
|
4 |
-
from generation_utils import run_generation, estimate_latency, reset_textbox,get_special_token_id
|
5 |
-
from config import SUPPORTED_LLM_MODELS
|
6 |
-
import gradio as gr
|
7 |
-
from threading import Thread
|
8 |
-
from time import perf_counter
|
9 |
-
from typing import List
|
10 |
-
from transformers import AutoTokenizer, TextIteratorStreamer
|
11 |
-
import numpy as np
|
12 |
-
import os
|
13 |
-
from flask import Flask, render_template, redirect, url_for, request, flash
|
14 |
-
from flask_sqlalchemy import SQLAlchemy
|
15 |
-
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
|
16 |
-
from werkzeug.security import generate_password_hash, check_password_hash
|
17 |
-
|
18 |
-
app = Flask(__name__)
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
)
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
""
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
button_submit = gr.Button(value="Submit")
|
281 |
-
gr.Examples(examples, user_text)
|
282 |
-
with gr.Column(scale=1):
|
283 |
-
max_new_tokens = gr.Slider(
|
284 |
-
minimum=1,
|
285 |
-
maximum=1000,
|
286 |
-
value=256,
|
287 |
-
step=1,
|
288 |
-
interactive=True,
|
289 |
-
label="Max New Tokens",
|
290 |
-
)
|
291 |
-
top_p = gr.Slider(
|
292 |
-
minimum=0.05,
|
293 |
-
maximum=1.0,
|
294 |
-
value=0.92,
|
295 |
-
step=0.05,
|
296 |
-
interactive=True,
|
297 |
-
label="Top-p (nucleus sampling)",
|
298 |
-
)
|
299 |
-
top_k = gr.Slider(
|
300 |
-
minimum=0,
|
301 |
-
maximum=50,
|
302 |
-
value=0,
|
303 |
-
step=1,
|
304 |
-
interactive=True,
|
305 |
-
label="Top-k",
|
306 |
-
)
|
307 |
-
temperature = gr.Slider(
|
308 |
-
minimum=0.1,
|
309 |
-
maximum=5.0,
|
310 |
-
value=0.8,
|
311 |
-
step=0.1,
|
312 |
-
interactive=True,
|
313 |
-
label="Temperature",
|
314 |
-
)
|
315 |
-
|
316 |
-
user_text.submit(
|
317 |
-
run_generation,
|
318 |
-
[user_text, top_p, temperature, top_k, max_new_tokens, performance],
|
319 |
-
[model_output, performance],
|
320 |
-
)
|
321 |
-
button_submit.click(
|
322 |
-
run_generation,
|
323 |
-
[user_text, top_p, temperature, top_k, max_new_tokens, performance],
|
324 |
-
[model_output, performance],
|
325 |
-
)
|
326 |
-
button_clear.click(
|
327 |
-
reset_textbox,
|
328 |
-
[user_text, model_output, performance],
|
329 |
-
[user_text, model_output, performance],
|
330 |
-
)
|
331 |
-
|
332 |
-
if __name__ == "__main__":
|
333 |
-
demo.queue()
|
334 |
-
try:
|
335 |
-
demo.launch(height=800)
|
336 |
-
except Exception:
|
337 |
-
demo.launch(share=True, height=800)
|
338 |
-
|
339 |
-
# Call main function to start Gradio interface
|
340 |
main()
|
|
|
1 |
+
import os
|
2 |
+
from transformers import AutoTokenizer, AutoConfig
|
3 |
+
from optimum.intel.openvino import OVModelForCausalLM
|
4 |
+
from generation_utils import run_generation, estimate_latency, reset_textbox,get_special_token_id
|
5 |
+
from config import SUPPORTED_LLM_MODELS
|
6 |
+
import gradio as gr
|
7 |
+
from threading import Thread
|
8 |
+
from time import perf_counter
|
9 |
+
from typing import List
|
10 |
+
from transformers import AutoTokenizer, TextIteratorStreamer
|
11 |
+
import numpy as np
|
12 |
+
import os
|
13 |
+
from flask import Flask, render_template, redirect, url_for, request, flash
|
14 |
+
from flask_sqlalchemy import SQLAlchemy
|
15 |
+
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
|
16 |
+
from werkzeug.security import generate_password_hash, check_password_hash
|
17 |
+
|
18 |
+
app = Flask(__name__)
|
19 |
+
|
20 |
+
|
21 |
+
if __name__ == '__main__':
|
22 |
+
app.run(debug=True)
|
23 |
+
model_dir = "C:/phi-2/INT8_compressed_weights"
|
24 |
+
print(f"Checking model directory: {model_dir}")
|
25 |
+
print(f"Contents: {os.listdir(model_dir)}") # Check contents of the directory
|
26 |
+
|
27 |
+
print(f"Loading model from {model_dir}")
|
28 |
+
|
29 |
+
|
30 |
+
model_name = "susnato/phi-2"
|
31 |
+
model_configuration = SUPPORTED_LLM_MODELS["phi-2"]
|
32 |
+
ov_config = {"PERFORMANCE_HINT": "LATENCY", "NUM_STREAMS": "1", "CACHE_DIR": ""}
|
33 |
+
|
34 |
+
tok = AutoTokenizer.from_pretrained(model_name)
|
35 |
+
|
36 |
+
ov_model = OVModelForCausalLM.from_pretrained(
|
37 |
+
model_dir,
|
38 |
+
device="CPU",
|
39 |
+
ov_config=ov_config,
|
40 |
+
)
|
41 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
42 |
+
tokenizer_kwargs = model_configuration.get("toeknizer_kwargs", {})
|
43 |
+
# Continue with your tokenizer usage
|
44 |
+
response_key = model_configuration.get("response_key")
|
45 |
+
tokenizer_response_key = None
|
46 |
+
|
47 |
+
def get_special_token_id(tokenizer: AutoTokenizer, key: str) -> int:
|
48 |
+
"""
|
49 |
+
Gets the token ID for a given string that has been added to the tokenizer as a special token.
|
50 |
+
|
51 |
+
Args:
|
52 |
+
tokenizer (PreTrainedTokenizer): the tokenizer
|
53 |
+
key (str): the key to convert to a single token
|
54 |
+
|
55 |
+
Raises:
|
56 |
+
ValueError: if more than one ID was generated
|
57 |
+
|
58 |
+
Returns:
|
59 |
+
int: the token ID for the given key
|
60 |
+
"""
|
61 |
+
token_ids = tokenizer.encode(key)
|
62 |
+
if len(token_ids) > 1:
|
63 |
+
raise ValueError(f"Expected only a single token for '{key}' but found {token_ids}")
|
64 |
+
return token_ids[0]
|
65 |
+
if response_key is not None:
|
66 |
+
tokenizer_response_key = next(
|
67 |
+
(token for token in tokenizer.additional_special_tokens if token.startswith(response_key)),
|
68 |
+
None,
|
69 |
+
)
|
70 |
+
|
71 |
+
end_key_token_id = None
|
72 |
+
if tokenizer_response_key:
|
73 |
+
try:
|
74 |
+
end_key = model_configuration.get("end_key")
|
75 |
+
if end_key:
|
76 |
+
end_key_token_id =get_special_token_id(tokenizer, end_key)
|
77 |
+
# Ensure generation stops once it generates "### End"
|
78 |
+
except ValueError:
|
79 |
+
pass
|
80 |
+
|
81 |
+
prompt_template = model_configuration.get("prompt_template", "{instruction}")
|
82 |
+
end_key_token_id = end_key_token_id or tokenizer.eos_token_id
|
83 |
+
pad_token_id = end_key_token_id or tokenizer.pad_token_id
|
84 |
+
|
85 |
+
def estimate_latency(
|
86 |
+
current_time: float,
|
87 |
+
current_perf_text: str,
|
88 |
+
new_gen_text: str,
|
89 |
+
per_token_time: List[float],
|
90 |
+
num_tokens: int,
|
91 |
+
):
|
92 |
+
"""
|
93 |
+
Helper function for performance estimation
|
94 |
+
|
95 |
+
Parameters:
|
96 |
+
current_time (float): This step time in seconds.
|
97 |
+
current_perf_text (str): Current content of performance UI field.
|
98 |
+
new_gen_text (str): New generated text.
|
99 |
+
per_token_time (List[float]): history of performance from previous steps.
|
100 |
+
num_tokens (int): Total number of generated tokens.
|
101 |
+
|
102 |
+
Returns:
|
103 |
+
update for performance text field
|
104 |
+
update for a total number of tokens
|
105 |
+
"""
|
106 |
+
num_current_toks = len(tokenizer.encode(new_gen_text))
|
107 |
+
num_tokens += num_current_toks
|
108 |
+
per_token_time.append(num_current_toks / current_time)
|
109 |
+
if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:
|
110 |
+
current_bucket = per_token_time[:-10]
|
111 |
+
return (
|
112 |
+
f"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}",
|
113 |
+
num_tokens,
|
114 |
+
)
|
115 |
+
return current_perf_text, num_tokens
|
116 |
+
def run_generation(
|
117 |
+
user_text: str,
|
118 |
+
top_p: float,
|
119 |
+
temperature: float,
|
120 |
+
top_k: int,
|
121 |
+
max_new_tokens: int,
|
122 |
+
perf_text: str,
|
123 |
+
):
|
124 |
+
"""
|
125 |
+
Text generation function
|
126 |
+
|
127 |
+
Parameters:
|
128 |
+
user_text (str): User-provided instruction for a generation.
|
129 |
+
top_p (float): Nucleus sampling. If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for a generation.
|
130 |
+
temperature (float): The value used to module the logits distribution.
|
131 |
+
top_k (int): The number of highest probability vocabulary tokens to keep for top-k-filtering.
|
132 |
+
max_new_tokens (int): Maximum length of generated sequence.
|
133 |
+
perf_text (str): Content of text field for printing performance results.
|
134 |
+
Returns:
|
135 |
+
model_output (str) - model-generated text
|
136 |
+
perf_text (str) - updated perf text filed content
|
137 |
+
"""
|
138 |
+
|
139 |
+
# Prepare input prompt according to model expected template
|
140 |
+
prompt_text = prompt_template.format(instruction=user_text)
|
141 |
+
|
142 |
+
# Tokenize the user text.
|
143 |
+
model_inputs = tokenizer(prompt_text, return_tensors="pt", **tokenizer_kwargs)
|
144 |
+
|
145 |
+
# Start generation on a separate thread, so that we don't block the UI. The text is pulled from the streamer
|
146 |
+
# in the main thread. Adds timeout to the streamer to handle exceptions in the generation thread.
|
147 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
148 |
+
generate_kwargs = dict(
|
149 |
+
model_inputs,
|
150 |
+
streamer=streamer,
|
151 |
+
max_new_tokens=max_new_tokens,
|
152 |
+
do_sample=True,
|
153 |
+
top_p=top_p,
|
154 |
+
temperature=float(temperature),
|
155 |
+
top_k=top_k,
|
156 |
+
eos_token_id=end_key_token_id,
|
157 |
+
pad_token_id=pad_token_id,
|
158 |
+
)
|
159 |
+
t = Thread(target=ov_model.generate, kwargs=generate_kwargs)
|
160 |
+
t.start()
|
161 |
+
|
162 |
+
# Pull the generated text from the streamer, and update the model output.
|
163 |
+
model_output = ""
|
164 |
+
per_token_time = []
|
165 |
+
num_tokens = 0
|
166 |
+
start = perf_counter()
|
167 |
+
for new_text in streamer:
|
168 |
+
current_time = perf_counter() - start
|
169 |
+
model_output += new_text
|
170 |
+
perf_text, num_tokens = estimate_latency(current_time, perf_text, new_text, per_token_time, num_tokens)
|
171 |
+
yield model_output, perf_text
|
172 |
+
start = perf_counter()
|
173 |
+
return model_output, perf_text
|
174 |
+
def reset_textbox(instruction: str, response: str, perf: str):
|
175 |
+
"""
|
176 |
+
Helper function for resetting content of all text fields
|
177 |
+
|
178 |
+
Parameters:
|
179 |
+
instruction (str): Content of user instruction field.
|
180 |
+
response (str): Content of model response field.
|
181 |
+
perf (str): Content of performance info filed
|
182 |
+
|
183 |
+
Returns:
|
184 |
+
empty string for each placeholder
|
185 |
+
"""
|
186 |
+
return "", "", ""
|
187 |
+
|
188 |
+
|
189 |
+
|
190 |
+
examples = [
|
191 |
+
"Give me a recipe for pizza with pineapple",
|
192 |
+
"Write me a tweet about the new OpenVINO release",
|
193 |
+
"Explain the difference between CPU and GPU",
|
194 |
+
"Give five ideas for a great weekend with family",
|
195 |
+
"Do Androids dream of Electric sheep?",
|
196 |
+
"Who is Dolly?",
|
197 |
+
"Please give me advice on how to write resume?",
|
198 |
+
"Name 3 advantages to being a cat",
|
199 |
+
"Write instructions on how to become a good AI engineer",
|
200 |
+
"Write a love letter to my best friend",
|
201 |
+
]
|
202 |
+
|
203 |
+
def main():
|
204 |
+
with gr.Blocks() as demo:
|
205 |
+
gr.Markdown(
|
206 |
+
"# Question Answering with Model and OpenVINO.\n"
|
207 |
+
"Provide instruction which describes a task below or select among predefined examples and model writes response that performs requested task."
|
208 |
+
)
|
209 |
+
|
210 |
+
with gr.Row():
|
211 |
+
with gr.Column(scale=4):
|
212 |
+
user_text = gr.Textbox(
|
213 |
+
placeholder="Write an email about an alpaca that likes flan",
|
214 |
+
label="User instruction",
|
215 |
+
)
|
216 |
+
model_output = gr.Textbox(label="Model response", interactive=False)
|
217 |
+
performance = gr.Textbox(label="Performance", lines=1, interactive=False)
|
218 |
+
with gr.Column(scale=1):
|
219 |
+
button_clear = gr.Button(value="Clear")
|
220 |
+
button_submit = gr.Button(value="Submit")
|
221 |
+
gr.Examples(examples, user_text)
|
222 |
+
with gr.Column(scale=1):
|
223 |
+
max_new_tokens = gr.Slider(
|
224 |
+
minimum=1,
|
225 |
+
maximum=1000,
|
226 |
+
value=256,
|
227 |
+
step=1,
|
228 |
+
interactive=True,
|
229 |
+
label="Max New Tokens",
|
230 |
+
)
|
231 |
+
top_p = gr.Slider(
|
232 |
+
minimum=0.05,
|
233 |
+
maximum=1.0,
|
234 |
+
value=0.92,
|
235 |
+
step=0.05,
|
236 |
+
interactive=True,
|
237 |
+
label="Top-p (nucleus sampling)",
|
238 |
+
)
|
239 |
+
top_k = gr.Slider(
|
240 |
+
minimum=0,
|
241 |
+
maximum=50,
|
242 |
+
value=0,
|
243 |
+
step=1,
|
244 |
+
interactive=True,
|
245 |
+
label="Top-k",
|
246 |
+
)
|
247 |
+
temperature = gr.Slider(
|
248 |
+
minimum=0.1,
|
249 |
+
maximum=5.0,
|
250 |
+
value=0.8,
|
251 |
+
step=0.1,
|
252 |
+
interactive=True,
|
253 |
+
label="Temperature",
|
254 |
+
)
|
255 |
+
|
256 |
+
user_text.submit(
|
257 |
+
run_generation,
|
258 |
+
[user_text, top_p, temperature, top_k, max_new_tokens, performance],
|
259 |
+
[model_output, performance],
|
260 |
+
)
|
261 |
+
button_submit.click(
|
262 |
+
run_generation,
|
263 |
+
[user_text, top_p, temperature, top_k, max_new_tokens, performance],
|
264 |
+
[model_output, performance],
|
265 |
+
)
|
266 |
+
button_clear.click(
|
267 |
+
reset_textbox,
|
268 |
+
[user_text, model_output, performance],
|
269 |
+
[user_text, model_output, performance],
|
270 |
+
)
|
271 |
+
|
272 |
+
if __name__ == "__main__":
|
273 |
+
demo.queue()
|
274 |
+
try:
|
275 |
+
demo.launch(height=800)
|
276 |
+
except Exception:
|
277 |
+
demo.launch(share=True, height=800)
|
278 |
+
|
279 |
+
# Call main function to start Gradio interface
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
280 |
main()
|