"""Gradio chat interface (HF Space) that loads models from the SparseMindAI Hugging Face organization (repos and buckets) and streams responses with timing metrics.""" from __future__ import annotations import gc import os import threading import time from pathlib import Path import gradio as gr import spaces import torch from huggingface_hub import HfApi from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer NAMESPACE = os.getenv("MODELS_NAMESPACE", "SparseMindAI") BUCKET_CACHE = "/tmp/bucket_models" _load_lock = threading.Lock() _models: dict[str, tuple] = {} # value -> (model, tokenizer) def _bucket_models(api: HfApi, bucket_id: str) -> list[tuple[str, str]]: """Return (label, value) for every model folder inside a bucket.""" out: list[tuple[str, str]] = [] try: tree = list(api.list_bucket_tree(bucket_id, recursive=True)) except Exception: # noqa: BLE001 return out has_config: set[str] = set() for item in tree: if getattr(item, "type", "file") != "file": continue folder, _, name = item.path.rpartition("/") if name == "config.json": has_config.add(folder) for folder in sorted(has_config): label = f"{bucket_id}/{folder}" if folder else bucket_id value = f"bucket/{bucket_id}/{folder}" if folder else f"bucket/{bucket_id}" out.append((label, value)) return out def list_models() -> list[tuple[str, str]]: """List models from the namespace: HF repos plus HF buckets.""" api = HfApi() entries: list[tuple[str, str]] = [] try: for m in api.list_models(author=NAMESPACE): entries.append((m.id, m.id)) except Exception: # noqa: BLE001 pass try: for b in api.list_buckets(namespace=NAMESPACE): entries += _bucket_models(api, b.id) except Exception: # noqa: BLE001 pass entries.sort(key=lambda e: e[0].lower()) return entries def _download_bucket(value: str) -> str: """Download a bucket model folder to local disk and return its path.""" parts = value.split("/", 2) bucket_id = parts[1] prefix = parts[2] if len(parts) > 2 else "" local_dir = Path(BUCKET_CACHE) / bucket_id / (prefix or "_root") if (local_dir / "config.json").exists(): return str(local_dir) api = HfApi() tree = list(api.list_bucket_tree(bucket_id, prefix=prefix or None, recursive=True)) files = [] for item in tree: if getattr(item, "type", "file") != "file": continue rel = item.path if prefix and rel.startswith(prefix + "/"): rel = rel[len(prefix) + 1:] files.append((item.path, str(local_dir / rel))) if not files: raise ValueError(f"No files found in bucket {bucket_id}/{prefix}") local_dir.mkdir(parents=True, exist_ok=True) api.download_bucket_files(bucket_id, files) return str(local_dir) def get_model(value: str) -> tuple: """Load (and cache) a model from a repo or bucket, evicting other models.""" with _load_lock: if value in _models: return _models[value] for old in list(_models): del _models[old] gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() source = _download_bucket(value) if value.startswith("bucket/") else value print(f"Loading {value} ...", flush=True) model = AutoModelForCausalLM.from_pretrained(source, torch_dtype="auto") tokenizer = AutoTokenizer.from_pretrained(source) _models[value] = (model, tokenizer) print("Model loaded.", flush=True) return model, tokenizer def apply_chat_template(tokenizer, messages, thinking: bool) -> str: """Apply the model's chat template, falling back when the template does not support Qwen3's `enable_thinking` flag.""" kwargs = {"tokenize": False, "add_generation_prompt": True} try: return tokenizer.apply_chat_template(messages, enable_thinking=thinking, **kwargs) except TypeError: return tokenizer.apply_chat_template(messages, **kwargs) def make_timing(start: float, end: float, first: float | None, num_tokens: int) -> dict: total = end - start ttft = (first - start) if first is not None else total return { "ttft_ms": round(ttft * 1000, 1), "tpt_ms": round((total / num_tokens) * 1000, 1) if num_tokens else 0.0, "total_ms": round(total * 1000, 1), "num_tokens": num_tokens, "tokens_per_sec": round(num_tokens / total, 2) if total > 0 else 0.0, } def format_timing(t: dict | None) -> str: if not t: return "" return ( f"TTFT **{t['ttft_ms']} ms** · " f"TPT **{t['tpt_ms']} ms/tok** · " f"total **{t['total_ms'] / 1000:.2f} s** · " f"{t['num_tokens']} tok · " f"{t['tokens_per_sec']} tok/s" ) @spaces.GPU(duration=180) def respond(message, history, model_name, temperature, top_p, max_tokens, thinking): """Streaming chat handler. Yields (input, chatbot, timing) tuples.""" message = (message or "").strip() if not message: yield "", history, "" return conversation = [m for m in (history or []) if (m.get("content") or "").strip()] conversation.append({"role": "user", "content": message}) history_out = list(conversation) + [{"role": "assistant", "content": ""}] yield "", history_out, "generating…" try: model, tokenizer = get_model(model_name) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) prompt = apply_chat_template(tokenizer, conversation, thinking=thinking) inputs = tokenizer(prompt, return_tensors="pt").to(device) except Exception as exc: # noqa: BLE001 history_out[-1] = {"role": "assistant", "content": f"[error] {exc}"} yield "", history_out, "" return do_sample = float(temperature) > 0 streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) gen_kwargs = dict( **inputs, max_new_tokens=int(max_tokens), streamer=streamer, do_sample=do_sample, temperature=float(temperature) if do_sample else 1.0, top_p=float(top_p) if do_sample else 1.0, eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id, ) threading.Thread(target=model.generate, kwargs=gen_kwargs, daemon=True).start() start = time.perf_counter() first: float | None = None acc = "" count = 0 try: for text in streamer: if first is None: first = time.perf_counter() count += 1 acc += text history_out[-1] = {"role": "assistant", "content": acc} yield "", history_out, "generating…" except Exception as exc: # noqa: BLE001 acc += f"\n[error] {exc}" timing = make_timing(start, time.perf_counter(), first, count) history_out[-1] = {"role": "assistant", "content": acc} yield "", history_out, format_timing(timing) def build_ui(): choices = list_models() default_model = next( (v for label, v in choices if "qwen3-8b" in label.lower()), choices[0][1] if choices else None, ) with gr.Blocks(title="SparseMindAI Chat") as demo: gr.Markdown("# SparseMindAI Chat") chatbot = gr.Chatbot(height=480, show_label=False) with gr.Row(): msg = gr.Textbox(placeholder="Message…", show_label=False, scale=6, container=False) send_btn = gr.Button("Send", scale=1, variant="primary") with gr.Row(): model_dd = gr.Dropdown(choices, value=default_model, label="Model") temp = gr.Slider(0, 1.5, value=0.6, step=0.05, label="Temperature") top_p = gr.Slider(0, 1, value=0.95, step=0.05, label="Top-p") max_tokens = gr.Slider(1, 4096, value=512, step=1, label="Max tokens") thinking = gr.Checkbox(value=True, label="Thinking (Qwen3)") with gr.Row(): clear_btn = gr.Button("Clear") timing_md = gr.Markdown() inputs = [msg, chatbot, model_dd, temp, top_p, max_tokens, thinking] outputs = [msg, chatbot, timing_md] msg.submit(respond, inputs, outputs) send_btn.click(respond, inputs, outputs) clear_btn.click(lambda: ([], ""), outputs=[chatbot, timing_md]) return demo if __name__ == "__main__": build_ui().queue(default_concurrency_limit=1).launch()