AlexWortega commited on
Commit
765b90c
·
verified ·
1 Parent(s): 594354e

Hermes SIQ-1-35B on ZeroGPU (llama-cpp-python recipe)

Browse files
Files changed (3) hide show
  1. README.md +34 -7
  2. app.py +349 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,13 +1,40 @@
1
  ---
2
- title: Hermes Agent Zerogpu
3
- emoji: 🌍
4
- colorFrom: blue
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 6.18.0
8
- python_version: '3.13'
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: Hermes · SIQ-1-35B (ZeroGPU)
3
+ emoji: 🪽
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 6.14.0
8
+ python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
+ models:
12
+ - AlexWortega/SIQ-1-35B
13
  ---
14
 
15
+ # Hermes · SIQ-1-35B on ZeroGPU
16
+
17
+ Chat with **[AlexWortega/SIQ-1-35B](https://huggingface.co/AlexWortega/SIQ-1-35B)**
18
+ (Qwen3.x MoE 35B-A3B, agentic) served as a **GGUF `Q4_K_M`** via
19
+ `llama-cpp-python` on **ZeroGPU**.
20
+
21
+ Built by copying the proven ZeroGPU recipe from
22
+ [`AlexWortega/my_pi_agent`](https://huggingface.co/spaces/AlexWortega/my_pi_agent):
23
+ the cu124 `llama-cpp-python` wheel + a CUDA-lib preload + a lazy
24
+ `Llama(n_gpu_layers=-1)` created **inside** the `@spaces.GPU` call. This is why it
25
+ works where vLLM/SGLang don't — those initialize CUDA in the main process, which
26
+ ZeroGPU forbids (vLLM issue #3510).
27
+
28
+ Panels: **🖥 Preview** (live HTML/JS artifact), **🧩 Code**, **🧠 Reasoning**
29
+ (`<think>…</think>`), **📝 Raw**.
30
+
31
+ ## Required settings
32
+ - **Hardware:** ZeroGPU (`zero-a10g`, H200/70 GB) — fits the ~21 GB Q4 quant with room for KV.
33
+ - **Secret `HF_TOKEN`:** the model repo is **private**, so the GGUF download needs your token.
34
+
35
+ ## Tunable variables
36
+ | var | default | meaning |
37
+ |-----|---------|---------|
38
+ | `GGUF_REPO` | `AlexWortega/SIQ-1-35B` | GGUF repo |
39
+ | `GGUF_FILE` | `gguf/SIQ-1-35B.Q4_K_M.gguf` | quant to load (non-MTP) |
40
+ | `N_CTX` | `16384` | context window |
app.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import json
4
+ import time
5
+ import uuid
6
+ import datetime
7
+ import html as _html
8
+ from pathlib import Path
9
+
10
+ # --- Preload CUDA runtime libs before importing llama_cpp ---
11
+ # The cu124 llama-cpp-python wheel's libllama.so needs libcudart.so.12 /
12
+ # libcublas at import time. On ZeroGPU those aren't on the default loader
13
+ # path, so we dlopen the pip-provided nvidia libs (cudart first) globally.
14
+ import ctypes
15
+ import glob
16
+ import site
17
+
18
+
19
+ def _preload_cuda():
20
+ bases = set(site.getsitepackages())
21
+ try:
22
+ bases.add(site.getusersitepackages())
23
+ except Exception:
24
+ pass
25
+ libs = []
26
+ for base in bases:
27
+ libs += glob.glob(os.path.join(base, "nvidia", "*", "lib", "*.so*"))
28
+ priority = {"cuda_runtime": 0, "cublas": 1}
29
+
30
+ def _key(p):
31
+ for name, rank in priority.items():
32
+ if name in p:
33
+ return rank
34
+ return 2
35
+
36
+ for so in sorted(set(libs), key=_key):
37
+ try:
38
+ ctypes.CDLL(so, mode=ctypes.RTLD_GLOBAL)
39
+ except OSError:
40
+ pass
41
+
42
+
43
+ _preload_cuda()
44
+
45
+ import gradio as gr
46
+ import spaces
47
+ from huggingface_hub import hf_hub_download
48
+ from llama_cpp import Llama
49
+
50
+ # ---- feedback logging (JSONL, synced to a private HF dataset) ----
51
+ # NB: huggingface_hub.CommitScheduler's background thread breaks under ZeroGPU's
52
+ # process forking ("Invalid file descriptor: -1"), so we append locally and push
53
+ # the file synchronously from the main process instead.
54
+ from huggingface_hub import HfApi
55
+
56
+ FEEDBACK_REPO = os.environ.get("FEEDBACK_REPO", "")
57
+ _FB_DIR = Path("feedback")
58
+ _FB_DIR.mkdir(exist_ok=True)
59
+ _FB_FILE = _FB_DIR / f"log_{uuid.uuid4().hex}.jsonl"
60
+ _FB_PATH_IN_REPO = f"data/{_FB_FILE.name}"
61
+ _HF_TOKEN = os.environ.get("HF_TOKEN")
62
+ _api = HfApi(token=_HF_TOKEN) if (_HF_TOKEN and FEEDBACK_REPO) else None
63
+ print("feedback ->", FEEDBACK_REPO if _api else "(local only, no HF_TOKEN)", flush=True)
64
+
65
+
66
+ def _log(record):
67
+ record = {
68
+ "ts": datetime.datetime.now(datetime.timezone.utc).isoformat(),
69
+ **record,
70
+ }
71
+ try:
72
+ with _FB_FILE.open("a", encoding="utf-8") as f:
73
+ f.write(json.dumps(record, ensure_ascii=False) + "\n")
74
+ except Exception as e: # noqa: BLE001
75
+ print("local log failed:", repr(e)[:120], flush=True)
76
+ return
77
+ if _api is not None:
78
+ try:
79
+ _api.upload_file(
80
+ path_or_fileobj=str(_FB_FILE),
81
+ path_in_repo=_FB_PATH_IN_REPO,
82
+ repo_id=FEEDBACK_REPO,
83
+ repo_type="dataset",
84
+ commit_message="feedback log",
85
+ )
86
+ except Exception as e: # noqa: BLE001
87
+ print("dataset upload failed:", repr(e)[:160], flush=True)
88
+
89
+ # ---- model (GGUF pulled from the Hub at startup, runs on ZeroGPU) ----
90
+ GGUF_REPO = os.environ.get("GGUF_REPO", "AlexWortega/SIQ-1-35B")
91
+ GGUF_FILE = os.environ.get("GGUF_FILE", "gguf/SIQ-1-35B.Q4_K_M.gguf")
92
+ N_CTX = int(os.environ.get("N_CTX", "16384"))
93
+
94
+ print("Downloading GGUF from the Hub ...", flush=True)
95
+ MODEL_PATH = hf_hub_download(GGUF_REPO, GGUF_FILE)
96
+ print("GGUF ready at", MODEL_PATH, flush=True)
97
+
98
+ _LLM = None
99
+
100
+
101
+ def _get_llm():
102
+ global _LLM
103
+ if _LLM is None:
104
+ _LLM = Llama(
105
+ model_path=MODEL_PATH,
106
+ n_gpu_layers=-1,
107
+ n_ctx=N_CTX,
108
+ verbose=False,
109
+ )
110
+ return _LLM
111
+
112
+
113
+ _THINK = re.compile(r"<think>(.*?)</think>", re.DOTALL)
114
+ _CODE_BLOCK = re.compile(r"```([\w+-]*)\s*\n(.*?)```", re.DOTALL)
115
+
116
+
117
+ def _split(text):
118
+ """Return (clean_answer, thinking). Handles an unterminated <think>."""
119
+ think_parts = _THINK.findall(text)
120
+ answer = _THINK.sub("", text)
121
+ if "<think>" in text and "</think>" not in text:
122
+ i = text.index("<think>")
123
+ think_parts.append(text[i + len("<think>"):])
124
+ answer = text[:i]
125
+ thinking = "\n\n".join(p.strip() for p in think_parts).strip()
126
+ return answer.strip(), thinking
127
+
128
+
129
+ def _extract_doc(answer):
130
+ """Assemble a single self-contained HTML document from the answer's
131
+ HTML/CSS/JS code blocks, to render in the preview iframe."""
132
+ htmls, csss, jss = [], [], []
133
+ for lang, body in _CODE_BLOCK.findall(answer):
134
+ l = (lang or "").lower().strip()
135
+ b = body.strip()
136
+ if not b:
137
+ continue
138
+ low = b.lower()
139
+ if l in ("html", "htm") or "<!doctype" in low or "<html" in low or "<body" in low:
140
+ htmls.append(b)
141
+ elif l == "css":
142
+ csss.append(b)
143
+ elif l in ("js", "javascript"):
144
+ jss.append(b)
145
+ elif l == "" and "<" in b and ">" in b:
146
+ htmls.append(b)
147
+ doc = htmls[0] if htmls else ""
148
+ if not doc and (csss or jss):
149
+ doc = "<!DOCTYPE html><html><head><meta charset='utf-8'></head><body></body></html>"
150
+ if not doc:
151
+ return ""
152
+ if "<html" not in doc.lower() and "<!doctype" not in doc.lower():
153
+ doc = (
154
+ "<!DOCTYPE html><html><head><meta charset='utf-8'></head><body>\n"
155
+ + doc
156
+ + "\n</body></html>"
157
+ )
158
+ if csss and "<style" not in doc.lower():
159
+ style = "<style>\n" + "\n".join(csss) + "\n</style>"
160
+ doc = doc.replace("</head>", style + "</head>", 1) if "</head>" in doc else style + doc
161
+ if jss and "<script" not in doc.lower():
162
+ script = "<script>\n" + "\n".join(jss) + "\n</script>"
163
+ doc = doc.replace("</body>", script + "</body>", 1) if "</body>" in doc else doc + script
164
+ return doc
165
+
166
+
167
+ _EMPTY_PREVIEW = (
168
+ "<div style='padding:1rem;color:#888;font-family:sans-serif'>"
169
+ "The preview appears here once the model returns HTML/CSS/JS in a code block.</div>"
170
+ )
171
+ _NO_REASONING = "(no <think> reasoning in this turn)"
172
+
173
+
174
+ def _iframe(doc):
175
+ if not doc or not doc.strip():
176
+ return _EMPTY_PREVIEW
177
+ esc = _html.escape(doc, quote=True)
178
+ return (
179
+ f'<iframe srcdoc="{esc}" sandbox="allow-scripts allow-modals allow-forms allow-popups" '
180
+ 'style="width:100%;height:540px;border:1px solid #ddd;border-radius:8px;background:white"></iframe>'
181
+ )
182
+
183
+
184
+ DEFAULT_SYS = (
185
+ "You are Hermes, a capable agentic coding assistant powered by SIQ-1-35B. Reason briefly inside "
186
+ "<think> ... </think>, then answer. When the user asks for a web app, page, "
187
+ "game or visual UI, output ONE complete, self-contained HTML file with inline "
188
+ "CSS and JavaScript inside a single ```html code block (no external files or "
189
+ "CDNs unless necessary). Keep the thinking short so you have room for the code."
190
+ )
191
+
192
+
193
+ @spaces.GPU(duration=180)
194
+ def _stream(message, history, system_prompt, temperature, max_tokens):
195
+ llm = _get_llm()
196
+ msgs = []
197
+ if system_prompt and system_prompt.strip():
198
+ msgs.append({"role": "system", "content": system_prompt.strip()})
199
+ for m in history:
200
+ if m.get("role") in ("user", "assistant") and m.get("content"):
201
+ msgs.append({"role": m["role"], "content": m["content"]})
202
+ msgs.append({"role": "user", "content": message})
203
+
204
+ raw = ""
205
+ for chunk in llm.create_chat_completion(
206
+ messages=msgs,
207
+ max_tokens=int(max_tokens),
208
+ temperature=float(temperature),
209
+ stream=True,
210
+ ):
211
+ delta = chunk["choices"][0]["delta"].get("content", "")
212
+ if not delta:
213
+ continue
214
+ raw += delta
215
+ answer, thinking = _split(raw)
216
+ yield (answer if answer else "…"), raw, thinking
217
+
218
+
219
+ def respond(message, history, system_prompt, temperature, max_tokens, meta):
220
+ meta = meta or []
221
+ if not message or not message.strip():
222
+ yield history or [], "", "", _NO_REASONING, "", _EMPTY_PREVIEW, meta
223
+ return
224
+ history = (history or []) + [
225
+ {"role": "user", "content": message},
226
+ {"role": "assistant", "content": ""},
227
+ ]
228
+ prior = history[:-2]
229
+ answer = raw = thinking = ""
230
+ for answer, raw, thinking in _stream(
231
+ message, prior, system_prompt, temperature, max_tokens
232
+ ):
233
+ history[-1]["content"] = answer
234
+ code = _extract_doc(answer)
235
+ # live-update chat / raw / reasoning / code; keep preview steady until done
236
+ yield history, "", raw, (thinking or _NO_REASONING), code, _EMPTY_PREVIEW, meta
237
+ doc = _extract_doc(answer)
238
+ history[-1]["content"] = answer
239
+ turn_id = uuid.uuid4().hex
240
+ record = {
241
+ "turn_id": turn_id,
242
+ "event": "generation",
243
+ "user": message,
244
+ "answer": answer,
245
+ "reasoning": thinking,
246
+ "code": doc,
247
+ "reaction": None,
248
+ }
249
+ meta = meta + [record]
250
+ yield history, "", raw, (thinking or _NO_REASONING), doc, _iframe(doc), meta
251
+ _log(record) # after yield: upload doesn't block the visible response
252
+
253
+
254
+ def on_like(meta, evt: gr.LikeData):
255
+ reaction = "like" if evt.liked else "dislike"
256
+ turn = (evt.index // 2) if isinstance(evt.index, int) else 0
257
+ base = dict(meta[turn]) if (meta and 0 <= turn < len(meta)) else {}
258
+ _log(
259
+ {
260
+ "turn_id": base.get("turn_id"),
261
+ "event": "feedback",
262
+ "reaction": reaction,
263
+ "user": base.get("user"),
264
+ "answer": base.get("answer"),
265
+ "reasoning": base.get("reasoning"),
266
+ "code": base.get("code"),
267
+ }
268
+ )
269
+ emoji = "👍" if evt.liked else "👎"
270
+ return f"Saved feedback {emoji} (turn {turn + 1})"
271
+
272
+
273
+ CARD = """
274
+ <div style="display:flex;gap:14px;align-items:center;flex-wrap:wrap;
275
+ border:1px solid var(--border-color-primary,#444);border-radius:12px;
276
+ padding:14px 16px;background:var(--block-background-fill,transparent);
277
+ color:var(--body-text-color,inherit)">
278
+ <div style="font-size:34px">🪽</div>
279
+ <div style="flex:1;min-width:260px">
280
+ <div style="font-size:19px;font-weight:700;color:var(--body-text-color,inherit)">Hermes · SIQ-1-35B</div>
281
+ <div style="color:var(--body-text-color-subdued,#9aa);font-size:13px;margin-top:2px">
282
+ <b>SIQ-1-35B</b> · Qwen3.x MoE 35B-A3B (agentic) ·
283
+ GGUF <code>Q4_K_M</code> · runs on <b>ZeroGPU</b> via <code>llama-cpp-python</code>
284
+ </div>
285
+ <div style="color:var(--body-text-color-subdued,#9aa);font-size:13px;margin-top:6px">
286
+ 💬 chat &nbsp;·&nbsp; 🧠 shows the model's reasoning &nbsp;·&nbsp;
287
+ 🖥 live HTML/JS preview (Artifacts-style) &nbsp;·&nbsp;
288
+ 📝 text-only (<b>no image input</b>)
289
+ </div>
290
+ <div style="margin-top:8px;font-size:13px">
291
+ <a href="https://huggingface.co/AlexWortega/SIQ-1-35B" target="_blank"
292
+ style="color:var(--link-text-color,#3b82f6)">base model</a> ·
293
+ <a href="https://huggingface.co/AlexWortega/SIQ-1-35B" target="_blank"
294
+ style="color:var(--link-text-color,#3b82f6)">GGUF</a>
295
+ </div>
296
+ </div>
297
+ </div>
298
+ """
299
+
300
+
301
+ with gr.Blocks(title="Hermes · SIQ-1-35B", fill_height=True) as demo:
302
+ gr.HTML(CARD)
303
+ gr.Markdown(
304
+ "Ask for a web app, page or game and the model writes a complete HTML file — "
305
+ "the **🖥 Preview** tab runs it live. Tips: bump *Max tokens* for bigger apps."
306
+ )
307
+ meta_state = gr.State([])
308
+ with gr.Row():
309
+ with gr.Column(scale=3):
310
+ chatbot = gr.Chatbot(height=480, label="Chat (use 👍 / 👎 on replies)")
311
+ fb_status = gr.Markdown("", elem_id="fb_status")
312
+ msg = gr.Textbox(
313
+ placeholder="e.g. \"build a pomodoro timer in HTML/JS\" (Enter to send)",
314
+ label="Message",
315
+ autofocus=True,
316
+ )
317
+ with gr.Row():
318
+ send = gr.Button("Send", variant="primary")
319
+ clear = gr.Button("Clear")
320
+ with gr.Column(scale=3):
321
+ with gr.Tab("🖥 Preview"):
322
+ preview = gr.HTML(_EMPTY_PREVIEW)
323
+ with gr.Tab("🧩 Code"):
324
+ code_box = gr.Code(label="Artifact (HTML)", language="html")
325
+ with gr.Tab("🧠 Reasoning"):
326
+ think_box = gr.Textbox(label="What the model was thinking", lines=18)
327
+ with gr.Tab("📝 Raw"):
328
+ raw_box = gr.Textbox(label="Full raw output (with tags)", lines=18)
329
+ with gr.Accordion("⚙️ Settings", open=False):
330
+ system_prompt = gr.Textbox(
331
+ value=DEFAULT_SYS, label="System prompt", lines=4
332
+ )
333
+ temperature = gr.Slider(
334
+ 0.0, 1.5, value=0.6, step=0.05, label="Temperature"
335
+ )
336
+ max_tokens = gr.Slider(
337
+ 256, 8192, value=4096, step=128, label="Max tokens"
338
+ )
339
+
340
+ inputs = [msg, chatbot, system_prompt, temperature, max_tokens, meta_state]
341
+ outputs = [chatbot, msg, raw_box, think_box, code_box, preview, meta_state]
342
+ send.click(respond, inputs, outputs)
343
+ msg.submit(respond, inputs, outputs)
344
+ clear.click(
345
+ lambda: ([], "", "", "", "", _EMPTY_PREVIEW, []), None, outputs
346
+ )
347
+ chatbot.like(on_like, [meta_state], [fb_status])
348
+
349
+ demo.queue().launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124
2
+ llama-cpp-python==0.3.23
3
+ nvidia-cuda-runtime-cu12==12.4.127
4
+ nvidia-cublas-cu12==12.4.5.8
5
+ huggingface_hub>=0.25
6
+ spaces