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|>"), ("", ""), ("", ""), ("<|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"
.*?
", "", 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"
\nThinking\n\n" f"{think_md}\n\n
\n\n" f"**Answer:**\n{answer}" ) return ( f"
\nThinking\n\n" f"{think_md}\n\n
\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()