File size: 14,859 Bytes
2e96f89 31683bf 2e96f89 31683bf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 | import spaces
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, StoppingCriteria, StoppingCriteriaList
from huggingface_hub import HfApi, login
from threading import Thread
import gc
import os
import shutil
import torch
import psutil
import time
import queue as _queue
import re
# Optional login with token from environment (HF Spaces secret)
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
if HF_TOKEN:
try:
login(token=HF_TOKEN, add_to_git_credential=False)
except Exception:
pass
HF_CACHE_DIR = os.path.expanduser("~/.cache/huggingface/hub")
DEFAULT_MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
MODELS = [
"HuggingFaceTB/SmolLM2-135M-Instruct",
"HuggingFaceTB/SmolLM2-360M-Instruct",
"HuggingFaceTB/SmolLM2-1.7B-Instruct",
"Qwen/Qwen3-0.6B",
"Qwen/Qwen2.5-0.5B",
"Qwen/Qwen2.5-1.5B",
"Qwen/Qwen3-1.7B",
"LiquidAI/LFM2.5-1.2B-Thinking",
"LiquidAI/LFM2.5-1.2B-Instruct",
"LiquidAI/LFM2.5-350M",
"TinyLlama/TinyLlama-1.1B-Chat-v1.0",
"microsoft/Phi-3.5-mini-instruct",
"microsoft/Phi-3-mini-4k-instruct",
"meta-llama/Llama-3.2-1B",
"NousResearch/Hermes-3-Llama-3.1-8B",
"facebook/opt-125m",
"EleutherAI/pythia-160m",
"openai-community/gpt2",
]
THINKING_PATTERNS = [
# (start, end)
("<|begin_of_thought|>", "<|end_of_thought|>"),
("<think>", "</think>"),
("<thinking>", "</thinking>"),
("<|thinking|>", "<|/thinking|>"),
]
class ModelManager:
def __init__(self):
self.model = None
self.tokenizer = None
self.model_id = None
self.stop_generation = False
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.thinking_pair = None # (start, end) or None
model_manager = ModelManager()
def detect_thinking(tokenizer):
if tokenizer is None:
return None
try:
vocab = set()
if hasattr(tokenizer, "get_vocab"):
vocab.update(tokenizer.get_vocab().keys())
if hasattr(tokenizer, "additional_special_tokens"):
vocab.update(tokenizer.additional_special_tokens or [])
if hasattr(tokenizer, "added_tokens_decoder"):
vocab.update(str(v) for v in tokenizer.added_tokens_decoder.values())
for start, end in THINKING_PATTERNS:
if start in vocab or end in vocab:
return (start, end)
except Exception:
pass
return None
class StopOnFlag(StoppingCriteria):
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
return model_manager.stop_generation
_search_cache = {}
def search_hf_models(query):
if not query or len(query.strip()) < 2:
return gr.update(choices=MODELS)
q = query.strip().lower()
if q in _search_cache:
return gr.update(choices=_search_cache[q])
try:
api = HfApi(token=HF_TOKEN)
models = list(api.list_models(search=query, limit=20, sort="downloads"))
model_ids = [m.id for m in models if m.id]
if model_ids:
_search_cache[q] = model_ids
return gr.update(choices=model_ids)
except Exception:
pass
return gr.update(choices=MODELS)
def get_system_stats():
mem = psutil.virtual_memory()
disk = psutil.disk_usage("/")
return (
f"CPU: {psutil.cpu_percent(interval=0.5)}% | "
f"RAM: {round(mem.used / 1024**3, 1)}/{round(mem.total / 1024**3, 1)} GB | "
f"Disk: {round(disk.used / 1024**3, 1)}/{round(disk.total / 1024**3, 1)} GB"
)
def load_model(model_id: str):
model_manager.stop_generation = True
model_manager.model = None
model_manager.tokenizer = None
model_manager.model_id = None
model_manager.thinking_pair = None
yield f"Loading **{model_id}** ...", None
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
try:
tokenizer = AutoTokenizer.from_pretrained(
model_id,
trust_remote_code=True,
token=HF_TOKEN,
)
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model = AutoModelForCausalLM.from_pretrained(
model_id,
trust_remote_code=True,
torch_dtype=dtype,
token=HF_TOKEN,
device_map="auto" if torch.cuda.is_available() else None,
)
if not torch.cuda.is_available():
model = model.to("cpu")
model_manager.tokenizer = tokenizer
model_manager.model = model
model_manager.model_id = model_id
model_manager.thinking_pair = detect_thinking(tokenizer)
tag = " (thinking model detected)" if model_manager.thinking_pair else ""
yield f"Loaded **{model_id}** on {model_manager.device.upper()}{tag}", None
except Exception as e:
yield f"Error loading model: {str(e)}", None
def clean_cache():
if os.path.exists(HF_CACHE_DIR):
shutil.rmtree(HF_CACHE_DIR, ignore_errors=True)
os.makedirs(HF_CACHE_DIR, exist_ok=True)
return "Cache cleaned"
return "Cache directory not found"
def format_chat_prompt(history, system_prompt: str):
"""Build messages list for chat template or fallback."""
messages = []
if system_prompt and system_prompt.strip():
messages.append({"role": "system", "content": system_prompt.strip()})
for user_msg, assistant_msg in history:
messages.append({"role": "user", "content": user_msg})
if assistant_msg is not None:
# Strip any previous thinking markup for the history we feed the model
clean = re.sub(r"<details>.*?</details>", "", assistant_msg, flags=re.DOTALL)
clean = re.sub(r"\*\*Answer:\*\*.*", "", clean, flags=re.DOTALL).strip()
messages.append({"role": "assistant", "content": clean or assistant_msg})
return messages
def parse_thinking(text: str, thinking_pair):
"""Return (thinking_text, answer_text)."""
if not thinking_pair:
return "", text
start, end = thinking_pair
if end in text:
parts = text.split(end, 1)
think = parts[0].replace(start, "").strip()
answer = parts[1].strip()
# also strip solution tags if present
answer = re.sub(r"<\|begin_of_solution\|>|<\|end_of_solution\|>", "", answer).strip()
return think, answer
else:
# still thinking
think = text.replace(start, "").strip()
return think, ""
def render_message(thinking: str, answer: str, show_thinking: bool) -> str:
if not show_thinking or not thinking:
return answer or "..."
# Collapsible thinking block
think_md = "\n".join(f"> {line}" for line in thinking.splitlines()) if thinking else "> _thinking..._"
if answer:
return (
f"<details open>\n<summary><b>Thinking</b></summary>\n\n"
f"{think_md}\n\n</details>\n\n"
f"**Answer:**\n{answer}"
)
return (
f"<details open>\n<summary><b>Thinking</b></summary>\n\n"
f"{think_md}\n\n</details>\n\n*...*"
)
def estimate_duration(history, message, system_prompt, max_tokens, temperature, top_p, show_thinking):
return min(max(int(max_tokens) // 15, 20), 90)
@spaces.GPU(duration=estimate_duration)
def generate(
history: list,
message: str,
system_prompt: str,
max_tokens: int,
temperature: float,
top_p: float,
show_thinking: bool,
):
if model_manager.model is None or model_manager.tokenizer is None:
history = history + [(message, "β οΈ Please load a model first.")]
yield history, ""
return
if not message or not message.strip():
yield history, ""
return
model_manager.stop_generation = False
tokenizer = model_manager.tokenizer
model = model_manager.model
thinking_pair = model_manager.thinking_pair
# Build prompt
messages = format_chat_prompt(history, system_prompt)
messages.append({"role": "user", "content": message.strip()})
try:
if hasattr(tokenizer, "apply_chat_template"):
prompt = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
else:
# simple fallback
parts = []
for m in messages:
role = m["role"].upper()
parts.append(f"[{role}]: {m['content']}")
parts.append("[ASSISTANT]:")
prompt = "\n\n".join(parts)
except Exception:
prompt = message
# Inject thinking start token if model expects it
if thinking_pair and thinking_pair[0] not in prompt:
prompt = prompt + thinking_pair[0] + "\n"
inputs = tokenizer([prompt], return_tensors="pt")
if torch.cuda.is_available():
inputs = {k: v.to("cuda") for k, v in inputs.items()}
model = model.to("cuda")
else:
inputs = {k: v.to("cpu") for k, v in inputs.items()}
model = model.to("cpu")
streamer = TextIteratorStreamer(
tokenizer, timeout=120.0, skip_prompt=True, skip_special_tokens=True
)
gen_kwargs = dict(
**inputs,
streamer=streamer,
max_new_tokens=int(max_tokens),
temperature=float(temperature) if temperature > 0 else 1.0,
top_p=float(top_p),
do_sample=temperature > 0,
pad_token_id=tokenizer.eos_token_id or tokenizer.pad_token_id,
stopping_criteria=StoppingCriteriaList([StopOnFlag()]),
)
thread = Thread(target=model.generate, kwargs=gen_kwargs)
thread.start()
# Add empty assistant turn
history = history + [(message, "")]
full_text = ""
try:
for new_text in streamer:
if model_manager.stop_generation:
break
full_text += new_text
thinking, answer = parse_thinking(full_text, thinking_pair)
rendered = render_message(thinking, answer, show_thinking)
history[-1] = (message, rendered)
yield history, ""
except _queue.Empty:
thinking, answer = parse_thinking(full_text, thinking_pair)
rendered = render_message(thinking, answer, show_thinking)
history[-1] = (message, rendered + "\n\n*(stream timed out)*")
yield history, ""
# Final clean-up pass
thinking, answer = parse_thinking(full_text, thinking_pair)
rendered = render_message(thinking, answer, show_thinking)
history[-1] = (message, rendered)
yield history, ""
def stop_generation():
model_manager.stop_generation = True
return "Stopped"
# βββββββββββββββββββββββββββ UI βββββββββββββββββββββββββββ
css = """
#chatbot { height: 520px; }
.thinking-details summary { cursor: pointer; font-weight: 600; }
"""
with gr.Blocks(title="SLM Chat Β· Thinking", theme=gr.themes.Soft(), css=css) as demo:
gr.Markdown(
"""
# π§ SLM Chat with Thinking
Chat with small language models. Toggle **Show Thinking** to reveal the modelβs reasoning in a separate block.
"""
)
with gr.Row():
with gr.Column(scale=1, min_width=280):
with gr.Group():
model_dd = gr.Dropdown(
choices=MODELS,
value=DEFAULT_MODEL,
label="Model",
allow_custom_value=True,
interactive=True,
)
search_box = gr.Textbox(
label="Search Hugging Face",
placeholder="e.g. qwen thinking, smol, liquidβ¦",
lines=1,
)
with gr.Row():
search_btn = gr.Button("π Search", variant="secondary", size="sm")
load_btn = gr.Button("Load Model", variant="primary")
clean_btn = gr.Button("Clear Cache", variant="stop", size="sm")
status = gr.Markdown("*Ready β load a model to start*")
with gr.Accordion("Generation settings", open=False):
system_prompt = gr.Textbox(
label="System prompt",
value="You are a helpful, concise assistant.",
lines=2,
)
max_tokens = gr.Slider(32, 4096, value=512, step=32, label="Max new tokens")
temperature = gr.Slider(0.0, 1.5, value=0.7, step=0.05, label="Temperature")
top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-p")
show_thinking = gr.Checkbox(
label="Show Thinking",
value=True,
info="Display the modelβs reasoning in a collapsible block",
)
stats = gr.Textbox(label="System", interactive=False, lines=1)
gr.Timer(3).tick(get_system_stats, outputs=stats)
with gr.Column(scale=3):
chatbot = gr.Chatbot(
label="Conversation",
elem_id="chatbot",
height=520,
show_copy_button=True,
render_markdown=True,
)
with gr.Row():
msg = gr.Textbox(
label="Message",
placeholder="Ask anythingβ¦",
scale=5,
container=False,
autofocus=True,
)
submit_btn = gr.Button("Send", variant="primary", scale=1)
stop_btn = gr.Button("Stop", variant="stop", scale=1)
# ββ Events ββ
search_btn.click(search_hf_models, inputs=search_box, outputs=model_dd)
search_box.submit(search_hf_models, inputs=search_box, outputs=model_dd)
load_btn.click(load_model, inputs=model_dd, outputs=[status, chatbot])
clean_btn.click(clean_cache, outputs=status)
submit_event = msg.submit(
generate,
inputs=[chatbot, msg, system_prompt, max_tokens, temperature, top_p, show_thinking],
outputs=[chatbot, msg],
)
submit_btn.click(
generate,
inputs=[chatbot, msg, system_prompt, max_tokens, temperature, top_p, show_thinking],
outputs=[chatbot, msg],
)
stop_btn.click(stop_generation, outputs=status, cancels=[submit_event])
gr.Markdown(
"""
---
**Tip:** Models such as `LiquidAI/LFM2.5-1.2B-Thinking` or any Qwen3 / DeepSeek-R1 style model work best with the thinking toggle.
Add your HF token as a Space secret named `HF_TOKEN` for gated models.
"""
)
if __name__ == "__main__":
demo.queue(default_concurrency_limit=1).launch()
|