mlclaw 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.agents/skills/mlclaw/SKILL.md +63 -18
  2. package/Dockerfile +21 -4
  3. package/README.md +70 -24
  4. package/assets/hf-logo.svg +8 -0
  5. package/assets/hf-tooling/manifest.json +50 -0
  6. package/assets/hf-tooling/skills/hf-cli/SKILL.md +218 -0
  7. package/assets/hf-tooling/skills/hf-mem/SKILL.md +79 -0
  8. package/assets/hf-tooling/skills/huggingface-best/SKILL.md +134 -0
  9. package/assets/hf-tooling/skills/huggingface-datasets/SKILL.md +107 -0
  10. package/assets/hf-tooling/skills/huggingface-gradio/SKILL.md +298 -0
  11. package/assets/hf-tooling/skills/huggingface-gradio/examples.md +613 -0
  12. package/assets/hf-tooling/skills/huggingface-local-models/SKILL.md +113 -0
  13. package/assets/hf-tooling/skills/huggingface-local-models/references/hardware.md +38 -0
  14. package/assets/hf-tooling/skills/huggingface-local-models/references/hub-discovery.md +178 -0
  15. package/assets/hf-tooling/skills/huggingface-local-models/references/quantization.md +256 -0
  16. package/assets/hf-tooling/skills/huggingface-papers/SKILL.md +239 -0
  17. package/assets/hf-tooling/skills/huggingface-spaces/SKILL.md +239 -0
  18. package/assets/hf-tooling/skills/huggingface-spaces/references/buckets.md +89 -0
  19. package/assets/hf-tooling/skills/huggingface-spaces/references/debugging.md +236 -0
  20. package/assets/hf-tooling/skills/huggingface-spaces/references/gradio.md +200 -0
  21. package/assets/hf-tooling/skills/huggingface-spaces/references/grants.md +56 -0
  22. package/assets/hf-tooling/skills/huggingface-spaces/references/inference-providers.md +85 -0
  23. package/assets/hf-tooling/skills/huggingface-spaces/references/known-errors.md +232 -0
  24. package/assets/hf-tooling/skills/huggingface-spaces/references/requirements.md +169 -0
  25. package/assets/hf-tooling/skills/huggingface-spaces/references/zerogpu.md +349 -0
  26. package/assets/hf-tooling/skills/huggingface-tool-builder/SKILL.md +120 -0
  27. package/assets/hf-tooling/skills/huggingface-tool-builder/references/baseline_hf_api.py +57 -0
  28. package/assets/hf-tooling/skills/huggingface-tool-builder/references/baseline_hf_api.sh +40 -0
  29. package/assets/hf-tooling/skills/huggingface-tool-builder/references/baseline_hf_api.tsx +57 -0
  30. package/assets/hf-tooling/skills/huggingface-tool-builder/references/find_models_by_paper.sh +230 -0
  31. package/assets/hf-tooling/skills/huggingface-tool-builder/references/hf_enrich_models.sh +96 -0
  32. package/assets/hf-tooling/skills/huggingface-tool-builder/references/hf_model_card_frontmatter.sh +188 -0
  33. package/assets/hf-tooling/skills/huggingface-tool-builder/references/hf_model_papers_auth.sh +171 -0
  34. package/assets/hf-tooling/skills/huggingface-zerogpu/SKILL.md +289 -0
  35. package/assets/hf-tooling/skills/huggingface-zerogpu/references/concurrency.md +79 -0
  36. package/assets/hf-tooling/skills/huggingface-zerogpu/references/cuda-and-deps.md +66 -0
  37. package/assets/hf-tooling/skills/huggingface-zerogpu/references/how-quota-works.md +74 -0
  38. package/assets/hf-tooling/skills/huggingface-zerogpu/references/how-zerogpu-works.md +50 -0
  39. package/assets/hf-tooling/templates/.agents/mcp/huggingface.json +11 -0
  40. package/assets/hf-tooling/templates/.env.example +5 -0
  41. package/assets/hf-tooling/templates/examples/huggingface/README.md +16 -0
  42. package/assets/hf-tooling/templates/examples/huggingface/bucket-sync.md +19 -0
  43. package/assets/hf-tooling/templates/examples/huggingface/dataset-upload.py +22 -0
  44. package/assets/hf-tooling/templates/examples/huggingface/hf-discover.md +13 -0
  45. package/assets/hf-tooling/templates/examples/huggingface/runtime-inspection.py +9 -0
  46. package/assets/mlclaw-control-ui/assets/index-D2TFes32.js +9 -0
  47. package/assets/mlclaw-control-ui/assets/index-DP72PFuv.css +1 -0
  48. package/assets/mlclaw-control-ui/index.html +13 -0
  49. package/assets/mlclaw.svg +298 -124
  50. package/dist/hf-tooling-seed.js +261 -0
  51. package/dist/mlclaw-space-runtime.js +6634 -3321
  52. package/dist/mlclaw.mjs +428 -178
  53. package/entrypoint.sh +4 -0
  54. package/mlclaw.ps1 +4 -2
  55. package/mlclaw.sh +5 -3
  56. package/openclaw.default.json +1 -0
  57. package/package.json +16 -2
  58. package/space/README.md +32 -2
  59. package/tsconfig.json +3 -2
@@ -0,0 +1,239 @@
1
+ ---
2
+ name: huggingface-spaces
3
+ description: Build, deploy, and maintain applications on Hugging Face Spaces — Gradio / Docker / Static SDKs, ZeroGPU and dedicated hardware, model loading, debugging, buckets, inference providers, community grants. Use whenever the user asks to create or host an app on Hugging Face, port code onto ZeroGPU, fix a Space that won't build or run, or otherwise work with `hf spaces …`, `@spaces.GPU`, Space README frontmatter, or the `spaces` Python package.
4
+ ---
5
+
6
+ # Hugging Face Spaces
7
+
8
+ Hugging Face Spaces host machine-learning applications. There are 1M+ today; each Space is a git repo. This skill covers creating, building, debugging, and maintaining them.
9
+
10
+ ## 0. Getting ready
11
+
12
+ Before anything else:
13
+
14
+ 1. Check the `hf` CLI is installed: `which hf`. If not, `pip install -U huggingface_hub`.
15
+ 2. Check the user is logged in: `hf auth whoami`. If not, ask them to run `! hf auth login` in this session — they'll need a write-scoped token from https://huggingface.co/settings/tokens.
16
+ 3. Note `whoami`'s `canPay` and `isPro` flags — they gate hardware choices below.
17
+
18
+ The `hf-cli` skill teaches an agent every `hf` command and is the recommended companion to this one. Install it with `hf skills add hf-cli` (add `--claude --global` to install for Claude Code as well, user-level).
19
+
20
+ ## 1. What a Space is
21
+
22
+ A Space is a git repo with three possible SDKs:
23
+
24
+ - **Gradio** — most Spaces. Python, fast iteration, supports ZeroGPU.
25
+ - **Docker** — arbitrary container. Use when you need a non-Python stack or a pre-built template (Streamlit, Argilla, Shiny, etc. — full list at https://huggingface.co/docs/hub/spaces-sdks-docker). Does **not** support ZeroGPU.
26
+ - **Static** — plain HTML, or a React/Svelte/Vue project built at deploy time. Use for in-browser ML (transformers.js / WebGPU / WebAssembly / onnxruntime-web), project pages, interactive reports, or Spaces that orchestrate other Spaces. No hardware needed.
27
+
28
+ ### Hardware tiers
29
+
30
+ Free, no creator cost: **`cpu-basic`** and **`zero-a10g`** (ZeroGPU). Static Spaces are also free and don't need hardware.
31
+
32
+ **`cpu-basic`** — 2 vCPU / 16 GB. For data viz, API-proxy Spaces, small CPU-bound models.
33
+
34
+ **ZeroGPU (`zero-a10g`)** — dynamic, per-request GPU allocation on NVIDIA RTX PRO 6000 Blackwell (sm_120). Two sizes: `large` (half MIG, 48 GB, 1× quota) and `xlarge` (full, 96 GB, 2× quota). Free for the Space creator; Space visitors consume their own daily quota (~5 min free / 40 min Pro / 60 min Enterprise). **Gradio-only**, **PyTorch-first**. Requires the creator to be on a PRO / Team / Enterprise plan.
35
+
36
+ **Dedicated GPU** (T4, L4, A10G, L40S, A100, H200) — billed to the Space creator by the hour. List + pricing: `hf spaces hardware`. Only the creator can attach these, and only if `canPay=True`. Use when ZeroGPU genuinely doesn't fit — non-PyTorch main model with heavy init, very-large-model long-context inference, etc.
37
+
38
+ If a non-PRO user has a use case that wants ZeroGPU, you can still build it: create a `cpu-basic` Space, code the app for ZeroGPU, push, then request a community grant. See [`references/grants.md`](references/grants.md).
39
+
40
+ For the authoritative reference: https://huggingface.co/docs/hub/spaces-overview
41
+
42
+ ## 2. Look for an existing demo first
43
+
44
+ Before deciding how to build anything, search for prior art:
45
+
46
+ ```bash
47
+ hf spaces search "<model name or task>" --sdk gradio --limit 10
48
+ ```
49
+
50
+ If someone has built a similar Space, read its `app.py` and `requirements.txt` — that gives you the working pattern. Saves a lot of blind iteration. Mention to the user what you found before committing to an approach.
51
+
52
+ ## 3. Decide SDK and hardware
53
+
54
+ Follow the user's explicit request first. If they were vague:
55
+
56
+ - **Default for a public ML demo**: Gradio + ZeroGPU. Use this unless something below applies.
57
+ - **The model's only inference path is non-PyTorch** (ONNX / TF / JAX / vLLM as the MAIN model, with heavy init): dedicated GPU.
58
+ - But: marginal non-torch tools (a small ONNX preprocessor, a TF utility) inside a torch-main pipeline are fine on ZeroGPU. The hijack only patches torch; init the non-torch lib inside `@spaces.GPU` and pay the short per-call init cost.
59
+ - **Tiny / CPU-bound model, or API-proxy Space**: `cpu-basic` (`hardware`-free isn't applicable to Gradio).
60
+ - **Browser-side ML or project page**: Static.
61
+ - **Container with non-Python stack**: Docker.
62
+
63
+ ### Sourcing the model
64
+
65
+ - **GitHub repo** — clone locally to read structure. If it already has a Gradio demo, the minimal viable path is to adapt it onto ZeroGPU (see [`references/zerogpu.md`](references/zerogpu.md)). Otherwise: read the README + inference code, prefer the PyTorch path, estimate VRAM (bf16 ≈ `params_B × 2` GB; 48 GB fits ≤24B params at bf16, or much larger with quantization — see [`references/zerogpu.md`](references/zerogpu.md) for quantization on ZeroGPU).
66
+ - **HF model repo** — read its README, follow any linked GitHub.
67
+ - **Paper / blog post** — look for an official or unofficial implementation. Don't reimplement unless trivial or the user explicitly asks.
68
+ - **Vague request** — search Spaces first; surface results.
69
+
70
+ If the model genuinely won't fit, check **Inference Providers** as an alternative: see [`references/inference-providers.md`](references/inference-providers.md). This avoids hosting the model at all.
71
+
72
+ ## 4. Create the Space
73
+
74
+ ```bash
75
+ hf repos create <namespace>/<name> --type space --space-sdk <gradio|docker|static> \
76
+ [--flavor zero-a10g|cpu-basic|<paid-flavor>] \
77
+ [--secrets KEY=val] [--env KEY=val] \
78
+ --public|--private|--protected \
79
+ --exist-ok
80
+ ```
81
+
82
+ - `--space-sdk` is required.
83
+ - `--flavor` selects hardware. `zero-a10g` is the (legacy) identifier for ZeroGPU. Omit for `cpu-basic`. Run `hf spaces hardware` for the full paid list and pricing.
84
+ - Visibility: `--public` (anyone can view), `--private` (only you), `--protected` (app is reachable but git repo / Files tab is private).
85
+ - `--secrets KEY=val` becomes an environment variable inside the Space and is **not** visible to visitors. Use for API keys, gated-repo tokens (`HF_TOKEN=hf_…`), etc. Can also be set later via `hf spaces secrets set <id> KEY=val`.
86
+ - `--env KEY=val` is **visible to visitors** — use only for non-sensitive config (`GRADIO_SSR_MODE=false`, `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`, etc.).
87
+
88
+ > Note: `hardware:` in the README YAML is silently ignored — hardware is only set via `--flavor` at creation, or later via `hf spaces settings <id> --hardware <name>`.
89
+
90
+ ## 5. Build the app
91
+
92
+ The Space now exists at `https://huggingface.co/spaces/<namespace>/<name>` but is empty.
93
+
94
+ ### README.md frontmatter
95
+
96
+ Always required:
97
+
98
+ ```yaml
99
+ ---
100
+ title: ...
101
+ emoji: 🚀 # pick something representative
102
+ colorFrom: blue # red|yellow|green|blue|indigo|purple|pink|gray (only these)
103
+ colorTo: indigo
104
+ sdk: gradio # gradio | docker | static
105
+ sdk_version: 6.15.1 # latest stable unless you have a reason*
106
+ app_file: app.py # gradio only (docker / static use Dockerfile / index.html)
107
+ short_description: ... # ≤ 60 chars (server rejects longer)
108
+ python_version: "3.12" # ZeroGPU officially supports 3.10.13 and 3.12.12
109
+ startup_duration_timeout: 30m # default; bump to 1h for big LLMs / heavy downloads
110
+ ---
111
+ ```
112
+
113
+ \* Default to the current latest stable, and **look up what that is** (`pip index versions gradio`, or the version a freshly-created Space defaults to) — the number above is a placeholder that goes stale, don't reuse it. Only pin older when the latest genuinely doesn't work for this Space: a custom component pins it, or you're adapting an existing demo and don't want to rewrite for 5.x→6.x breaking changes. If you need a 5.x, pick `5.50.0` (latest of the series; still supports custom components).
114
+
115
+ All frontmatter options: https://huggingface.co/docs/hub/spaces-config-reference
116
+
117
+ ### Minimal ZeroGPU Gradio app
118
+
119
+ ```python
120
+ import spaces # MUST come before torch / diffusers / transformers
121
+ import torch
122
+ import gradio as gr
123
+ from diffusers import DiffusionPipeline
124
+
125
+ pipe = DiffusionPipeline.from_pretrained("<repo>", torch_dtype=torch.bfloat16).to("cuda")
126
+
127
+ @spaces.GPU(duration=60)
128
+ def generate(prompt: str):
129
+ """Generate an image from a text prompt.""" # docstring → API / MCP tool description
130
+ return pipe(prompt).images[0]
131
+
132
+ gr.Interface(fn=generate, inputs=gr.Text(), outputs=gr.Image()).launch(mcp_server=True)
133
+ ```
134
+
135
+ Three rules — full treatment in [`references/zerogpu.md`](references/zerogpu.md):
136
+
137
+ 1. **`import spaces` before torch / any CUDA-touching import.** It monkey-patches `torch.cuda.*`; once CUDA is initialized in the main process, it's too late.
138
+ 2. **Load the model at module scope, `.to("cuda")` eagerly.** ZeroGPU intercepts the call, packs weights to disk, and streams them into VRAM on the first `@spaces.GPU` entry. Lazy loading inside the decorator costs every user.
139
+ 3. **Decorate the function Gradio binds.** Estimate `duration` to the realistic worst case (smaller = higher queue priority and tighter quota check). For input-dependent runtime, pass a callable.
140
+
141
+ ### Examples, docstrings, and MCP
142
+
143
+ - **Add `gr.Examples` whenever it makes sense** (the app takes input and representative inputs exist) — prefer the model/repo's own official examples. Keep example rows to the few inputs a user actually varies (prompt, image) and give the handler defaults for the rest (steps, seed, guidance) so a row is `["a prompt"]`, not a wall of knobs. Use `cache_examples=True, cache_mode="lazy"`. See [`references/gradio.md`](references/gradio.md).
144
+ - **Give every API-triggered function a docstring and type hints.** Each Gradio event handler is exposed over the API; the docstring + signature are what a caller — and the MCP tool schema — sees.
145
+ - **Launch with `demo.launch(mcp_server=True)`** (Gradio 5+) so the Space doubles as an MCP server: each API function becomes an MCP tool described by its docstring and hints.
146
+
147
+ ### requirements.txt
148
+
149
+ Short version:
150
+
151
+ - **Do NOT list**: `gradio`, `spaces`, `huggingface_hub` (preinstalled and platform-managed; pinning them causes resolution failures or silently breaks the ZeroGPU runtime).
152
+ - **Do list if you use them**: `torchvision`, `torchaudio` (not preinstalled), plus everything else (`diffusers`, `transformers`, `accelerate`, `sentencepiece`, …).
153
+ - ZeroGPU only accepts torch `2.8.0`, `2.9.1`, `2.10.0`, `2.11.0`. Default to leaving torch unpinned (the runtime preinstalls the latest). Only pin when a dep forces it.
154
+ - For prebuilt CUDA-extension wheels (`flash_attn`, `xformers`, `pytorch3d`, `nvdiffrast`, `diff_gaussian_rasterization`, `torchmcubes`): use the prebuilt Blackwell wheels at `https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/tree/main/wheels`. Full mapping + caveats in [`references/requirements.md`](references/requirements.md).
155
+
156
+ ### Per-SDK depth
157
+
158
+ - **Gradio patterns** (themes, `gr.Examples`, streaming, custom HTML components, `gr.Server`): [`references/gradio.md`](references/gradio.md).
159
+ - **Docker**: https://huggingface.co/docs/hub/spaces-sdks-docker. Examples: `hf spaces list --filter docker`.
160
+ - **Static**: https://huggingface.co/docs/hub/spaces-sdks-static. For built SPAs, set `app_build_command: npm run build` and `app_file: dist/index.html` in frontmatter.
161
+ - **ZeroGPU specifics** (decorator semantics, sizing, AoTI, generators, concurrency, pickle / `gr.State` across the worker boundary): [`references/zerogpu.md`](references/zerogpu.md) — read this whenever the Space targets ZeroGPU.
162
+
163
+
164
+ ## 6. Iterate on the Space, not locally
165
+
166
+ Try to build a release candidate from the user quest locally and push it — then use the live URL as your test loop. The Space environment is the only one that matters; do not try to test locally. `python3 -m py_compile app.py` is the maximum local check worth doing before pushing.
167
+
168
+ Push files with `hf upload <namespace>/<name> . --repo-type space`. **`--repo-type space` is required** — `hf upload` defaults to a *model* repo and will otherwise upload to (and silently create) a model repo of the same name. Add `--exclude "**/__pycache__/**"` so local bytecode caches aren't committed into the Space.
169
+
170
+ Once pushed, pick the cheapest update mechanism for each change — hot-reload for pure Python edits, `hf upload` for code-only files hot-reload can't touch, full rebuild only when `requirements.txt` / `Dockerfile` / README frontmatter actually changed. Full ladder + footguns (hot-reload poisoning factory reboot, runtime.sha lag, etc.) in [`references/debugging.md`](references/debugging.md).
171
+
172
+ ## 7. Verify
173
+
174
+ Don't trust `RUNNING` alone — the app can be running but broken. Four steps, in order:
175
+
176
+ **A. Alive?** Stage + hardware:
177
+ ```bash
178
+ hf spaces info <ns>/<name> --expand runtime
179
+ ```
180
+
181
+ **B. Logs clean post-boot?** Read the run log to confirm startup finished without warnings or silent fallbacks:
182
+ ```bash
183
+ hf spaces logs <ns>/<name> --tail 200
184
+ ```
185
+ Look for model-load completion, no import warnings, no "falling back to CPU" / dtype downgrade messages, no `RUNNING` masking a half-broken app.
186
+
187
+ **C. API actually responds.** With logs still tailing in another terminal (`hf spaces logs <ns>/<name> --follow`), call the endpoint:
188
+ ```python
189
+ from gradio_client import Client, handle_file
190
+ import os
191
+ c = Client("<ns>/<name>", token=os.environ["HF_TOKEN"], httpx_kwargs={"timeout": 600})
192
+ print(c.view_api()) # discover endpoints — don't guess
193
+ result = c.predict(..., api_name="/generate")
194
+ ```
195
+
196
+ **D. Sniff output AND logs.** HTTP 200 ≠ correct output. Check both:
197
+ ```python
198
+ head = open(result, "rb").read(16)
199
+ # glTF / \x89PNG / RIFF…WEBP / RIFF…WAVE / [4:8]==b"ftyp" → png/jpg/webp/wav/mp4
200
+ ```
201
+ And look at the run log emitted during the call — silent fallbacks (model snapping to a different size, missing optional dep, dtype downgrade) only show up there.
202
+
203
+ Full smoke-test patterns (streaming endpoints, OAuth-gated Spaces, `gr.Server` custom routes): [`references/debugging.md`](references/debugging.md).
204
+
205
+ ## 8. Permanent storage (buckets)
206
+
207
+ Spaces are stateless — `/data` is wiped on restart. If the Space needs to persist user uploads, generations, logs, or interact with a long-lived store, mount a **bucket**:
208
+
209
+ ```bash
210
+ hf buckets create <ns>/<bucket-name> # --private optional
211
+ hf spaces volumes set <ns>/<space> -v hf://buckets/<ns>/<bucket-name>:/data # read-write at /data
212
+ ```
213
+
214
+ Buckets are paid storage; check `canPay` and confirm with the user. Full patterns (read-fast / write-durable, public bucket URLs, model-cache anti-pattern): [`references/buckets.md`](references/buckets.md).
215
+
216
+ ## 9. When things break
217
+
218
+ Order of operations:
219
+
220
+ 1. Read the logs: `hf spaces logs <id> --build --follow` (build error) or `hf spaces logs <id> --follow` (runtime error). Find the **first** error, not the last.
221
+ 2. Grep [`references/known-errors.md`](references/known-errors.md) for the error string. Check if this is a known issue before trying your own fix — most common ZeroGPU / Gradio / dependency errors have a 1–2 line fix there.
222
+ 3. Iterate using the cheapest rung from [`references/debugging.md`](references/debugging.md). The vast majority of issues resolve with log-reading + smoke-test loops; interactive dev mode + SSH is a heavy-hammer last resort.
223
+
224
+ If you solve an error that wasn't in the known-errors list, suggest the user PR it back to this skill so future runs benefit.
225
+
226
+ ---
227
+
228
+ ## Reference index
229
+
230
+ | When to read | File |
231
+ |---|---|
232
+ | **How ZeroGPU works** + correct patterns (decorator, sizing, pickle, generators, real-time, AoTI) | [`references/zerogpu.md`](references/zerogpu.md) |
233
+ | **Iterate + debug**: logs, rung ladder, smoke testing (and dev mode + SSH as a last resort) | [`references/debugging.md`](references/debugging.md) |
234
+ | **Error-string lookup** — the single place for all error symptoms (Spaces, ZeroGPU, Gradio, deps) | [`references/known-errors.md`](references/known-errors.md) |
235
+ | Pinning deps, picking wheels, torch-family alignment | [`references/requirements.md`](references/requirements.md) |
236
+ | `gr.Examples` (add when it makes sense), themes, custom HTML components, `gr.Server`, MCP server (`mcp_server=True`) | [`references/gradio.md`](references/gradio.md) |
237
+ | Persistent storage, public bucket URLs | [`references/buckets.md`](references/buckets.md) |
238
+ | Community grant requests (non-PRO needing ZeroGPU) | [`references/grants.md`](references/grants.md) |
239
+ | Provider proxy (zero-VRAM big LLM via Cerebras / Fireworks / Together / etc.) | [`references/inference-providers.md`](references/inference-providers.md) |
@@ -0,0 +1,89 @@
1
+ # Persistent storage with Buckets
2
+
3
+ Spaces are stateless. All data is wiped on restart / rebuild. For state that must survive (user uploads, generations, dynamic feeds, logs, growing databases): mount an HF **Bucket** — S3-like object storage living at `hf://buckets/<ns>/<bucket>`.
4
+
5
+ Buckets are paid (per-TB storage). Check `whoami.canPay` and confirm with the user before creating one. Pricing + free tier: https://huggingface.co/storage.
6
+
7
+ Full docs: https://huggingface.co/docs/hub/storage-buckets.
8
+
9
+ ## Create + attach
10
+
11
+ ```bash
12
+ hf buckets create <ns>/<bucket-name> # --private optional
13
+ hf spaces volumes set <ns>/<space> -v hf://buckets/<ns>/<bucket-name>:/data
14
+ ```
15
+
16
+ After this, writes to `/data/` in the Space are durable. Reads come from the bucket via the Xet storage backend.
17
+
18
+ To make the bucket files publicly addressable: leave the bucket public. Public bucket files are served at `https://huggingface.co/buckets/<ns>/<bucket>/resolve/<path>` (HTTP 302 redirect to a signed CDN URL). The Space writes once and the public URL works forever — no streaming proxy needed.
19
+
20
+ ## Write-durable, read-fast pattern
21
+
22
+ For a feed-style Space (e.g. a community jam where users save generations and browse a public timeline), don't re-scan disk on every request. Module-level disk scan → in-memory list → every write appends to both:
23
+
24
+ ```python
25
+ import os, json, uuid
26
+ from datetime import datetime, timezone
27
+
28
+ BUCKET_ID = "<ns>/<bucket-name>"
29
+ BUCKET_URL = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve"
30
+ _feed = []
31
+
32
+ def _load_feed():
33
+ root = "/data/songs"
34
+ if not os.path.isdir(root):
35
+ return
36
+ for sid in os.listdir(root):
37
+ meta = f"{root}/{sid}/meta.json"
38
+ if os.path.isfile(meta):
39
+ _feed.append(json.load(open(meta)))
40
+ _feed.sort(key=lambda s: s["created_at"], reverse=True)
41
+
42
+ _load_feed() # one scan at startup
43
+
44
+ @app.api(name="save", time_limit=60)
45
+ def save(audio_bytes: bytes, title: str):
46
+ sid = uuid.uuid4().hex[:12]
47
+ d = f"/data/songs/{sid}"; os.makedirs(d, exist_ok=True)
48
+ open(f"{d}/audio.wav", "wb").write(audio_bytes)
49
+ meta = {"id": sid, "title": title,
50
+ "url": f"{BUCKET_URL}/songs/{sid}/audio.wav",
51
+ "created_at": datetime.now(timezone.utc).isoformat()}
52
+ json.dump(meta, open(f"{d}/meta.json", "w"))
53
+ _feed.insert(0, meta) # cache stays current — no re-scan
54
+ return meta
55
+
56
+ @app.api(name="feed", concurrency_limit=10)
57
+ def feed(): return _feed[:50] # zero disk I/O
58
+ ```
59
+
60
+ Reference Space using this pattern: https://huggingface.co/spaces/victor/ace-step-jam
61
+
62
+ ## Anti-pattern: bucket as model-weights cache
63
+
64
+ **Do NOT** `snapshot_download(..., local_dir="/data/weights")` and load checkpoints from there. Bucket I/O is S3-paced; reading a 22 GB `safetensors` from `/data` during `from_pretrained` stalls past any `@spaces.GPU` duration cap.
65
+
66
+ For model weights, let HF Hub re-download to local container disk on each cold start. With `HF_HUB_ENABLE_HF_TRANSFER=1` (set in the runtime by default) this is fast — typically much faster than streaming the same bytes through bucket I/O at request time.
67
+
68
+ Bucket I/O is fine for occasional metadata reads (the feed pattern above) or saving user information. It is *not* fine as the path your model loader streams gigabytes through every cold start.
69
+
70
+ ## Cache redirects
71
+
72
+ `/home/user/.cache` is read-only on ZeroGPU. Redirect transient caches at the top of `app.py`, before any library import that uses them:
73
+
74
+ ```python
75
+ import os
76
+ os.environ.setdefault("HF_HOME", "/data/.cache/huggingface") # or /tmp on non-bucket Spaces
77
+ os.environ.setdefault("HF_MODULES_CACHE", "/tmp/hf_modules")
78
+ os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib")
79
+ ```
80
+
81
+ Missing redirections fail silently or at first matplotlib / transformers / diffusers import.
82
+
83
+ ## Write access from the Space
84
+
85
+ The Space's `HF_TOKEN` secret needs write permission on the bucket. Set via Settings → Secrets in the Space UI, or `hf spaces secrets set <id> HF_TOKEN=<token>`.
86
+
87
+ ## Security note
88
+
89
+ Public bucket files are publicly accessible forever at their resolve URL. **Don't write PII** to a public bucket. If you need durable but private storage (e.g. per-user history requiring an HF login), keep the bucket private and gate reads through your Space's own auth.
@@ -0,0 +1,236 @@
1
+ # Debugging and iteration
2
+
3
+ How to iterate cheaply, read logs, and smoke-test. Dev mode + SSH exists as a last resort (covered at the bottom).
4
+
5
+ ## The rung ladder
6
+
7
+ Pick the cheapest update mechanism that fits the change. Going one rung too high wastes 30 s – 15 min per cycle.
8
+
9
+ | Rung | When | Command | Cost |
10
+ |---|---|---|---|
11
+ | 1. Hot-reload | Pure Python edit on a Gradio Space (SDK 6.1+), **no new deps** | `hf spaces hot-reload <id> -f app.py` | seconds, no rebuild |
12
+ | 2. `hf upload` | Code-only change hot-reload can't handle (`gr.Server`, Streamlit, Docker entrypoint, non-Python file) | `hf upload <id> . --repo-type space --include '<file>'` | 30–90 s app restart |
13
+ | 3. Full rebuild | `requirements.txt`, `Dockerfile`, README frontmatter, or hardware change | `hf upload <id> . --repo-type space --exclude "**/__pycache__/**" && hf spaces logs <id> --build --follow` | 1–15 min |
14
+
15
+ `hf upload` defaults to a **model** repo — always pass `--repo-type space`, or it uploads to (and silently creates) a model repo of the same name. Also `--exclude "**/__pycache__/**"` so local bytecode caches don't get committed into the Space.
16
+ | 4. Factory reboot | Container in inconsistent state (broken pip env, etc.) | `hf spaces restart <id> --factory-reboot` | full rebuild + cold start |
17
+
18
+ ### How hot-reload works
19
+
20
+ `hf spaces hot-reload <id> -f app.py` patches the running Python process in place via `jurigged` (vendored inside the `spaces` package), then commits the change to the repo with a hot-reload marker that tells the platform to skip its usual restart. Seconds, no rebuild.
21
+
22
+ Applies cleanly to function-body changes and new top-level symbols. Does **not** rerun module-level imports or one-time init — the model was loaded when `app.py` first ran and jurigged won't re-execute that load. New pip deps, README frontmatter, `Dockerfile`, and hardware changes need a full rebuild (rung 3).
23
+
24
+ Independent of dev mode. Marked experimental in the CLI. Requires Gradio SDK 6.1+.
25
+
26
+ ### Footguns
27
+
28
+ - **Hot-reload poisons factory reboot.** A commit that's only a hot-reload leaves runtime metadata that's valid only while the hot process is alive. `--factory-reboot` on top of one can fail with `fatal: could not read Username for 'https://huggingface.co'`. Recovery: push any normal `hf upload` commit (even a one-line no-op) first, then restart.
29
+ - **`runtime.sha` lags repo SHA on restart.** `hf upload` succeeds → repo updates → `hf spaces info` keeps reporting the *previous* commit's SHA under `runtime` for several minutes while the new container loads. Poll `runtime.sha`, not just `stage`, and don't issue another restart until it flips.
30
+ - **Concurrent uploads or restart-while-uploading collide.** Wait for one to finish.
31
+ - **"Let me try locally first"** for anything that depends on the Space's Python / torch / CUDA env. The Space environment is the only one that matters. `python3 -m py_compile app.py` is the maximum local check worth doing before pushing.
32
+
33
+ ## Reading logs
34
+
35
+ ```bash
36
+ hf spaces info <id> --expand runtime # stage at a glance
37
+ hf spaces logs <id> --build --follow # build log, live
38
+ hf spaces logs <id> --follow # run log, live
39
+ hf spaces logs <id> --build --tail 500 # bigger window — default is small
40
+ ```
41
+
42
+ Find the **first** error in the build log, not the last. Cascading errors after the first are noise.
43
+
44
+ State machine (terminal states in bold):
45
+
46
+ ```
47
+ BUILDING → APP_STARTING → RUNNING
48
+ ↘ RUNTIME_ERROR
49
+ ↘ BUILD_ERROR
50
+ ↘ CONFIG_ERROR
51
+ ```
52
+
53
+ For stage-specific lookups, see [`known-errors.md`](known-errors.md).
54
+
55
+ ## Smoke-test patterns
56
+
57
+ A Space isn't done until a `gradio_client` call against the live URL exercises the endpoint end-to-end. Four steps in order — keep `hf spaces logs <id> --follow` running in another terminal throughout, so any silent fallback (model snapping to a different size, missing optional dep, dtype downgrade) surfaces.
58
+
59
+ ### A. Alive?
60
+
61
+ ```bash
62
+ hf spaces info <id> --expand runtime --format json \
63
+ | python3 -c "import json,sys; r=json.load(sys.stdin)['runtime']; \
64
+ print(r['stage'], r.get('hardware','?'))"
65
+ # expect: RUNNING zero-a10g
66
+ ```
67
+
68
+ If `requested_hardware` is `cpu-basic` when you wanted GPU, your `--flavor` was rejected silently. Fix with `hf spaces settings <id> --hardware zero-a10g`.
69
+
70
+ ### B. Logs clean post-boot?
71
+
72
+ ```bash
73
+ hf spaces logs <id> --tail 200
74
+ ```
75
+
76
+ Confirm the model finished loading, no import warnings, no "falling back to CPU" / dtype-downgrade messages, no failing health checks the platform forgave. Do this before calling the API — many silent failures (a config typo loading the wrong model, a missing optional dep, a one-time init that errored but didn't crash boot) are only visible here.
77
+
78
+ ### C. API actually functions?
79
+
80
+ Default — sync `gr.Interface` / `gr.Blocks` / `gr.ChatInterface` / `gr.Server` `@app.api`:
81
+
82
+ ```python
83
+ from gradio_client import Client, handle_file
84
+ import os
85
+
86
+ c = Client("<ns>/<name>", token=os.environ["HF_TOKEN"],
87
+ httpx_kwargs={"timeout": 600}) # ≥ @spaces.GPU duration + 60s
88
+
89
+ print(c.view_api()) # discover endpoints — don't guess api_name
90
+
91
+ result = c.predict(
92
+ handle_file("test.png"), # file inputs need handle_file()
93
+ "short prompt",
94
+ api_name="/generate", # matches @app.api(name=...) or the function name
95
+ )
96
+ ```
97
+
98
+ **Streaming endpoints** (function uses `yield` or `TextIteratorStreamer`) — `.predict()` returns only the final value. Iterate chunks via `.submit()`:
99
+
100
+ ```python
101
+ job = c.submit("short prompt", api_name="/chat")
102
+ for chunk in job: print(chunk, end="")
103
+ # or job.result() for the final value
104
+ ```
105
+
106
+ **`gr.Server` custom `@app.get/post(...)` routes** don't appear in `view_api()`. Hit them with plain HTTP:
107
+
108
+ ```python
109
+ import httpx
110
+ r = httpx.post(f"https://<subdomain>.hf.space/your_route",
111
+ json={...}, timeout=600,
112
+ headers={"Authorization": f"Bearer {os.environ['HF_TOKEN']}"})
113
+ ```
114
+
115
+ **OAuth-gated Spaces** (`hf_oauth: true` + `gr.LoginButton`) — anonymous `Client` can't authenticate. Test interactively after sign-in, or capture a session token and pass via `httpx_kwargs={"headers": {...}}`.
116
+
117
+ **MCP server mode** (`launch(mcp_server=True)`) — different protocol. Use an MCP client.
118
+
119
+ ### D. Output bytes AND logs look right?
120
+
121
+ HTTP 200 ≠ correct output. Sniff both the returned file and the run log emitted during the call.
122
+
123
+ ```python
124
+ head = open(path, "rb").read(16)
125
+ # b'glTF...' → glb
126
+ # b'\x89PNG' → png
127
+ # b'\xff\xd8' → jpeg
128
+ # b'RIFF...WEBP' → webp
129
+ # b'RIFF...WAVE' → wav
130
+ # head[4:8]==b'ftyp' → mp4
131
+ # b'ply\n' → ply
132
+ ```
133
+
134
+ For text: non-empty, not all `<think>...</think>` (thinking-model leak), length reasonable. For images: returned dimensions match what was requested (some models snap to nearest preset).
135
+
136
+ Look at the tailed run log alongside — silent fallbacks (model snapping resolution, missing optional dep falling back to a slower path, dtype downgrade) only show up there.
137
+
138
+ ### What NOT to do
139
+
140
+ - **Don't launch Playwright / headless browser** to verify backend logic. The Gradio UI calls the same API `gradio_client` does — one `predict` tests both.
141
+ - **Don't build mock-mode + local-server harnesses** before pushing. Local-green ≠ Space-green.
142
+ - **Don't smoke-test with full-budget inputs.** Smallest input that exercises the GPU code path — short prompt, small image, low step count. You're verifying wiring, not quality.
143
+
144
+ ## Iterating on the Space, not locally
145
+
146
+ The Space env is the only one that matters: Python, torch, CUDA, file paths, env vars, gradio version, the `spaces` hijack all differ from your laptop.
147
+
148
+ Workflow:
149
+
150
+ 1. Decide SDK + hardware. Write the smallest `app.py` / `Dockerfile` + `requirements.txt` + README frontmatter — just enough that the entry point loads.
151
+ 2. Push immediately. Don't build a Playwright / mock harness first.
152
+ 3. Once `RUNNING`: verify with `gradio_client` against the real Space. That's your test loop.
153
+ 4. Iterate via the cheapest rung.
154
+
155
+ `python3 -m py_compile app.py` is the maximum local check worth doing.
156
+
157
+ ## Last resort: dev mode + SSH
158
+
159
+ Use only when:
160
+
161
+ - A failure is non-deterministic (device-side asserts, OOM under specific shapes, race conditions).
162
+ - You need `CUDA_LAUNCH_BLOCKING=1` or `gdb` to localize a CUDA error.
163
+ - You'd burn 4+ build cycles trying variations from outside.
164
+
165
+ Reading logs + grepping [`known-errors.md`](known-errors.md) + a tight `gradio_client` smoke loop solves the vast majority of issues. Dev mode is a heavy hammer.
166
+
167
+ ### Prerequisites
168
+
169
+ 1. **PRO / Team / Enterprise plan** — dev mode is a paid feature.
170
+ 2. **An SSH key registered on the user's HF profile.** Without this, SSH refuses the connection. If the user doesn't have one yet, they need to:
171
+ - Generate a keypair locally: `ssh-keygen -t ed25519 -f ~/.ssh/hf_dev -N ''` (no passphrase keeps automation simple; user can pick differently if they prefer).
172
+ - Add the **public** key (`~/.ssh/hf_dev.pub`) at https://huggingface.co/settings/keys.
173
+ - Keep the **private** key (`~/.ssh/hf_dev`) on the machine they'll SSH from.
174
+ 3. **The Space must be in `RUNNING` or `RUNTIME_ERROR`** before dev mode lets you in — not `BUILD_ERROR`. If it's in build error, push a stub `app.py` that boots cleanly first (e.g. `import gradio as gr; gr.Interface(lambda: 'ok', None, 'text').launch()`), then enable dev mode.
175
+
176
+ ### Enable
177
+
178
+ No `huggingface_hub` Python wrapper yet — use the REST endpoint:
179
+
180
+ ```bash
181
+ curl -s -X POST \
182
+ -H "Authorization: Bearer $HF_TOKEN" \
183
+ -H "Content-Type: application/json" \
184
+ "https://huggingface.co/api/spaces/<ns>/<space>/dev-mode" \
185
+ -d '{"enabled": true}'
186
+ ```
187
+
188
+ ### SSH in
189
+
190
+ ```bash
191
+ ssh -i ~/.ssh/hf_dev -o BatchMode=yes -o StrictHostKeyChecking=accept-new \
192
+ <ns>-<space>@ssh.hf.space
193
+ ```
194
+
195
+ Username is `<namespace>-<space>` **lowercase**, with `-` replacing `/`. Dots in the Space name become hyphens too.
196
+
197
+ ### Inside the VM
198
+
199
+ It's a normal container at `/home/user/app/`. You can edit files, `pip install`, run repros, call `@spaces.GPU`-decorated functions interactively (they get a real GPU window).
200
+
201
+ **`nvidia-smi` in the bare terminal will fail** with `NVML: Unknown Error`. Expected — ZeroGPU only exposes the real GPU inside `@spaces.GPU` calls. Don't assume the GPU is broken.
202
+
203
+ **Edits in `/home/user/app/` don't survive** a restart, sleep, or dev-mode-disable. Only commits persist.
204
+
205
+ ### Smoke-test the fix inside the container
206
+
207
+ Before exiting dev mode, verify the fix actually works under a real GPU window:
208
+
209
+ ```bash
210
+ cat > /home/user/app/_devtest.py <<'PY'
211
+ import spaces, torch
212
+ from app import predict # or whatever your @spaces.GPU function is
213
+ print(predict(<realistic-args>))
214
+ PY
215
+ python3 _devtest.py
216
+ ```
217
+
218
+ ### Persist + exit
219
+
220
+ Commit + push from inside the container (`git config user.email / user.name` first; the HF git remote works). Then disable dev mode:
221
+
222
+ ```bash
223
+ curl -s -X POST -H "Authorization: Bearer $HF_TOKEN" \
224
+ -H "Content-Type: application/json" \
225
+ "https://huggingface.co/api/spaces/<ns>/<space>/dev-mode" \
226
+ -d '{"enabled": false}'
227
+ ```
228
+
229
+ **Factory-reboot** to apply the pushed state (in dev mode the Space won't rebuild on commits):
230
+
231
+ ```python
232
+ from huggingface_hub import HfApi
233
+ HfApi(token=HF_TOKEN).restart_space("<ns>/<space>", factory_reboot=True)
234
+ ```
235
+
236
+ Then re-run the outside-the-container smoke test. Dev-mode success does **not** guarantee post-rebuild success — different image, different process tree.