IMJONEZZ commited on
Commit
321303b
·
1 Parent(s): 10c83ac

space: finetuned Warden on ZeroGPU the documented way — bf16 + .to('cuda') module-level + @spaces.GPU(xlarge), no bitsandbytes/device_map (the actual fix). Direct run_in_threadpool call verified by the probe.

Browse files
Files changed (2) hide show
  1. requirements.txt +10 -3
  2. space/app.py +162 -68
requirements.txt CHANGED
@@ -1,11 +1,18 @@
1
- # HF Space (Gradio SDK + ZeroGPU). Diagnostic build: measure the box (CPU RAM,
2
- # disk, real VRAM) and confirm a @spaces.GPU call works before loading the
3
- # model. torch only (no transformers/bnb yet) keeps this build light + safe.
 
4
  gradio==5.49.1
5
  spaces
6
  torch==2.10.0
 
 
7
  huggingface_hub>=0.30
8
  textual>=1.0
9
  rich>=13.0
10
  pyyaml>=6.0
11
  httpx>=0.27
 
 
 
 
 
1
+ # HF Space (Gradio SDK + ZeroGPU). Inference follows the ZeroGPU docs exactly:
2
+ # bf16 model placed on cuda at module level via .to('cuda') (NOT device_map,
3
+ # NOT bitsandbytes both fight ZeroGPU's CUDA emulation and were the source of
4
+ # every earlier crash). Measured box: 2TB CPU RAM, 96GB VRAM on xlarge.
5
  gradio==5.49.1
6
  spaces
7
  torch==2.10.0
8
+ transformers>=4.57,<5
9
+ accelerate
10
  huggingface_hub>=0.30
11
  textual>=1.0
12
  rich>=13.0
13
  pyyaml>=6.0
14
  httpx>=0.27
15
+ # Nemotron-H hard-imports mamba_ssm's triton kernels; prebuilt wheels for
16
+ # torch 2.10 / cu12 / cp312 (pip's isolated build env can't compile them).
17
+ https://github.com/state-spaces/mamba/releases/download/v2.3.2.post1/mamba_ssm-2.3.2.post1+cu12torch2.10cxx11abiTRUE-cp312-cp312-linux_x86_64.whl
18
+ https://github.com/Dao-AILab/causal-conv1d/releases/download/v1.6.2.post1/causal_conv1d-1.6.2.post1+cu12torch2.10cxx11abiTRUE-cp312-cp312-linux_x86_64.whl
space/app.py CHANGED
@@ -1,20 +1,27 @@
1
- """SCRYPT on the web — ZeroGPU diagnostic build.
2
 
3
- Before loading a 30B model (and risking another crash), this build MEASURES
4
- the box: CPU RAM, disk, and the real GPU VRAM seen inside a @spaces.GPU call.
5
- It also confirms that a GPU call works at all from our setup. The game stays
6
- playable on the scripted Warden meanwhile; styling and the PTY are intact.
7
 
8
- Once we know the numbers, the model gets loaded the way the ZeroGPU docs
9
- prescribe: placed on `cuda` at module level with `.to('cuda')` (NOT
10
- device_map, NOT bitsandbytes both of which fight ZeroGPU's CUDA emulation).
 
 
 
 
 
 
 
11
 
12
  GET / CRT landing page
13
- GET /api/status warden state + CPU RAM + disk
14
- GET /api/gpuinfo run the @spaces.GPU probe: real VRAM + a CUDA alloc test
15
  GET /api/whisper scripted teaser
16
  GET /play xterm.js terminal
17
  WS /pty per-visitor game subprocess
 
18
  """
19
 
20
  from __future__ import annotations
@@ -23,7 +30,8 @@ import asyncio
23
  import json
24
  import os
25
  import random
26
- import shutil
 
27
  import tempfile
28
  from pathlib import Path
29
 
@@ -33,55 +41,85 @@ try:
33
  except ImportError:
34
  spaces = None
35
 
36
- from fastapi import APIRouter, WebSocket, WebSocketDisconnect
37
- from fastapi.responses import FileResponse
38
  from fastapi.staticfiles import StaticFiles
39
  from starlette.concurrency import run_in_threadpool
40
 
41
  REPO_ROOT = Path(__file__).resolve().parent.parent
42
  STATIC = Path(__file__).parent / "static"
43
 
 
 
44
 
45
- def _meminfo() -> dict:
46
- info = {}
47
- try:
48
- for line in open("/proc/meminfo"):
49
- k, v = line.split(":")
50
- if k in ("MemTotal", "MemAvailable"):
51
- info[k] = round(int(v.strip().split()[0]) / 1048576, 1) # GB
52
- except Exception:
53
- pass
54
- try:
55
- du = shutil.disk_usage("/")
56
- info["DiskFreeGB"] = round(du.free / 1e9, 1)
57
- info["DiskTotalGB"] = round(du.total / 1e9, 1)
58
- except Exception:
59
- pass
60
- return info
61
 
62
 
63
- # ---------------------------------------------------------- the GPU probe
 
 
 
64
 
65
- def _gpu_probe() -> str:
66
- """Trivial GPU work: report the real device + VRAM and prove a CUDA alloc
67
- succeeds. This is the documented usage shape — if even this aborts, the
68
- problem is the call mechanism, not the model."""
69
- import torch
70
 
71
- if not torch.cuda.is_available():
72
- return "cuda not available inside @spaces.GPU"
73
- p = torch.cuda.get_device_properties(0)
74
- x = torch.ones(1024, 1024, device="cuda")
75
- y = (x @ x).sum().item()
76
- free, total = torch.cuda.mem_get_info()
77
- return (
78
- f"{p.name} | total {p.total_memory/1e9:.1f}GB | "
79
- f"free {free/1e9:.1f}GB | matmul_ok={y>0}"
80
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
 
 
 
 
 
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  if spaces is not None:
84
- _gpu_probe = spaces.GPU(duration=30)(_gpu_probe)
 
 
85
 
86
 
87
  # ----------------------------------------------------------------- the surface
@@ -103,28 +141,60 @@ router = APIRouter()
103
  @router.get("/api/status")
104
  def status() -> dict:
105
  return {
106
- "mode": "diagnostic",
107
- "zerogpu": spaces is not None,
108
- "system": _meminfo(),
109
- "note": "GET /api/gpuinfo to probe the real GPU",
110
  }
111
 
112
 
113
- @router.get("/api/gpuinfo")
114
- async def gpuinfo() -> dict:
115
- """Run the @spaces.GPU probe directly from this route (the same call shape
116
- real inference would use) and report what happens."""
117
  import time
118
 
 
 
 
 
 
 
119
  t0 = time.time()
120
  try:
121
- result = await run_in_threadpool(_gpu_probe)
122
- return {"ok": True, "gpu": result, "seconds": round(time.time() - t0, 1)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  except Exception as err:
124
  import traceback
125
 
126
  traceback.print_exc()
127
- return {"ok": False, "error": f"{type(err).__name__}: {err}"}
 
 
 
 
 
 
128
 
129
 
130
  @router.get("/api/whisper")
@@ -146,14 +216,22 @@ def play() -> FileResponse:
146
 
147
 
148
  def game_env() -> dict:
149
- # Diagnostic build: no model yet, so the game runs its scripted Warden.
150
- return {
151
  "TERM": "xterm-256color",
152
  "COLORTERM": "truecolor",
153
  "PYTHONUNBUFFERED": "1",
154
  "PYTHONPATH": str(REPO_ROOT),
155
- "SCRYPT_BACKEND": "scripted",
156
  }
 
 
 
 
 
 
 
 
 
 
157
 
158
 
159
  async def _pump_pty_to_ws(master_fd: int, ws: WebSocket) -> None:
@@ -219,14 +297,28 @@ async def pty_bridge(ws: WebSocket) -> None:
219
 
220
  import gradio as gr # noqa: E402
221
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  with gr.Blocks(title="SCRYPT engine room") as engine:
223
  gr.Markdown(
224
- "# SCRYPT engine room\n\nThe game lives at [/](/). "
225
- "Diagnostic build — measuring the box before loading the Warden."
 
 
226
  )
227
- # Registering the GPU probe as a gradio API satisfies ZeroGPU's startup
228
- # detection of a @spaces.GPU function.
229
- gr.api(_gpu_probe, api_name="gpu_probe")
230
 
231
 
232
  if __name__ == "__main__":
@@ -240,9 +332,11 @@ if __name__ == "__main__":
240
  fastapi_app.include_router(router)
241
  fastapi_app.mount("/static", StaticFiles(directory=STATIC), name="static")
242
  # Move our routes (incl. the /static mount) ahead of gradio's catch-all.
243
- our = [r for r in fastapi_app.router.routes if getattr(r, "name", "") in {
244
- "status", "gpuinfo", "whisper", "landing", "play", "pty_bridge", "static",
245
- }]
 
 
246
  for r in our:
247
  fastapi_app.router.routes.remove(r)
248
  fastapi_app.router.routes[0:0] = our
 
1
+ """SCRYPT on the web — the finetuned Warden on ZeroGPU, done the documented way.
2
 
3
+ Hard-won lesson: every earlier crash came from bitsandbytes + device_map="cuda"
4
+ fighting ZeroGPU's CUDA emulation. The blessed pattern (verified against a live
5
+ probe on this box: 2TB CPU RAM, RTX Pro 6000 Blackwell, 96GB on xlarge) is:
 
6
 
7
+ * load the model in bf16 and place it with .to('cuda') AT MODULE LEVEL
8
+ (ZeroGPU emulates CUDA outside @spaces.GPU, then migrates at call time);
9
+ * NO device_map, NO bitsandbytes, NO lazy-load-inside-the-worker;
10
+ * the @spaces.GPU function can be called straight from a FastAPI route via
11
+ run_in_threadpool (the probe ran in 1.0s that way).
12
+
13
+ Gradio is the engine room, not the face: it launches the server (and arms the
14
+ ZeroGPU startup handshake), then we transplant our own routes onto its FastAPI
15
+ so the custom CRT page and the raw PTY websocket win. Game subprocesses reach
16
+ the Warden through the existing `api` backend pointed at our loopback /v1.
17
 
18
  GET / CRT landing page
19
+ GET /api/status is the Warden loaded?
20
+ GET /api/probe ask the live Warden one line (verify generation)
21
  GET /api/whisper scripted teaser
22
  GET /play xterm.js terminal
23
  WS /pty per-visitor game subprocess
24
+ POST /v1/chat/completions loopback OpenAI endpoint (game -> @spaces.GPU)
25
  """
26
 
27
  from __future__ import annotations
 
30
  import json
31
  import os
32
  import random
33
+ import secrets
34
+ import sys
35
  import tempfile
36
  from pathlib import Path
37
 
 
41
  except ImportError:
42
  spaces = None
43
 
44
+ from fastapi import APIRouter, Request, WebSocket, WebSocketDisconnect
45
+ from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
46
  from fastapi.staticfiles import StaticFiles
47
  from starlette.concurrency import run_in_threadpool
48
 
49
  REPO_ROOT = Path(__file__).resolve().parent.parent
50
  STATIC = Path(__file__).parent / "static"
51
 
52
+ WARDEN_REPO = os.environ.get("WARDEN_MODEL", "IMJONEZZ/warden-nemotron-3-nano-30b")
53
+ INTERNAL_KEY = os.environ.get("SCRYPT_INTERNAL_KEY") or secrets.token_hex(16)
54
 
55
+ tok = None
56
+ model = None
57
+ WARDEN_ERR = "spaces package not present (not on a ZeroGPU Space)"
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
 
60
+ def _install_mamba_kernels() -> None:
61
+ """Nemotron-H hard-imports mamba_ssm's triton kernels. The wheels are in
62
+ requirements.txt; this just confirms they imported (CPU-only, no CUDA)."""
63
+ from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn # noqa: F401
64
 
 
 
 
 
 
65
 
66
+ if spaces is not None:
67
+ try:
68
+ _install_mamba_kernels()
69
+ import torch
70
+ from transformers import AutoModelForCausalLM, AutoTokenizer
71
+
72
+ tok = AutoTokenizer.from_pretrained(WARDEN_REPO, trust_remote_code=True)
73
+ # bf16, no device_map. .to('cuda') at module level is intercepted by
74
+ # ZeroGPU's emulation and migrated to the real GPU per @spaces.GPU call.
75
+ model = AutoModelForCausalLM.from_pretrained(
76
+ WARDEN_REPO,
77
+ torch_dtype=torch.bfloat16,
78
+ trust_remote_code=True,
79
+ low_cpu_mem_usage=True,
80
+ )
81
+ model.to("cuda")
82
+ model.eval()
83
+ WARDEN_ERR = ""
84
+ except Exception as err: # the game survives without the model (scripted)
85
+ import traceback
86
+
87
+ traceback.print_exc()
88
+ WARDEN_ERR = f"{type(err).__name__}: {err}"
89
+
90
+ WARDEN_READY = not WARDEN_ERR
91
+
92
 
93
+ def _generate_impl(messages, max_tokens, temperature, enable_thinking):
94
+ """Blocking generate -> full text. Single short line, so no streaming
95
+ machinery (a thread + streamer across the ZeroGPU fork hangs); the game's
96
+ typewriter reveals it client-side."""
97
+ import torch
98
 
99
+ inputs = tok.apply_chat_template(
100
+ messages,
101
+ add_generation_prompt=True,
102
+ return_tensors="pt",
103
+ enable_thinking=enable_thinking,
104
+ ).to("cuda")
105
+ with torch.no_grad():
106
+ out = model.generate(
107
+ input_ids=inputs,
108
+ max_new_tokens=max_tokens,
109
+ do_sample=temperature > 0,
110
+ temperature=max(temperature, 1e-3),
111
+ top_p=0.95,
112
+ )
113
+ return tok.decode(out[0, inputs.shape[1]:], skip_special_tokens=True)
114
+
115
+
116
+ # bf16 30B (~60GB) needs the 96GB xlarge slice; duration covers the first
117
+ # call's CPU->GPU migration. The probe proved a direct run_in_threadpool call
118
+ # into a @spaces.GPU function works on this box.
119
  if spaces is not None:
120
+ warden_gpu = spaces.GPU(size="xlarge", duration=120)(_generate_impl)
121
+ else:
122
+ warden_gpu = _generate_impl
123
 
124
 
125
  # ----------------------------------------------------------------- the surface
 
141
  @router.get("/api/status")
142
  def status() -> dict:
143
  return {
144
+ "warden_ready": WARDEN_READY,
145
+ "warden_state": "ready" if WARDEN_READY else WARDEN_ERR,
146
+ "model": WARDEN_REPO,
147
+ "engine": "transformers/bf16 @ ZeroGPU xlarge",
148
  }
149
 
150
 
151
+ @router.get("/api/probe")
152
+ async def probe(q: str = "A new process woke up in your machine. Greet it in one short line, in voice.") -> dict:
 
 
153
  import time
154
 
155
+ if not WARDEN_READY:
156
+ return {"ok": False, "state": WARDEN_ERR}
157
+ msgs = [
158
+ {"role": "system", "content": "You are the Warden, the malevolent operating system of SCRYPTOS. Terse, menacing, Unix-flavored."},
159
+ {"role": "user", "content": q},
160
+ ]
161
  t0 = time.time()
162
  try:
163
+ line = await run_in_threadpool(warden_gpu, msgs, 60, 0.6, False)
164
+ return {"ok": True, "line": line.strip(), "seconds": round(time.time() - t0, 1)}
165
+ except Exception as err:
166
+ return {"ok": False, "error": f"{type(err).__name__}: {err}"}
167
+
168
+
169
+ @router.post("/v1/chat/completions")
170
+ async def chat_completions(request: Request):
171
+ """Loopback OpenAI endpoint for the game's `api` backend. Per-boot bearer
172
+ so only our own subprocesses drive the GPU."""
173
+ if request.headers.get("authorization") != f"Bearer {INTERNAL_KEY}":
174
+ return JSONResponse({"error": "unauthorized"}, status_code=401)
175
+ if not WARDEN_READY:
176
+ return JSONResponse({"error": f"warden offline: {WARDEN_ERR}"}, status_code=503)
177
+
178
+ body = await request.json()
179
+ messages = body.get("messages", [])
180
+ max_tokens = int(body.get("max_tokens", 256))
181
+ temperature = float(body.get("temperature", 0.6))
182
+ thinking = bool(body.get("chat_template_kwargs", {}).get("enable_thinking", False))
183
+ try:
184
+ text = await run_in_threadpool(
185
+ warden_gpu, messages, max_tokens, temperature, thinking
186
+ )
187
  except Exception as err:
188
  import traceback
189
 
190
  traceback.print_exc()
191
+ return JSONResponse({"error": f"{type(err).__name__}: {err}"}, status_code=503)
192
+
193
+ def sse():
194
+ yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]})}\n\n"
195
+ yield "data: [DONE]\n\n"
196
+
197
+ return StreamingResponse(sse(), media_type="text/event-stream")
198
 
199
 
200
  @router.get("/api/whisper")
 
216
 
217
 
218
  def game_env() -> dict:
219
+ env = {
 
220
  "TERM": "xterm-256color",
221
  "COLORTERM": "truecolor",
222
  "PYTHONUNBUFFERED": "1",
223
  "PYTHONPATH": str(REPO_ROOT),
 
224
  }
225
+ if WARDEN_READY:
226
+ env |= {
227
+ "SCRYPT_BACKEND": "api",
228
+ "SCRYPT_API_BASE": "http://127.0.0.1:7860/v1",
229
+ "SCRYPT_API_KEY": INTERNAL_KEY,
230
+ "SCRYPT_MODEL": "warden",
231
+ }
232
+ else:
233
+ env["SCRYPT_BACKEND"] = "scripted"
234
+ return env
235
 
236
 
237
  async def _pump_pty_to_ws(master_fd: int, ws: WebSocket) -> None:
 
297
 
298
  import gradio as gr # noqa: E402
299
 
300
+
301
+ def _probe_ui(text: str) -> str:
302
+ if not WARDEN_READY:
303
+ return f"warden offline: {WARDEN_ERR}"
304
+ try:
305
+ return warden_gpu(
306
+ [{"role": "user", "content": text}], 80, 0.6, False
307
+ )
308
+ except Exception as err:
309
+ return f"generation failed: {type(err).__name__}: {err}"
310
+
311
+
312
  with gr.Blocks(title="SCRYPT engine room") as engine:
313
  gr.Markdown(
314
+ "# SCRYPT engine room\n\n"
315
+ f"model: `{WARDEN_REPO}`\n\n"
316
+ f"status: {'**ready**' if WARDEN_READY else f'offline — {WARDEN_ERR}'}\n\n"
317
+ "The game lives at [/](/)."
318
  )
319
+ box = gr.Textbox(label="say something to the Warden")
320
+ out = gr.Textbox(label="the Warden")
321
+ box.submit(_probe_ui, box, out)
322
 
323
 
324
  if __name__ == "__main__":
 
332
  fastapi_app.include_router(router)
333
  fastapi_app.mount("/static", StaticFiles(directory=STATIC), name="static")
334
  # Move our routes (incl. the /static mount) ahead of gradio's catch-all.
335
+ names = {
336
+ "status", "probe", "chat_completions", "whisper",
337
+ "landing", "play", "pty_bridge", "static",
338
+ }
339
+ our = [r for r in fastapi_app.router.routes if getattr(r, "name", "") in names]
340
  for r in our:
341
  fastapi_app.router.routes.remove(r)
342
  fastapi_app.router.routes[0:0] = our