Spaces:
Sleeping
Sleeping
File size: 8,643 Bytes
4c4052e 149287a 4c4052e 149287a 4c4052e 94911b5 4c4052e 149287a 4c4052e 149287a 4c4052e 149287a 4c4052e 149287a 4c4052e 149287a 4c4052e 149287a 4c4052e 149287a 4c4052e 149287a 4c4052e 149287a 4c4052e 94911b5 4c4052e 94911b5 4c4052e 94911b5 4c4052e 149287a 4c4052e 149287a 4c4052e 149287a 4c4052e | 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 | """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()
|