DavideTHU commited on
Commit
4c4052e
·
verified ·
1 Parent(s): aaf5ca0

Add Gradio chat interface

Browse files
Files changed (3) hide show
  1. README.md +14 -6
  2. app.py +172 -0
  3. requirements.txt +3 -0
README.md CHANGED
@@ -1,13 +1,21 @@
1
  ---
2
- title: Sparsemind Chat
3
- emoji: 📈
4
- colorFrom: pink
5
- colorTo: red
6
  sdk: gradio
7
  sdk_version: 6.31.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
1
  ---
2
+ title: SparseMindAI Chat
3
+ emoji: 🧠
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 6.31.0
 
8
  app_file: app.py
9
  pinned: false
10
+ models:
11
+ - SparseMindAI/qwen3-8b-24sst-sparse-adamw
12
+ - SparseMindAI/Qwen36-7B-24-sparse
13
+ - SparseMindAI/Qwen-original-model
14
+ - SparseMindAI/Qwen-1to4-sparse-model
15
  ---
16
 
17
+ # SparseMindAI Chat
18
+
19
+ Chat with any model from the [SparseMindAI](https://huggingface.co/SparseMindAI) organization. Pick a model from the dropdown and stream responses; each reply reports TTFT, TPT, total time, token count, and tokens/sec.
20
+
21
+ > **Note:** 7–8B models need a lot of RAM. The free CPU Basic tier (16 GB RAM) will likely run out of memory for these models — use CPU Upgrade (32 GB) or a GPU for best results.
app.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio chat interface (HF Space) that loads models from the SparseMindAI
2
+ Hugging Face organization and streams responses with timing metrics."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import gc
7
+ import os
8
+ import threading
9
+ import time
10
+
11
+ import gradio as gr
12
+ import torch
13
+ from huggingface_hub import HfApi
14
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
15
+
16
+ NAMESPACE = os.getenv("MODELS_NAMESPACE", "SparseMindAI")
17
+
18
+ _load_lock = threading.Lock()
19
+ _models: dict[str, tuple] = {} # repo id -> (model, tokenizer)
20
+
21
+
22
+ def list_models() -> list[str]:
23
+ """List public models under the configured Hugging Face namespace."""
24
+ try:
25
+ api = HfApi()
26
+ return sorted(m.id for m in api.list_models(author=NAMESPACE))
27
+ except Exception: # noqa: BLE001
28
+ return []
29
+
30
+
31
+ def get_model(repo_id: str) -> tuple:
32
+ """Load (and cache) a model from the Hub, evicting other models."""
33
+ with _load_lock:
34
+ if repo_id in _models:
35
+ return _models[repo_id]
36
+ for old in list(_models):
37
+ del _models[old]
38
+ gc.collect()
39
+ if torch.cuda.is_available():
40
+ torch.cuda.empty_cache()
41
+ print(f"Loading {repo_id} ...", flush=True)
42
+ model = AutoModelForCausalLM.from_pretrained(repo_id, torch_dtype="auto")
43
+ tokenizer = AutoTokenizer.from_pretrained(repo_id)
44
+ _models[repo_id] = (model, tokenizer)
45
+ print("Model loaded.", flush=True)
46
+ return model, tokenizer
47
+
48
+
49
+ def apply_chat_template(tokenizer, messages, thinking: bool) -> str:
50
+ """Apply the model's chat template, falling back when the template does
51
+ not support Qwen3's `enable_thinking` flag."""
52
+ kwargs = {"tokenize": False, "add_generation_prompt": True}
53
+ try:
54
+ return tokenizer.apply_chat_template(messages, enable_thinking=thinking, **kwargs)
55
+ except TypeError:
56
+ return tokenizer.apply_chat_template(messages, **kwargs)
57
+
58
+
59
+ def make_timing(start: float, end: float, first: float | None, num_tokens: int) -> dict:
60
+ total = end - start
61
+ ttft = (first - start) if first is not None else total
62
+ return {
63
+ "ttft_ms": round(ttft * 1000, 1),
64
+ "tpt_ms": round((total / num_tokens) * 1000, 1) if num_tokens else 0.0,
65
+ "total_ms": round(total * 1000, 1),
66
+ "num_tokens": num_tokens,
67
+ "tokens_per_sec": round(num_tokens / total, 2) if total > 0 else 0.0,
68
+ }
69
+
70
+
71
+ def format_timing(t: dict | None) -> str:
72
+ if not t:
73
+ return ""
74
+ return (
75
+ f"TTFT **{t['ttft_ms']} ms** · "
76
+ f"TPT **{t['tpt_ms']} ms/tok** · "
77
+ f"total **{t['total_ms'] / 1000:.2f} s** · "
78
+ f"{t['num_tokens']} tok · "
79
+ f"{t['tokens_per_sec']} tok/s"
80
+ )
81
+
82
+
83
+ def respond(message, history, model_name, temperature, top_p, max_tokens, thinking):
84
+ """Streaming chat handler. Yields (input, chatbot, timing) tuples."""
85
+ message = (message or "").strip()
86
+ if not message:
87
+ yield "", history, ""
88
+ return
89
+
90
+ conversation = [m for m in (history or []) if (m.get("content") or "").strip()]
91
+ conversation.append({"role": "user", "content": message})
92
+ history_out = list(conversation) + [{"role": "assistant", "content": ""}]
93
+ yield "", history_out, "generating…"
94
+
95
+ try:
96
+ model, tokenizer = get_model(model_name)
97
+ prompt = apply_chat_template(tokenizer, conversation, thinking=thinking)
98
+ inputs = tokenizer(prompt, return_tensors="pt")
99
+ except Exception as exc: # noqa: BLE001
100
+ history_out[-1] = {"role": "assistant", "content": f"[error] {exc}"}
101
+ yield "", history_out, ""
102
+ return
103
+
104
+ do_sample = float(temperature) > 0
105
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
106
+ gen_kwargs = dict(
107
+ **inputs,
108
+ max_new_tokens=int(max_tokens),
109
+ streamer=streamer,
110
+ do_sample=do_sample,
111
+ temperature=float(temperature) if do_sample else 1.0,
112
+ top_p=float(top_p) if do_sample else 1.0,
113
+ eos_token_id=tokenizer.eos_token_id,
114
+ pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id,
115
+ )
116
+ threading.Thread(target=model.generate, kwargs=gen_kwargs, daemon=True).start()
117
+
118
+ start = time.perf_counter()
119
+ first: float | None = None
120
+ acc = ""
121
+ count = 0
122
+ try:
123
+ for text in streamer:
124
+ if first is None:
125
+ first = time.perf_counter()
126
+ count += 1
127
+ acc += text
128
+ history_out[-1] = {"role": "assistant", "content": acc}
129
+ yield "", history_out, "generating…"
130
+ except Exception as exc: # noqa: BLE001
131
+ acc += f"\n[error] {exc}"
132
+
133
+ timing = make_timing(start, time.perf_counter(), first, count)
134
+ history_out[-1] = {"role": "assistant", "content": acc}
135
+ yield "", history_out, format_timing(timing)
136
+
137
+
138
+ def build_ui():
139
+ model_names = list_models()
140
+ default_model = next(
141
+ (m for m in model_names if "qwen3-8b" in m.lower()),
142
+ model_names[0] if model_names else None,
143
+ )
144
+
145
+ with gr.Blocks(title="SparseMindAI Chat") as demo:
146
+ gr.Markdown("# SparseMindAI Chat")
147
+ chatbot = gr.Chatbot(height=480, show_label=False)
148
+ with gr.Row():
149
+ msg = gr.Textbox(placeholder="Message…", show_label=False, scale=6, container=False)
150
+ send_btn = gr.Button("Send", scale=1, variant="primary")
151
+ with gr.Row():
152
+ model_dd = gr.Dropdown(model_names, value=default_model, label="Model")
153
+ temp = gr.Slider(0, 1.5, value=0.6, step=0.05, label="Temperature")
154
+ top_p = gr.Slider(0, 1, value=0.95, step=0.05, label="Top-p")
155
+ max_tokens = gr.Slider(1, 4096, value=512, step=1, label="Max tokens")
156
+ thinking = gr.Checkbox(value=True, label="Thinking (Qwen3)")
157
+ with gr.Row():
158
+ clear_btn = gr.Button("Clear")
159
+ timing_md = gr.Markdown()
160
+
161
+ inputs = [msg, chatbot, model_dd, temp, top_p, max_tokens, thinking]
162
+ outputs = [msg, chatbot, timing_md]
163
+
164
+ msg.submit(respond, inputs, outputs)
165
+ send_btn.click(respond, inputs, outputs)
166
+ clear_btn.click(lambda: ([], ""), outputs=[chatbot, timing_md])
167
+
168
+ return demo
169
+
170
+
171
+ if __name__ == "__main__":
172
+ build_ui().queue(default_concurrency_limit=1).launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ transformers>=4.51
2
+ torch>=2.2
3
+ huggingface_hub>=0.26