Spaces:
Running on Zero
Running on Zero
Commit ·
fbdeb92
1
Parent(s): bd03c92
Generalize thinking
Browse files
app.py
CHANGED
|
@@ -73,6 +73,13 @@ LANGUAGES = [
|
|
| 73 |
ACTIVE_SESSIONS = {}
|
| 74 |
SESSION_TIMEOUT = 60
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
def live_count(request: gr.Request):
|
| 78 |
current_time = time.time()
|
|
@@ -91,11 +98,29 @@ class ModelManager:
|
|
| 91 |
self.model_id = None
|
| 92 |
self.stop_generation = False
|
| 93 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 94 |
|
| 95 |
|
| 96 |
model_manager = ModelManager()
|
| 97 |
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
class StopOnFlag(StoppingCriteria):
|
| 100 |
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 101 |
return model_manager.stop_generation
|
|
@@ -154,7 +179,9 @@ def load_new_model(model_id):
|
|
| 154 |
model_manager.tokenizer = tokenizer
|
| 155 |
model_manager.model = model
|
| 156 |
model_manager.model_id = model_id
|
| 157 |
-
|
|
|
|
|
|
|
| 158 |
except Exception as e:
|
| 159 |
yield f"Error loading model: {str(e)}"
|
| 160 |
|
|
@@ -231,24 +258,25 @@ def run_inference(mode, prompt, system_prompt, context, src_lang, tgt_lang,
|
|
| 231 |
max_tokens, temperature, top_k, top_p, rep_penalty,
|
| 232 |
ngram_size, do_sample, gpu):
|
| 233 |
formatted = format_prompt(mode, prompt, system_prompt, context, src_lang, tgt_lang)
|
|
|
|
| 234 |
if gpu:
|
| 235 |
try:
|
| 236 |
-
yield from run_inference_gpu(formatted, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample)
|
| 237 |
except Exception as e:
|
| 238 |
yield f"GPU error: {e}\n\nClick **Generate** to retry.", "GPU Unavailable"
|
| 239 |
else:
|
| 240 |
-
yield from run_inference_raw(formatted, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample)
|
| 241 |
|
| 242 |
|
| 243 |
@spaces.GPU(duration=estimate_duration)
|
| 244 |
-
def run_inference_gpu(user_prompt, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample):
|
| 245 |
if model_manager.model is not None:
|
| 246 |
model_manager.model = model_manager.model.to("cuda")
|
| 247 |
|
| 248 |
-
yield from run_inference_raw(user_prompt, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample, use_cuda=True)
|
| 249 |
|
| 250 |
|
| 251 |
-
def run_inference_raw(user_prompt, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample, use_cuda=False):
|
| 252 |
if model_manager.model is None or model_manager.tokenizer is None:
|
| 253 |
yield "Please load a model first.", "Model not loaded"
|
| 254 |
return
|
|
@@ -257,12 +285,10 @@ def run_inference_raw(user_prompt, max_tokens, temperature, top_k, top_p, rep_pe
|
|
| 257 |
|
| 258 |
tokenizer = model_manager.tokenizer
|
| 259 |
model = model_manager.model
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
is_supra_reasoning = "Supra-50M-Reasoning" in model_id if model_id else False
|
| 263 |
|
| 264 |
-
if
|
| 265 |
-
user_prompt += "
|
| 266 |
|
| 267 |
inputs = tokenizer([user_prompt], return_tensors="pt")
|
| 268 |
|
|
@@ -295,8 +321,11 @@ def run_inference_raw(user_prompt, max_tokens, temperature, top_k, top_p, rep_pe
|
|
| 295 |
thread = Thread(target=model.generate, kwargs=generate_kwargs)
|
| 296 |
thread.start()
|
| 297 |
|
| 298 |
-
if
|
| 299 |
-
base_display =
|
|
|
|
|
|
|
|
|
|
| 300 |
generated_text = ""
|
| 301 |
else:
|
| 302 |
base_display = ""
|
|
@@ -314,14 +343,21 @@ def run_inference_raw(user_prompt, max_tokens, temperature, top_k, top_p, rep_pe
|
|
| 314 |
|
| 315 |
display_text = generated_text
|
| 316 |
|
| 317 |
-
if
|
|
|
|
| 318 |
display_text = display_text.replace("<s>", "").replace("</s>", "")
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
display_text = display_text.replace("<|
|
| 322 |
-
display_text = display_text.replace("<|end_of_thought|>", "\n\n")
|
| 323 |
-
display_text = display_text.replace("<|begin_of_solution|>", "Final Answer:\n\n")
|
| 324 |
display_text = display_text.replace("<|end_of_solution|>", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
device_label = "CUDA" if use_cuda else "CPU"
|
| 327 |
yield base_display + display_text, f"Speed: {tps:.2f} tokens/sec ({device_label})"
|
|
@@ -335,7 +371,17 @@ def clean_cache():
|
|
| 335 |
return "Cache directory not found."
|
| 336 |
|
| 337 |
|
| 338 |
-
with gr.Blocks(title="SLM Model Tester"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
|
| 340 |
gr.Markdown("# SLM Model Evaluation Hub")
|
| 341 |
|
|
@@ -381,7 +427,7 @@ with gr.Blocks(title="SLM Model Tester") as app:
|
|
| 381 |
label="Prompt",
|
| 382 |
value="Once upon a time in a digital kingdom,",
|
| 383 |
placeholder="Enter your prompt here...",
|
| 384 |
-
lines=
|
| 385 |
)
|
| 386 |
|
| 387 |
context_input = gr.Textbox(
|
|
@@ -400,9 +446,7 @@ with gr.Blocks(title="SLM Model Tester") as app:
|
|
| 400 |
|
| 401 |
run_btn = gr.Button("Generate", variant="primary", size="lg")
|
| 402 |
status_output = gr.Markdown("*Ready*")
|
| 403 |
-
output_text = gr.
|
| 404 |
-
label="Output", lines=15, buttons=["copy"], autoscroll=True
|
| 405 |
-
)
|
| 406 |
|
| 407 |
search_btn.click(
|
| 408 |
fn=search_hf_models,
|
|
|
|
| 73 |
ACTIVE_SESSIONS = {}
|
| 74 |
SESSION_TIMEOUT = 60
|
| 75 |
|
| 76 |
+
THINKING_PATTERNS = [
|
| 77 |
+
# (start_token, end_token, thinking_label, answer_label)
|
| 78 |
+
("<|begin_of_thought|>", "<|end_of_thought|>", "Thinking Process:", "Final Answer:"),
|
| 79 |
+
("<think>", "</think>", "Thinking:", "Answer:"),
|
| 80 |
+
("<thinking>", "</thinking>", "Thinking:", "Answer:"),
|
| 81 |
+
]
|
| 82 |
+
|
| 83 |
|
| 84 |
def live_count(request: gr.Request):
|
| 85 |
current_time = time.time()
|
|
|
|
| 98 |
self.model_id = None
|
| 99 |
self.stop_generation = False
|
| 100 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 101 |
+
self.thinking = None # (start, end, think_label, answer_label) or None
|
| 102 |
|
| 103 |
|
| 104 |
model_manager = ModelManager()
|
| 105 |
|
| 106 |
|
| 107 |
+
def detect_thinking(tokenizer):
|
| 108 |
+
if tokenizer is None:
|
| 109 |
+
return None
|
| 110 |
+
try:
|
| 111 |
+
special = set()
|
| 112 |
+
if hasattr(tokenizer, "additional_special_tokens"):
|
| 113 |
+
special.update(tokenizer.additional_special_tokens)
|
| 114 |
+
if hasattr(tokenizer, "added_tokens_decoder"):
|
| 115 |
+
special.update(str(v) for v in tokenizer.added_tokens_decoder.values())
|
| 116 |
+
for start, end, think_label, answer_label in THINKING_PATTERNS:
|
| 117 |
+
if start in special or start in tokenizer.get_vocab():
|
| 118 |
+
return (start, end, think_label, answer_label)
|
| 119 |
+
except Exception:
|
| 120 |
+
pass
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
class StopOnFlag(StoppingCriteria):
|
| 125 |
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 126 |
return model_manager.stop_generation
|
|
|
|
| 179 |
model_manager.tokenizer = tokenizer
|
| 180 |
model_manager.model = model
|
| 181 |
model_manager.model_id = model_id
|
| 182 |
+
model_manager.thinking = detect_thinking(tokenizer)
|
| 183 |
+
tag = " (thinking model)" if model_manager.thinking else ""
|
| 184 |
+
yield f"Loaded **{model_id}** on {model_manager.device.upper()}{tag}"
|
| 185 |
except Exception as e:
|
| 186 |
yield f"Error loading model: {str(e)}"
|
| 187 |
|
|
|
|
| 258 |
max_tokens, temperature, top_k, top_p, rep_penalty,
|
| 259 |
ngram_size, do_sample, gpu):
|
| 260 |
formatted = format_prompt(mode, prompt, system_prompt, context, src_lang, tgt_lang)
|
| 261 |
+
show_prompt = mode == "Completion"
|
| 262 |
if gpu:
|
| 263 |
try:
|
| 264 |
+
yield from run_inference_gpu(formatted, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample, show_prompt)
|
| 265 |
except Exception as e:
|
| 266 |
yield f"GPU error: {e}\n\nClick **Generate** to retry.", "GPU Unavailable"
|
| 267 |
else:
|
| 268 |
+
yield from run_inference_raw(formatted, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample, show_prompt=show_prompt)
|
| 269 |
|
| 270 |
|
| 271 |
@spaces.GPU(duration=estimate_duration)
|
| 272 |
+
def run_inference_gpu(user_prompt, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample, show_prompt=False):
|
| 273 |
if model_manager.model is not None:
|
| 274 |
model_manager.model = model_manager.model.to("cuda")
|
| 275 |
|
| 276 |
+
yield from run_inference_raw(user_prompt, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample, use_cuda=True, show_prompt=show_prompt)
|
| 277 |
|
| 278 |
|
| 279 |
+
def run_inference_raw(user_prompt, max_tokens, temperature, top_k, top_p, rep_penalty, ngram_size, do_sample, use_cuda=False, show_prompt=False):
|
| 280 |
if model_manager.model is None or model_manager.tokenizer is None:
|
| 281 |
yield "Please load a model first.", "Model not loaded"
|
| 282 |
return
|
|
|
|
| 285 |
|
| 286 |
tokenizer = model_manager.tokenizer
|
| 287 |
model = model_manager.model
|
| 288 |
+
thinking = model_manager.thinking
|
|
|
|
|
|
|
| 289 |
|
| 290 |
+
if thinking and thinking[0] not in user_prompt:
|
| 291 |
+
user_prompt += thinking[0] + "\n"
|
| 292 |
|
| 293 |
inputs = tokenizer([user_prompt], return_tensors="pt")
|
| 294 |
|
|
|
|
| 321 |
thread = Thread(target=model.generate, kwargs=generate_kwargs)
|
| 322 |
thread.start()
|
| 323 |
|
| 324 |
+
if thinking:
|
| 325 |
+
base_display = ""
|
| 326 |
+
generated_text = ""
|
| 327 |
+
elif show_prompt:
|
| 328 |
+
base_display = user_prompt
|
| 329 |
generated_text = ""
|
| 330 |
else:
|
| 331 |
base_display = ""
|
|
|
|
| 343 |
|
| 344 |
display_text = generated_text
|
| 345 |
|
| 346 |
+
if thinking:
|
| 347 |
+
start_tok, end_tok, think_label, answer_label = thinking
|
| 348 |
display_text = display_text.replace("<s>", "").replace("</s>", "")
|
| 349 |
+
display_text = display_text.replace(start_tok, "")
|
| 350 |
+
display_text = display_text.replace(end_tok, "")
|
| 351 |
+
display_text = display_text.replace("<|begin_of_solution|>", "")
|
|
|
|
|
|
|
| 352 |
display_text = display_text.replace("<|end_of_solution|>", "")
|
| 353 |
+
if end_tok in generated_text:
|
| 354 |
+
parts = generated_text.split(end_tok, 1)
|
| 355 |
+
think_part = parts[0].replace(start_tok, "").strip()
|
| 356 |
+
answer_part = parts[1].replace("<|begin_of_solution|>", "").replace("<|end_of_solution|>", "").strip()
|
| 357 |
+
display_text = f"> _{think_part}_\n\n**{answer_part}**"
|
| 358 |
+
else:
|
| 359 |
+
think_part = generated_text.replace(start_tok, "").replace("<s>", "").replace("</s>", "").strip()
|
| 360 |
+
display_text = f"> _{think_part}_"
|
| 361 |
|
| 362 |
device_label = "CUDA" if use_cuda else "CPU"
|
| 363 |
yield base_display + display_text, f"Speed: {tps:.2f} tokens/sec ({device_label})"
|
|
|
|
| 371 |
return "Cache directory not found."
|
| 372 |
|
| 373 |
|
| 374 |
+
with gr.Blocks(title="SLM Model Tester", css="""
|
| 375 |
+
#output-box {
|
| 376 |
+
background: var(--background-fill-secondary);
|
| 377 |
+
border: 1px solid var(--border-color-primary);
|
| 378 |
+
border-radius: var(--radius-lg);
|
| 379 |
+
padding: 16px;
|
| 380 |
+
min-height: 200px;
|
| 381 |
+
font-size: 15px;
|
| 382 |
+
line-height: 1.6;
|
| 383 |
+
}
|
| 384 |
+
""") as app:
|
| 385 |
|
| 386 |
gr.Markdown("# SLM Model Evaluation Hub")
|
| 387 |
|
|
|
|
| 427 |
label="Prompt",
|
| 428 |
value="Once upon a time in a digital kingdom,",
|
| 429 |
placeholder="Enter your prompt here...",
|
| 430 |
+
lines=3
|
| 431 |
)
|
| 432 |
|
| 433 |
context_input = gr.Textbox(
|
|
|
|
| 446 |
|
| 447 |
run_btn = gr.Button("Generate", variant="primary", size="lg")
|
| 448 |
status_output = gr.Markdown("*Ready*")
|
| 449 |
+
output_text = gr.Markdown(label="Output", elem_id="output-box")
|
|
|
|
|
|
|
| 450 |
|
| 451 |
search_btn.click(
|
| 452 |
fn=search_hf_models,
|