Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install huggingface-spaces@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin huggingface-spaces v1.0.0 follows the Agent Plugins spec.
gh skills-hub install huggingface-spaces Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/huggingface-spaces/ Extract the ZIP to .github/skills/ in your repo. The folder name must match huggingface-spaces for Copilot to auto-discover it.
Skill Files (15)
README.md 0.4 KB
# Hugging Face Spaces skill
To add the Hugging Face Space creation skill for your agent, [Install the hf CLI](https://huggingface.co/docs/huggingface_hub/guides/cli#getting-started), login with `hf auth login` and run
```
hf skills add huggingface-spaces --claude --global
```
Or just point your agent here https://github.com/huggingface/skills/tree/main/skills/huggingface-spaces and it will know what to do
SKILL.md 17.4 KB
---
name: huggingface-spaces
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.
---
# Hugging Face Spaces
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.
## 0. Getting ready
Before anything else:
1. Check the `hf` CLI is installed: `which hf`. If not, `pip install -U huggingface_hub`.
2. Check the user is logged in: `hf auth whoami`. If not, run `hf auth login` — it prints a URL and a one-time code; ask the user to open the URL and enter the code, then login completes automatically (OAuth, no token needed). Alternatively, pass a write-scoped token from https://huggingface.co/settings/tokens with `--token`.
3. Note `whoami`'s `canPay` and `isPro` flags — they gate hardware choices below. A free (`isPro=False`) account can only host Static Spaces and up to 2 ZeroGPU Spaces.
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).
## 1. What a Space is
A Space is a git repo with three possible SDKs:
- **Gradio** — most Spaces. Python, fast iteration, supports ZeroGPU.
- **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.
- **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.
### Hardware tiers
Static Spaces are free for everyone and need no hardware. **Gradio and Docker Spaces run on compute and require a paid plan to create** — PRO for personal accounts, Team or Enterprise for organizations — with one exception: **free personal accounts in good standing (verified email, account older than 30 days) can host up to 2 ZeroGPU Spaces.**
So on a free account ZeroGPU is the *only* way to host a Gradio Space. `cpu-basic` is not the safe fallback it used to be — it is gated too.
**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**. Hosting caps per account: **2** free personal, **10** PRO, **50** Team / Enterprise org.
**`cpu-basic`** — 2 vCPU / 16 GB, no hourly cost but needs a paid plan. For data viz, API-proxy Spaces, small CPU-bound models.
**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.
If the user needs hardware they can't pay for — a dedicated GPU, or a Gradio Space beyond the free 2-ZeroGPU cap — they can still create a **Static** Space (free for everyone), push the app there, and request a community grant. See [`references/grants.md`](references/grants.md).
For the authoritative reference: https://huggingface.co/docs/hub/spaces-overview
## 2. Look for an existing demo first
Before deciding how to build anything, search for prior art:
```bash
hf spaces search "<model name or task>" --sdk gradio --limit 10
```
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.
## 3. Decide SDK and hardware
Follow the user's explicit request first. If they were vague:
- **Default for a public ML demo**: Gradio + ZeroGPU. Use this unless something below applies.
- **The model's only inference path is non-PyTorch** (ONNX / TF / JAX / vLLM as the MAIN model, with heavy init): dedicated GPU.
- 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.
- **Tiny / CPU-bound model, or API-proxy Space**: `cpu-basic` — but it needs a paid plan. On a free account, put it on `zero-a10g` with a no-op decorated function (ZeroGPU requires at least one) and keep the real work outside it — nothing ever requests a GPU, so no quota is burned. See [`references/inference-providers.md`](references/inference-providers.md).
- **Browser-side ML or project page**: Static.
- **Container with non-Python stack**: Docker.
### Sourcing the model
- **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).
- **HF model repo** — read its README, follow any linked GitHub.
- **Paper / blog post** — look for an official or unofficial implementation. Don't reimplement unless trivial or the user explicitly asks.
- **Vague request** — search Spaces first; surface results.
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.
## 4. Create the Space
```bash
hf repos create <namespace>/<name> --type space --space-sdk <gradio|docker|static> \
[--flavor zero-a10g|cpu-basic|<paid-flavor>] \
[--secrets KEY=val] [--env KEY=val] \
--public|--private|--protected \
--exist-ok
```
- `--space-sdk` is required.
- `--flavor` selects hardware. `zero-a10g` is the (legacy) identifier for ZeroGPU. Omitting it gives `cpu-basic` — which is itself gated behind a paid plan, so on a free account pass `--flavor zero-a10g` explicitly. Run `hf spaces hardware` for the full paid list and pricing.
- Visibility: `--public` (anyone can view), `--private` (only you), `--protected` (app is reachable but git repo / Files tab is private).
- `--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`.
- `--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.).
> 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>`.
## 5. Build the app
The Space now exists at `https://huggingface.co/spaces/<namespace>/<name>` but is empty.
### README.md frontmatter
Always required:
```yaml
---
title: ...
emoji: 🚀 # pick something representative
colorFrom: blue # red|yellow|green|blue|indigo|purple|pink|gray (only these)
colorTo: indigo
sdk: gradio # gradio | docker | static
sdk_version: 6.15.1 # latest stable unless you have a reason*
app_file: app.py # gradio only (docker / static use Dockerfile / index.html)
short_description: ... # ≤ 60 chars (server rejects longer)
python_version: "3.12" # ZeroGPU officially supports 3.10.13 and 3.12.12
startup_duration_timeout: 30m # default; bump to 1h for big LLMs / heavy downloads
---
```
\* 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).
All frontmatter options: https://huggingface.co/docs/hub/spaces-config-reference
### Minimal ZeroGPU Gradio app
```python
import spaces # MUST come before torch / diffusers / transformers
import torch
import gradio as gr
from diffusers import DiffusionPipeline
pipe = DiffusionPipeline.from_pretrained("<repo>", torch_dtype=torch.bfloat16).to("cuda")
@spaces.GPU(duration=60)
def generate(prompt: str):
"""Generate an image from a text prompt.""" # docstring → API / MCP tool description
return pipe(prompt).images[0]
gr.Interface(fn=generate, inputs=gr.Text(), outputs=gr.Image()).launch(mcp_server=True)
```
Three rules — full treatment in [`references/zerogpu.md`](references/zerogpu.md):
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.
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.
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.
### Examples, docstrings, and MCP
- **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).
- **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.
- **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.
### requirements.txt
Short version:
- **Do NOT list**: `gradio`, `spaces`, `huggingface_hub` (preinstalled and platform-managed; pinning them causes resolution failures or silently breaks the ZeroGPU runtime).
- **Do list if you use them**: `torchvision`, `torchaudio` (not preinstalled), plus everything else (`diffusers`, `transformers`, `accelerate`, `sentencepiece`, …).
- 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.
- 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).
### Per-SDK depth
- **Gradio patterns** (themes, `gr.Examples`, streaming, custom HTML components, `gr.Server`): [`references/gradio.md`](references/gradio.md).
- **Docker**: https://huggingface.co/docs/hub/spaces-sdks-docker. Examples: `hf spaces list --filter docker`.
- **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.
- **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.
## 6. Iterate on the Space, not locally
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.
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.
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).
## 7. Verify
Don't trust `RUNNING` alone — the app can be running but broken. Four steps, in order:
**A. Alive?** Stage + hardware:
```bash
hf spaces info <ns>/<name> --expand runtime
```
**B. Logs clean post-boot?** Read the run log to confirm startup finished without warnings or silent fallbacks:
```bash
hf spaces logs <ns>/<name> --tail 200
```
Look for model-load completion, no import warnings, no "falling back to CPU" / dtype downgrade messages, no `RUNNING` masking a half-broken app.
**C. API actually responds.** With logs still tailing in another terminal (`hf spaces logs <ns>/<name> --follow`), call the endpoint:
```python
from gradio_client import Client, handle_file
import os
c = Client("<ns>/<name>", token=os.environ["HF_TOKEN"], httpx_kwargs={"timeout": 600})
print(c.view_api()) # discover endpoints — don't guess
result = c.predict(..., api_name="/generate")
```
**D. Sniff output AND logs.** HTTP 200 ≠ correct output. Check both:
```python
head = open(result, "rb").read(16)
# glTF / \x89PNG / RIFF…WEBP / RIFF…WAVE / [4:8]==b"ftyp" → png/jpg/webp/wav/mp4
```
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.
Full smoke-test patterns (streaming endpoints, OAuth-gated Spaces, `gr.Server` custom routes): [`references/debugging.md`](references/debugging.md).
## 8. Permanent storage (buckets)
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**:
```bash
hf buckets create <ns>/<bucket-name> # --private optional
hf spaces volumes set <ns>/<space> -v hf://buckets/<ns>/<bucket-name>:/data # read-write at /data
```
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).
## 9. When things break
Order of operations:
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.
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.
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.
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.
---
## Reference index
| When to read | File |
|---|---|
| **How ZeroGPU works** + correct patterns (decorator, sizing, pickle, generators, real-time, AoTI) | [`references/zerogpu.md`](references/zerogpu.md) |
| **Iterate + debug**: logs, rung ladder, smoke testing (and dev mode + SSH as a last resort) | [`references/debugging.md`](references/debugging.md) |
| **Error-string lookup** — the single place for all error symptoms (Spaces, ZeroGPU, Gradio, deps) | [`references/known-errors.md`](references/known-errors.md) |
| Pinning deps, picking wheels, torch-family alignment | [`references/requirements.md`](references/requirements.md) |
| `gr.Examples` (add when it makes sense), themes, custom HTML components, `gr.Server`, MCP server (`mcp_server=True`) | [`references/gradio.md`](references/gradio.md) |
| Persistent storage, public bucket URLs | [`references/buckets.md`](references/buckets.md) |
| Community grant requests (hardware the user can't pay for) | [`references/grants.md`](references/grants.md) |
| Provider proxy (zero-VRAM big LLM via Cerebras / Fireworks / Together / etc.) | [`references/inference-providers.md`](references/inference-providers.md) |
| **3D Spaces: generation, CUDA extensions, output formats, and model recipes (incl. gaussian splatting)** | [`references/3d-generation.md`](references/3d-generation.md) |
3d-cuda-extensions.md 9.1 KB
# CUDA extensions for 3D Spaces on ZeroGPU
General ZeroGPU rules live in [`zerogpu.md`](zerogpu.md); wheel-tag anatomy and the prebuilt Blackwell wheel dataset live in [`requirements.md`](requirements.md). This file covers what makes 3D generation models harder than diffusion image models: native CUDA/C++ extensions and heavyweight multi-stage pipelines.
## The core constraint: no nvcc at build time
The ZeroGPU build container has **no CUDA toolkit and no GPU**. Any package that compiles CUDA at pip-install time (nvdiffrast, diff-gaussian-rasterization, torchmcubes, spconv-from-source, custom rasterizers, flash-attn sdist) **cannot be installed from `requirements.txt`** the normal way. At *runtime*, a CUDA toolkit is mounted at `/cuda-image/usr/local/cuda-13.0` (nvcc available once the app process is up), and the GPUs are RTX PRO 6000 Blackwell (**sm_120**).
Every working 3D Space uses one of three strategies, in order of preference:
### Strategy 1 — prebuilt wheels in requirements.txt (best)
Direct wheel URLs whose tags match the runtime exactly. Check sources in this order:
1. **The `multimodalart/zerogpu-blackwell-wheels` dataset** — covers `nvdiffrast`, `diff_gaussian_rasterization` (upstream Inria API), `torchmcubes`, `flash_attn`, `xformers`, `pytorch3d`. Cell-picking rules and per-package caveats in [`requirements.md`](requirements.md).
2. **The official Space for your model family** — its requirements.txt often links wheels for the model's bespoke extensions (e.g. `microsoft/TRELLIS.2` links Blackwell wheels for `flex_gemm`, `nvdiffrast`, `nvdiffrec_render`, `cumesh`, `o_voxel` on GitHub Releases).
3. **Build one yourself** on any CUDA machine (`TORCH_CUDA_ARCH_LIST="12.0+PTX" pip wheel .`) and host it in a Hub repo or commit it to the Space. No CUDA machine at hand? **Build it on HF Jobs** — pick a devel image matching the target runtime and let the job upload the wheel to a Hub repo:
```bash
hf jobs run --flavor rtx-pro-6000 --timeout 30m --secrets HF_TOKEN \
pytorch/pytorch:2.11.0-cuda13.0-cudnn9-devel \
bash -c 'export TORCH_CUDA_ARCH_LIST="12.0+PTX" && \
pip wheel --no-build-isolation --no-deps \
git+https://github.com/<org>/<extension>.git -w /tmp/wheels && \
pip install -U huggingface_hub && \
hf upload <user>/zerogpu-wheels /tmp/wheels wheels --repo-type dataset'
```
Then reference `https://huggingface.co/datasets/<user>/zerogpu-wheels/resolve/main/wheels/<file>.whl` in requirements.txt, or download and commit the wheel to the Space (Strategy 2). Three things to line up: the image's **torch + CUDA** must match the Space's pins (the tag above matches today's torch 2.11/cu130 ZeroGPU runtime — adjust as it moves), and the image's **Python** sets the wheel's cp tag, so check it matches the Space's `python_version:`. The `rtx-pro-6000` flavor is the same Blackwell sm_120 silicon as ZeroGPU, so the same job can `pip install` the fresh wheel and smoke-test the kernel before uploading; a cheaper flavor also works for compile-only (the arch comes from `TORCH_CUDA_ARCH_LIST`, not the attached GPU). Jobs bill by the minute and require a paid plan — a typical extension builds in well under 30 minutes.
When requirements contain a wheel URL, **pin `torch==` and `python_version:` to match its tags** (see `requirements.md`) — otherwise a base-image bump silently breaks the wheel. A tag mismatch is an `ImportError` (or a kernel-launch crash for a missing arch) at first import.
### Strategy 2 — wheel file committed to the Space repo
Same as Strategy 1 but the `.whl` lives in the Space repo and is installed at module-import time in `app.py` (the Hunyuan3D pattern, for their bespoke `custom_rasterizer`):
```python
import subprocess, shlex
subprocess.run(shlex.split("pip install custom_rasterizer-0.1-cp310-cp310-linux_x86_64.whl"), check=True)
```
Use when you built the wheel yourself and don't want an external URL dependency. The cp tag dictates `python_version:`.
### Strategy 3 — JIT compile at startup (fallback, e.g. for forks with no wheel)
**CPU-only extensions** (pybind11, plain C++): compile at module import with g++ — seconds, no GPU needed. Hunyuan3D's mesh painter:
```python
os.system("cd /home/user/app/hy3dpaint/DifferentiableRenderer && bash compile_mesh_painter.sh")
# the script is one line: c++ -O3 -shared -std=c++11 -fPIC $(python -m pybind11 --includes) x.cpp -o x$(python3-config --extension-suffix)
```
**CUDA extensions**, two variants seen in production:
*At module import, no GPU attached* (TripoSR's torchmcubes before its wheel existed, SF3D's texture_baker). Compiling needs only nvcc/headers, not a GPU — but you **must force the arch list** since nvcc can't probe a device:
```python
subprocess.run(
shlex.split("pip install --no-build-isolation ./texture_baker"),
env={**os.environ, "TORCH_CUDA_ARCH_LIST": "12.0+PTX"},
check=True,
)
```
*Inside a one-shot `@spaces.GPU(duration=600)` setup function called at module import* (`trellis-community/TRELLIS`, `dylanebert/LGM-mini` — the latter for the ashawkey diff-gaussian-rasterization fork that has no wheel). The full pattern: point `CUDA_HOME` at `/cuda-image/usr/local/cuda-13.0`, silence torch's CUDA-version check (torch cu128 vs nvcc 13.0) via a `sitecustomize.py` that no-ops `torch.utils.cpp_extension._check_cuda_version`, `pip install --no-build-isolation --no-deps git+<repo>`, then preload `ctypes.CDLL(".../libcudart.so.13", mode=ctypes.RTLD_GLOBAL)`. Copy it verbatim from one of those Spaces; don't reinvent it.
JIT costs: slower cold starts, a burned GPU allocation (second variant), and breakage when the runtime image moves. Prefer wheels; when you do JIT-build, log clearly so failures are diagnosable from the run logs — **a failed `os.system("pip install ...")` does not kill the app**; it resurfaces later as an ImportError or a silently degraded feature.
## Attention backends on Blackwell
Covered in [`requirements.md`](requirements.md) (flash_attn / xformers wheels, FA3-on-sm_120 crashes) and [`zerogpu.md`](zerogpu.md) → Attention backends. 3D-specific note: when a model exposes a backend env var (`ATTN_BACKEND` in TRELLIS: `xformers|flash_attn|sdpa|naive`), `sdpa` is the zero-dependency safe choice; set it before importing the model library.
## Durations for 3D workloads
Declared duration is billed against quota as requested (not actual runtime) and drives queue priority — declare honestly:
| Task | duration |
|---|---|
| Fast-tier single forward (TripoSR, SF3D), splat decode (TripoSplat, LGM) | default 60 (or lower for queue priority) |
| Hunyuan3D shape-only | 40–60 |
| TRELLIS / TRELLIS.2 generation; GLB extraction | 120 each |
| Hunyuan3D shape + RGB texture | 90 |
| Hunyuan3D-2.1 shape + PBR texture | 180 |
Multi-stage pipelines: split stages into separate `@spaces.GPU` functions **only when the user can act between them** (TRELLIS's generate → re-extract-at-different-quality split). Otherwise one decorated function per user action — each GPU entry costs a queue pass and a pickle round-trip.
## Passing 3D data across the GPU boundary
`@spaces.GPU` functions run in a forked process; args/returns cross via pickle (full rules in [`zerogpu.md`](zerogpu.md)). For 3D specifically:
- **Meshes/splats**: write files to a per-session temp path inside the GPU function, return the path string. Gaussian objects in these codebases are custom classes (CUDA tensors, sometimes locks) — they can never cross the boundary; do preprocess → sample → decode → file-write in one decorated function and return only paths.
- **Intermediate latents between GPU calls**: CPU numpy dicts in `gr.State` (the TRELLIS pattern), rebuilt on cuda in the next call.
- **`torch.cuda.empty_cache()` at the end of each GPU function** — 3D pipelines fragment VRAM fast on warm workers.
- Never decorate bound methods (ml-sharp's `ModelWrapper` holds a non-picklable `threading.RLock`; wrap module-level functions instead).
## Memory
ZeroGPU `large` (48 GB) fits everything covered here (heaviest: Hunyuan3D-2.1 full PBR ~29 GB, TRELLIS.2 ≥24 GB). Don't request `size="xlarge"` unless a real OOM shows in the run logs. `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True` (before importing torch) is the first fix for fragmentation OOMs on multi-stage pipelines.
## Failure checklist for 3D Spaces
(Also grep [`known-errors.md`](known-errors.md) — general errors are catalogued there.)
1. `ImportError: ...so: undefined symbol` / `cannot open shared object` → wheel-tag mismatch. Re-check torch pin, `python_version:`, CUDA suffix.
2. `RuntimeError: CUDA error: invalid argument` at first attention call → FA3-on-Blackwell dispatch; see `requirements.md`.
3. `nvcc not found` in **build** logs → a source CUDA dep leaked into requirements.txt; move it to a wheel or startup compile.
4. `No space left on device` → offload-disk overflow; too many model variants/stages pinned at module scope.
5. Hang at first request right after generation completes → a CUDA tensor (often nested in a dict/dataclass) crossed the pickle boundary.
6. App RUNNING but a feature is missing (e.g. texture button gone) → a startup `pip install`/compile failed silently; read the run log from the top.
3d-generation.md 8.5 KB
# 3D generation Spaces
Building a Space whose output is a 3D asset — image (occasionally text) in, downloadable and in-browser-viewable **mesh** (GLB/OBJ/PLY/STL) or **gaussian splat** (`.ply`/`.splat`) out. Read this whenever the user wants a Space/demo/playground for a 3D generation model, whether a stock checkpoint or their own finetuned variant. NeRF pipelines and world/scene models (HunyuanWorld, HY-World) are not covered.
The standard workflow in `SKILL.md` applies (create → build → iterate → verify). This file is the 3D entry point; the sub-references below cover the 3D-specific deltas.
## Sub-references
| When to read | File |
|---|---|
| CUDA/C++ extension handling — prebuilt wheels, startup-compile tricks, the dominant failure mode | `[3d-cuda-extensions.md](3d-cuda-extensions.md)` |
| Output formats (GLB/OBJ/PLY/STL, splats), viewers, orientation, preprocessing, temp-file patterns | `[3d-outputs.md](3d-outputs.md)` |
| Model selection details and per-family recipes (TRELLIS, Hunyuan3D, TripoSR, SF3D, …) | `[3d-models.md](3d-models.md)` |
| Gaussian-splat deliverables (TripoSplat, LGM) — pure-PyTorch splat decode | `[3d-gsplat.md](3d-gsplat.md)` |
## What makes 3D Spaces different
1. **Native extensions.** These models need CUDA/C++ extensions (nvdiffrast, rasterizers, marching cubes, texture bakers) that cannot compile at Space build time. Working Spaces use prebuilt wheels or startup-compile tricks — [`3d-cuda-extensions.md`](3d-cuda-extensions.md). Getting this wrong is the dominant failure mode.
2. **Vendored model code.** None of the major 3D models are cleanly pip-installable; every official Space carries the model library as a source tree in the Space repo. There is no `diffusers`-style one-liner. (Don't trust PyPI lookalikes: `trellis-3d` ships the Python tree without the CUDA extensions or the real dependency set.)
Both points make **"duplicate the official Space, then edit"** beat "assemble from scratch" here more than for any other model class.
## Picking a model
| Priority | Pick | Why | Reference |
|---|---|---|---|
| Best quality, PBR textures | **TRELLIS.2** | current quality bar; MIT; ≥24 GB (fits ZeroGPU large) | [`3d-models.md`](3d-models.md) |
| Textured output, finetuning story | **Hunyuan3D-2.1** (2.0 for lighter/faster) | official training code → common finetune target; PBR paint stage; non-commercial license | [`3d-models.md`](3d-models.md) |
| Speed / high-traffic / simplicity | **TripoSR** (untextured, MIT) or **SF3D** (textured, gated) | single forward pass, ~60s duration, tiny codebase | [`3d-models.md`](3d-models.md) |
| Gaussians alongside mesh, multi-image input | **TRELLIS 1** | dual gaussian+mesh decoder; lighter than TRELLIS.2 | [`3d-models.md`](3d-models.md) |
| Gaussian splats as the deliverable | **TripoSplat** (or LGM) | pure-PyTorch splat decode, no rasterizer needed; `gr.Model3D` renders splat `.ply` natively | [`3d-gsplat.md`](3d-gsplat.md) |
**Check gating and license in Phase 0, not at first build.** `stabilityai/stable-fast-3d` and `stable-point-aware-3d` are gated (`gated: auto`) — the user must have accepted the license and the Space needs `HF_TOKEN` as a secret; verify access with `hf repos info` / `HfApi().model_info()` up front. `tencent/Hunyuan3D-*` is ungated but **non-commercial** — flag before the Space goes public. TRELLIS/TripoSR/TripoSplat/LGM are MIT. Apple SHARP is research-only (`apple-amlr`).
If the model isn't covered by a reference file (Direct3D, TripoSG, Step1X-3D, a new release…), proceed by analogy with the user's agreement: find its official/most-liked *working* Space, fetch its actual files, and apply the same analysis — never guess a 3D dependency stack from memory.
## Deployment path: duplicate vs build
**Duplicate the official Space** (default for stock checkpoints, and for finetunes that are a `from_pretrained` swap — each reference file documents the swap):
```python
from huggingface_hub import HfApi
api = HfApi()
api.duplicate_repo("tencent/Hunyuan3D-2", to_id=f"{username}/my-hunyuan3d",
repo_type="space", private=True, space_hardware="zero-a10g",
space_secrets=[{"key": "HF_TOKEN", "value": hf_token}], # only if a gated/private repo is involved
exist_ok=True)
```
(`duplicate_space` is the deprecated older name.) Confirm the source Space is currently RUNNING first (`hf spaces info <id> --expand runtime`) — a paused/broken source means bitrot. Duplication copies *files only*; pass `space_hardware=`/`space_secrets=` explicitly. Then `hf download <repo> --repo-type space --local-dir .`, make the minimal edits (checkpoint repo-id, title/README, UI trims), and push back with `hf upload ... --repo-type space`. **Resist rewriting working extension-handling code you don't fully understand** — sitecustomize patches, `ctypes.CDLL` preloads, autotune caches, and `zero.startup()` calls all look redundant until removed.
**Build from source** (custom UI, shape-only trims, no live official Space): start from the TripoSR skeleton (the ~200-line app documented in [`3d-models.md`](3d-models.md) — the cleanest template), vendor the model library tree from the official Space or GitHub, and follow [`3d-cuda-extensions.md`](3d-cuda-extensions.md). Budget more debugging iterations than an image-model Space.
Either way, **fetch the official Space's live files first** (`https://huggingface.co/spaces/{id}/raw/main/{path}`) and treat them — not the reference files' pins — as source of truth. The reference files record what shipped as of mid-2026; the ZeroGPU runtime moves and official Spaces track it.
## UI design
Read [`3d-outputs.md`](3d-outputs.md) for formats, viewers, preprocessing, and temp-file patterns. Baseline image-to-3D UI:
- **Input**: image upload → visible preprocessing preview (background removal + crop — show what the model actually receives) → generate.
- **Controls**: only the knobs this model responds to. Seed + randomize always; then per family: sampler steps/guidance (TRELLIS, Hunyuan3D), marching-cubes resolution (TripoSR), remesh/vertex-count/texture-size (SF3D), decimation + texture size at extraction (TRELLIS.2). Don't surface every config field of a research codebase.
- **Output**: `gr.Model3D` (untextured meshes, splats) or `LitModel3D` with HDR lighting (textured/PBR), plus `gr.DownloadButton`s for GLB and secondary formats. Two-stage models (TRELLIS) show a fast turntable preview before the slower GLB extraction.
- **Examples**: 3–6 known-good images lifted from the official Space's assets, `cache_examples=True, cache_mode="lazy"`.
## Verify: 3D-specific additions
On top of the standard smoke test in `SKILL.md` §7:
1. These apps expose **chained endpoints, not one `/predict`** — e.g. TripoSR: `/preprocess` (image → segmented image) then `/generate` (→ mesh files). `Client(...).view_api()` first, then call in sequence, feeding the first result into the second via `handle_file(...)`.
2. **Validate the returned file, not its existence.** Meshes:
```python
import trimesh
m = trimesh.load("out.glb", force="scene")
geoms = list(m.geometry.values()) if hasattr(m, "geometry") else [m]
assert geoms and sum(g.faces.shape[0] for g in geoms) > 0, "empty mesh"
```
Gaussian splat `.ply` (no faces — check point count and splat attributes):
```python
from plyfile import PlyData
v = PlyData.read("out.ply")["vertex"]
assert v.count > 1000, "suspiciously few gaussians"
assert {"f_dc_0", "opacity", "scale_0", "rot_0"} <= set(v.data.dtype.names), "not a gaussian ply"
```
3. **Look at it in the browser once.** Orientation (upright? facing forward?), texture presence, viewer lighting — the failure modes a programmatic check can't catch ([`3d-outputs.md`](3d-outputs.md) → Orientation).
4. Startup-time extension compiles fail *silently* (app still boots, feature degrades) — grep the run log from the top even when everything looks green. Failure checklist: bottom of [`3d-cuda-extensions.md`](3d-cuda-extensions.md).
## What to avoid
- Assembling a TRELLIS/Hunyuan-class Space from scratch when a running official Space exists to duplicate.
- Trusting reference-file version pins over the live official Space's files.
- Compiling CUDA extensions via `requirements.txt` (no nvcc at build time), or `pip install`-ing PyPI lookalike packages for the model libraries.
- Returning meshes/gaussians as in-memory objects from `@spaces.GPU` functions — write files, return paths.
- Fixed output filenames (`output.glb`) — concurrent users clobber each other.
- Declaring green after `RUNNING` + a returned file. Load the mesh, count faces/points, and look at it once.
3d-gsplat.md 7.1 KB
# Gaussian splatting reference
Image-to-3D models whose output is a **gaussian splat** (a point cloud of oriented 3D gaussians) rather than a mesh. Deliverable file: gaussian `.ply` (the INRIA convention — the interchange format everything reads) and optionally `.splat` (antimatter15 32-byte records; smaller, no view-dependent color).
| Model | Repo | License / gating | Official Space (working reference) |
|---|---|---|---|
| TripoSplat | `VAST-AI/TripoSplat` | **MIT, ungated** | `VAST-AI/TripoSplat` (ZeroGPU, running, Gradio 6) |
| LGM | `ashawkey/LGM` (+ `dylanebert/LGM` diffusers port) | **MIT, ungated** | `dylanebert/LGM-mini` and `ashawkey/LGM` (ZeroGPU, running) |
| Apple SHARP | `apple/Sharp` | **apple-amlr — research-only**, ungated | `notaneimu/ml-sharp-3d-viewer` (currently CPU; code is ZeroGPU-ready) |
| Splatter Image | `szymanowiczs/splatter-image-v1` | MIT | `szymanowiczs/splatter_image` (ZeroGPU, running; old Gradio, minimal skeleton) |
| Splatt3R (stereo pair → scene) | `brandonsmart/splatt3r_v1.0` | research code | `brandonsmart/splatt3r` (ZeroGPU, running) |
TRELLIS 1 also exports gaussian `.ply` alongside its mesh — covered in `3d-models.md`.
> **Verify against the live official Space before writing files.** Facts below are as of 2026-07.
## The one decision that shapes everything: rasterize server-side or not?
Rendering gaussians on the server needs a CUDA rasterizer (`diff-gaussian-rasterization` or `gsplat`). Prebuilt Blackwell (sm_120) wheel availability is narrow: the `multimodalart/zerogpu-blackwell-wheels` dataset (see [`requirements.md`](requirements.md)) ships `diff_gaussian_rasterization` with the **upstream Inria API only** (2-tuple return) — the ashawkey fork most LGM-family code imports (4-tuple with alpha+depth) has no wheel, and gsplat's own wheel index tops out at torch 2.4/cu124. Two viable shapes:
**Shape A — no server-side rendering (default, strongly preferred).** The model decodes gaussians as plain PyTorch tensors; you write a `.ply` and let the *browser* render it. No CUDA extension at all — `requirements.txt` can be as small as `gradio, torch, torchvision, numpy, safetensors, pillow, tqdm` (TripoSplat's, in full). This is how every modern splat Space works (TripoSplat, SHARP, Splatt3R, Splatter Image; Splatt3R's requirements literally comment out the rasterizer dep).
**Shape B — a real rasterizer (only for server-rendered orbit videos).** If the code uses the upstream Inria API, take the prebuilt wheel from `requirements.md`'s dataset and be done. `ashawkey/LGM` needs its fork, so its Space JIT-builds it — the GPU-worker bootstrap documented in `3d-cuda-extensions.md` Strategy 3: `@spaces.GPU(duration=600)` setup function at module import, `CUDA_HOME=/cuda-image/usr/local/cuda-13.0`, `TORCH_CUDA_ARCH_LIST="12.0"`, sitecustomize no-op of `_check_cuda_version`, `pip install --no-build-isolation --no-deps git+https://github.com/graphdeco-inria/diff-gaussian-rasterization.git`, then `ctypes.CDLL(".../libcudart.so.13", RTLD_GLOBAL)`. Copy it from `dylanebert/LGM-mini` verbatim. Don't take this on unless the user explicitly wants server-rendered video output.
## Viewing splats
- **`gr.Model3D` renders gaussian `.ply` and `.splat` natively** (Babylon.js; supported at least since Gradio 4.25, current in 6.x). Return the file path like any other output. `display_mode` is ignored for splats; `clear_color`, `camera_position`, `height` still apply. This is the zero-effort default — use it.
- **Custom JS viewers** give better splat sorting and controls when the demo is the product: TripoSplat serves a Spark.js (`@sparkjsdev/spark`) viewer page in an iframe; ml-sharp vendors a static PlayCanvas SuperSplat build and serves it via `gr.set_static_paths(...)` + `gr.HTML` iframe with `/gradio_api/file=...` URLs. Only go here if `gr.Model3D`'s rendering visibly undersells the model.
- Always add a `gr.DownloadButton` for the `.ply` — splat users take the file to their own viewer/engine.
## Output writing
Gaussian `.ply` (INRIA convention): binary little-endian, vertex props `x,y,z,nx,ny,nz,f_dc_0..2,(f_rest_*),opacity(logit),scale_0..2(log),rot_0..3(quat)`. Model codebases ship their own writer (`save_ply` in LGM/SHARP/TripoSplat) — use it; don't hand-roll unless porting.
Optional `.splat` conversion for lighter downloads (~32 bytes/gaussian, drops view-dependent SH): TripoSplat's `triposplat.py::to_splat_bytes` is a complete pure-numpy reference — position f32×3, scale f32×3 (linear), RGBA u8×4 (`rgb = (f_dc·0.2820948 + 0.5)·255`, alpha = sigmoid(opacity)), quaternion u8×4 (`q·128+128`), records sorted by opacity×volume.
Watch orientation here too: splat conventions differ from viewers' (TripoSplat applies `[[1,0,0],[0,0,-1],[0,1,0]]` on export). If the splat renders sideways in `gr.Model3D`, fix it at export, same as meshes.
## ZeroGPU pickle discipline (bites harder here)
Gaussian objects in these codebases are custom classes (often holding CUDA tensors or locks) — **they cannot cross the `@spaces.GPU` boundary**. Two proven patterns:
- Do *everything* — preprocess, sample, decode, `.ply` write — inside one decorated function and return only path strings (TripoSplat, with an explicit comment to that effect).
- Never decorate bound methods; wrap module-level functions (`spaces.GPU(duration=180)(predict_to_ply)` — ml-sharp, whose `ModelWrapper` holds a non-picklable `threading.RLock`).
Durations: TripoSplat and LGM-mini run on the bare `@spaces.GPU` default 60s; SHARP uses 180. Splat decoding is fast — the multiview-diffusion stage (LGM) is what eats time.
## Model-specific notes
- **TripoSplat** — the current default pick: MIT, running official ZeroGPU Space, fp16 weights well within 48 GB, ~262k gaussians per generation, BiRefNet background removal built in. Caveat when duplicating: the official Space uses a fully custom Gradio 6 `gradio.Server` + `index.html` frontend, not `gr.Blocks` — its HTTP API is bespoke, so either keep it wholesale or rebuild a plain `gr.Blocks` + `gr.Model3D` UI around `TripoSplatPipeline` (the pipeline code is self-contained in `triposplat.py`/`model.py`). Weights download at startup via `hf download VAST-AI/TripoSplat --local-dir ckpts`.
- **LGM** — image → 4 multiview images (ImageDream) → gaussians. `dylanebert/LGM-mini` is the clean diffusers-style duplicate target (both pipelines via `from_pretrained(..., trust_remote_code=True)`, output straight into `gr.Model3D`); `ashawkey/LGM` is the video-rendering variant (Shape B). Both carry an xformers→SDPA monkeypatch for Blackwell — keep it when duplicating (the `xformers 0.0.34` Blackwell wheel in `requirements.md`'s dataset makes the patch unnecessary if you modernize the requirements instead, but the patch is harmless).
- **SHARP** — pip-installable (`sharp @ git+https://github.com/apple/ml-sharp.git@<sha>`), predicts a camera-space *scene* splat from one photo. Research-only license (`apple-amlr`) — tell the user before they build anything commercial. `preload_from_hub` in the frontmatter pre-bakes the checkpoint into the Space image.
- **Splatter Image** — the minimal skeleton (~CVPR 2024, per-pixel gaussians, MIT): good template bones, but its Space pins Gradio 4.27 and a cu113 torch via `pre-requirements.txt` — modernize rather than copy pins.
3d-models.md 19.5 KB
# 3D models: TRELLIS / TRELLIS.2, TripoSR, Stable Fast 3D, SPAR3D, Hunyuan3D
Per-family deployment recipes for mesh-generation models, distilled from the live files of their official Spaces. Gaussian splatting models live in [`3d-gsplat.md`](3d-gsplat.md); the overall workflow in [`3d-generation.md`](3d-generation.md).
## TRELLIS family
The TRELLIS family covers `microsoft/TRELLIS-image-large` (TRELLIS 1, ~1.2B) and `microsoft/TRELLIS.2-4B` (TRELLIS.2). Both are image-to-3D. Both are MIT licensed and ungated — no token needed to download weights.
| Variant | Model repo | Output | VRAM | Official Space (working reference) |
|---|---|---|---|---|
| TRELLIS 1 | `microsoft/TRELLIS-image-large` (mirror: `JeffreyXiang/TRELLIS-image-large`) | Gaussians + mesh → textured GLB, gaussian `.ply` | ~16 GB | `trellis-community/TRELLIS` (ZeroGPU, running) |
| TRELLIS.2 | `microsoft/TRELLIS.2-4B` | High-fidelity PBR-textured GLB | ≥24 GB | `microsoft/TRELLIS.2` (ZeroGPU, running) |
There is no usable pip package (`trellis-3d` on PyPI ships only the pure-Python tree without the CUDA extensions or real dependency set; nothing exists for TRELLIS.2). **Both official Spaces vendor the library source (`trellis/` or `trellis2/`) directly in the Space repo.** Deploying means duplicating the official Space or copying its tree — not `pip install`.
> **Verify against the live official Space before writing files.** Every pin below (torch/CUDA/Python versions, wheel URLs) reflects what the official Space shipped as of 2026-07 and tracks the ZeroGPU runtime, which changes. Fetch the current files first — `hf download <space-id> --repo-type space --local-dir .` or read `https://huggingface.co/spaces/<space-id>/raw/main/requirements.txt` — and treat those as source of truth.
### TRELLIS.2 recipe (prebuilt-wheels strategy)
The `microsoft/TRELLIS.2` Space compiles nothing: every CUDA extension is a prebuilt wheel whose tags match the ZeroGPU runtime exactly (`+torch2.11.0.cu130`, `cp312`, built for Blackwell sm_120). Its frontmatter pins `python_version: 3.12` and `sdk_version: 6.1.0`, and requirements.txt (as of 2026-07) is:
```
--extra-index-url https://download.pytorch.org/whl/cu130
torch==2.11.0
torchvision==0.26.0
triton==3.6.0
pillow==12.0.0
imageio==2.37.2
imageio-ffmpeg==0.6.0
tqdm==4.67.1
easydict==1.13
opencv-python-headless==4.12.0.88
trimesh==4.10.1
transformers==4.57.3
zstandard==0.25.0
kornia==0.8.2
timm==1.0.22
git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8
https://github.com/adithyaxx/flash-attention/releases/download/v2.8.3/flash_attn-2.8.3+cu13torch2.11cxx11abiTRUE-cp312-cp312-linux_x86_64.whl
https://github.com/LDYang694/Storages/releases/download/rtxpro6000/flex_gemm-1.0.0%2Btorch2.11.0.cu130-cp312-cp312-linux_x86_64.whl
https://github.com/LDYang694/Storages/releases/download/rtxpro6000/nvdiffrast-0.4.0%2Btorch2.11.0.cu130-cp312-cp312-linux_x86_64.whl
https://github.com/LDYang694/Storages/releases/download/rtxpro6000/nvdiffrec_render-0.0.0%2Btorch2.11.0.cu130-cp312-cp312-linux_x86_64.whl
https://github.com/LDYang694/Storages/releases/download/rtxpro6000/cumesh-0.0.1%2Btorch2.11.0.cu130-cp312-cp312-linux_x86_64.whl
https://github.com/LDYang694/Storages/releases/download/rtxpro6000/o_voxel-0.0.1%2Btorch2.11.0.cu130-cp312-cp312-linux_x86_64.whl
```
Wheel tags, torch pin, and `python_version:` must agree — see `3d-cuda-extensions.md` for the tag anatomy. TRELLIS.2 uses `flex_gemm` for sparse conv (no spconv).
Module-level setup (order matters — env vars before any torch/trellis import):
```python
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
os.environ["ATTN_BACKEND"] = "flash_attn"
os.environ["FLEX_GEMM_AUTOTUNE_CACHE_PATH"] = os.path.join(..., "autotune_cache.json")
pipeline = Trellis2ImageTo3DPipeline.from_pretrained("microsoft/TRELLIS.2-4B")
pipeline.rembg_model = None # official Space outsources rembg to briaai/BRIA-RMBG-2.0 via gradio_client
pipeline.low_vram = False
pipeline.cuda()
```
**Keep `autotune_cache.json` when duplicating.** The Space commits a pre-computed flex_gemm autotune cache so kernel autotuning doesn't re-run on every fresh ZeroGPU worker. Deleting it makes first-request latency much worse.
GPU functions in the official Space: `@spaces.GPU(duration=120)` on generation (`pipeline.run(...)` with per-stage sampler params, `pipeline_type` of `512` / `1024_cascade` / `1536_cascade`) and `@spaces.GPU(duration=120)` on GLB extraction (`pipeline.decode_latent(...)` + `o_voxel.postprocess.to_glb(...)`). Generation and extraction are split into two GPU calls with latents passed between them as CPU numpy in `gr.State` — keep that split; it lets users re-extract at different decimation/texture sizes without regenerating.
### TRELLIS 1 recipe (JIT-compile strategy)
The `trellis-community/TRELLIS` Space demonstrates the other viable strategy: compile nvdiffrast + diff-gaussian-rasterization **at first boot on a GPU worker**, inside `@spaces.GPU(duration=600)`, using the nvcc that ZeroGPU mounts at runtime (`/cuda-image/usr/local/cuda-13.0`). Its requirements.txt (torch 2.8.0, `spconv-cu120==2.3.6`, `xformers`, `rembg`, no python_version pin → 3.10) installs everything that *can* come from PyPI; the JIT step handles the rest with:
- `TORCH_CUDA_ARCH_LIST="12.0"` (Blackwell — nvcc can't probe a GPU that isn't attached yet)
- a `sitecustomize.py` that no-ops `torch.utils.cpp_extension._check_cuda_version` (torch built for cu128, nvcc is 13.0)
- `pip install --no-build-isolation ./extensions/nvdiffrast` (vendored source), then the mip-splatting `diff-gaussian-rasterization` from a shallow git clone
- afterwards, `ctypes.CDLL("<cuda-libdir>/libcudart.so.13", mode=ctypes.RTLD_GLOBAL)` so the freshly built extensions find the CUDA 13 runtime
Backend env vars, set at the very top of `app.py`: `SPCONV_ALGO=native`, `ATTN_BACKEND=xformers`. Because ZeroGPU is Blackwell, xformers must be forced onto Cutlass kernels (its Flash-Attn-3 dispatch crashes on sm_120) — the Space monkeypatches `xformers.ops.memory_efficient_attention` to default `op=(fmha.cutlass.FwOp, fmha.cutlass.BwOp)`. Don't drop that patch when duplicating.
GPU functions: `@spaces.GPU(duration=120)` for generate-and-extract-GLB (single- and multi-image modes, 120-frame turntable preview video via `render_utils.render_video`, GLB via `postprocessing_utils.to_glb(gs, mesh, simplify=0.95, texture_size=1024)`); bare `@spaces.GPU` for gaussian `.ply` extraction. Viewer: `LitModel3D` from `gradio_litmodel3d==0.0.1` (installed at runtime with `--no-deps` if missing). The Space also sets `demo.launch(mcp_server=True)` — TRELLIS demos double as MCP servers; keep it.
### Deploying a finetuned TRELLIS variant
Both pipelines resolve everything from a `pipeline.json` at the model repo root, so a finetuned checkpoint that keeps the repo layout is a one-line swap:
```python
pipeline = TrellisImageTo3DPipeline.from_pretrained("user/my-finetuned-trellis") # or Trellis2ImageTo3DPipeline
```
If the finetuned repo is private, pass the token via env (`HF_TOKEN` Space secret) — `from_pretrained` in the vendored trellis code goes through `huggingface_hub` and picks it up. If the user only has raw checkpoint files (no `pipeline.json`), copy `pipeline.json` + config layout from the base repo into their model repo first.
### Picking between the two
- **TRELLIS.2** — best quality, PBR materials, 3 resolution tiers; heavier (≥24 GB, fine on ZeroGPU large's 48 GB), Gradio 6, Python 3.12. Default choice for a new Space.
- **TRELLIS 1** — lighter (~16 GB), dual gaussian+mesh output (the gaussian `.ply` path matters if the user wants splats), multi-image conditioning modes, and the community Space is a cleaner codebase to modify. Choose when the user wants gaussians, multi-image input, or minimal VRAM.
### Durations and misc
- Generation: `duration=120` is what both official Spaces use; TRELLIS.2 at 1536³ pushes ~60s of pure compute on H100-class hardware, so don't go below 120.
- Call `torch.cuda.empty_cache()` at the end of each GPU function (both Spaces do) — sequential calls on a warm worker otherwise accumulate.
- TRELLIS.2's mesh simplify cap: `mesh.simplify(16777216)` — nvdiffrast's face-count limit.
- Preprocessing (alpha-bbox crop, resize to ≤1024, background removal) runs on CPU outside the GPU function.
## Mesh workhorses: TripoSR, Stable Fast 3D, SPAR3D, Hunyuan3D
Two groups in this file. The **fast tier** (TripoSR, SF3D, SPAR3D): single-forward-pass image-to-mesh, seconds per generation, small VRAM, simple codebases — pick when the user wants a snappy demo, a high-traffic public Space (short `@spaces.GPU` durations = less quota per click and better queue priority), or can accept lower fidelity than TRELLIS.2. And **Hunyuan3D-2/2.1** (Tencent): two-stage — a flow-matching DiT generates the shape, then an optional multiview-diffusion "Paint" stage textures it — pick when the user wants textured output and TRELLIS.2 doesn't fit, or when they finetuned a Hunyuan3D DiT (the 2.1 release includes official training code, so finetuned shape checkpoints are common).
| Model | Repo | Output | License / gating | Official Space |
|---|---|---|---|---|
| TripoSR | `stabilityai/TripoSR` | untextured mesh (OBJ + GLB) | **MIT, ungated** | `stabilityai/TripoSR` (ZeroGPU, running) |
| Stable Fast 3D (SF3D) | `stabilityai/stable-fast-3d` | UV-unwrapped **textured** GLB | stabilityai-ai-community, **gated (auto)** | `stabilityai/stable-fast-3d` (ZeroGPU, running) |
| SPAR3D | `stabilityai/stable-point-aware-3d` | textured GLB + editable point cloud | stabilityai-ai-community, **gated (auto)** | `stabilityai/stable-point-aware-3d` (dedicated L4, **currently BUILD_ERROR** — reference code only) |
| Hunyuan3D-2.0 | `tencent/Hunyuan3D-2` (subfolder `hunyuan3d-dit-v2-0`; also `-mini`, `-mv`) | GLB, RGB-textured (Paint 2.0) | tencent-hunyuan-community, **ungated, non-commercial** | `tencent/Hunyuan3D-2` (ZeroGPU, running) |
| Hunyuan3D-2.1 | `tencent/Hunyuan3D-2.1` (subfolder `hunyuan3d-dit-v2-1`) | GLB, **PBR**-textured (Paint 2.1) | tencent-hunyuan-community, **ungated, non-commercial** | `tencent/Hunyuan3D-2.1` (ZeroGPU, **paused** — code is still the reference) |
**Licenses and gating matter here.** The two Stability models are `gated: auto` — the deploying user must accept the license on the model page, and the Space needs their `HF_TOKEN` as a secret to download weights at startup; if the gate isn't accepted, `from_pretrained` fails with 401 at build — check before publishing. The Hunyuan models are ungated (no token needed) but the community license restricts commercial use — surface that before the user flips a Space public. TripoSR is MIT and needs nothing.
> **Verify against the live official Space before writing files.** Pins below are as of 2026-07. Fetch current files via `https://huggingface.co/spaces/<id>/raw/main/<path>` first.
### TripoSR — the minimal recipe (~200-line app)
The simplest working 3D Space on the Hub, and the best starting skeleton for a from-scratch mesh demo. `tsr/` package vendored in the Space; frontmatter pins `python_version: 3.10.13`, `sdk_version: 4.20.1`.
One CUDA extension, JIT-built at module import (marching cubes):
```python
subprocess.run(
shlex.split("pip install --no-build-isolation git+https://github.com/tatsy/torchmcubes.git"),
env={**os.environ, "TORCH_CUDA_ARCH_LIST": "12.0+PTX"}, # no GPU visible at startup — force Blackwell arch
check=True,
)
```
requirements.txt carries the build toolchain for it (`scikit-build-core>=0.10`, `pybind11>=2.10`, `cmake`, `ninja`) plus `rembg`, `onnxruntime`, `trimesh`, `omegaconf`, `einops`, `transformers`, `Pillow`, `huggingface-hub`. No torch pin (base image). (A prebuilt `torchmcubes` Blackwell wheel now exists in the dataset described in [`requirements.md`](requirements.md) — cleaner than the JIT build when building fresh.)
```python
model = TSR.from_pretrained("stabilityai/TripoSR", config_name="config.yaml", weight_name="model.ckpt")
model.renderer.set_chunk_size(131072)
model.to(device)
@spaces.GPU # default 60s is plenty — the forward pass is ~1s
def generate(image, mc_resolution):
scene_codes = model(image, device)
mesh = model.extract_mesh(scene_codes, resolution=mc_resolution)[0]
mesh = to_gradio_3d_orientation(mesh) # axis fix — see 3d-outputs.md
... # export OBJ + GLB to NamedTemporaryFiles, return both paths
```
Preprocessing on CPU, outside the GPU function: `rembg` background removal → `resize_foreground(image, 0.85)` → composite onto gray. UI: input image + "marching cubes resolution" slider (32–320) + two `gr.Model3D` tabs (OBJ and GLB).
### Stable Fast 3D — textured output, source-built extensions
`sf3d/` vendored; frontmatter `python_version: 3.10.13`, `sdk_version: 4.41.0`. Two vendored extension source dirs built at module import (they're commented out in requirements.txt with a note — the "HF hack"):
```python
os.system(
'CPPFLAGS="-include utility" TORCH_CUDA_ARCH_LIST="12.0+PTX" USE_CUDA=1 '
"pip install -vv --no-build-isolation ./texture_baker ./uv_unwrapper"
)
```
`texture_baker` is a torch CUDAExtension (the `CPPFLAGS="-include utility"` is required for its build), `uv_unwrapper` a plain C++ extension. Other deps of note: `open_clip_torch`, `rembg[gpu]`, `pynanoinstantmeshes` + `gpytoolbox` (remeshing), `gradio-litmodel3d==0.0.1`.
```python
model = SF3D.from_pretrained("stabilityai/stable-fast-3d",
config_name="config.yaml", weight_name="model.safetensors")
model.eval().to(device) # gated repo — needs HF_TOKEN secret with accepted license
@spaces.GPU # default 60s
def run(input_image, remesh_option, vertex_count, texture_size):
with torch.autocast(device_type=device, dtype=torch.bfloat16):
model_batch = create_batch(input_image)
...
trimesh_mesh.export(tmp.name, file_type="glb", include_normals=True)
```
UI controls that earn their place: foreground ratio, remesh (None/Triangle/Quad), target vertex count, texture size (512–2048). Viewer: `LitModel3D` with selectable HDR environment maps — textured output deserves image-based lighting (see [`3d-outputs.md`](3d-outputs.md)).
### SPAR3D — reference code only, don't duplicate blindly
Two-stage: point-cloud diffusion → mesh, with a `gradio_pointcloudeditor` step so users can edit the intermediate point cloud before meshing. Distinctive UI idea worth stealing. But the official Space runs on **dedicated L4, not ZeroGPU** (no `import spaces`, torch pinned to 2.5.1, real nvcc assumed) and is currently in BUILD_ERROR. To deploy SPAR3D on ZeroGPU you'd port it: add `spaces`, drop the torch pin, apply the SF3D extension-build pattern (same vendored `texture_baker`/`uv_unwrapper` + a prebuilt `pynim` wheel), and decorate the two stages. Budget real debugging time; propose SF3D instead unless the user specifically needs the point-cloud editing stage. Its background removal uses `transparent-background` (InSPyReNet) rather than rembg.
### Hunyuan3D-2 / 2.1 — textured two-stage generation
Both official Spaces vendor the model code in the Space repo (`hy3dgen/` for 2.0; `hy3dshape/` + `hy3dpaint/` for 2.1) — there's a `setup.py` but nothing is pip-installed; imports resolve from cwd. Two native extensions are handled at module-import time in `gradio_app.py`:
```python
# custom_rasterizer: prebuilt CUDA wheel committed to the Space repo (no nvcc at build time)
subprocess.run(shlex.split("pip install custom_rasterizer-0.1-cp310-cp310-linux_x86_64.whl"), check=True)
# mesh painter: CPU-only pybind11 extension, compiled with plain g++ in seconds
os.system("cd /home/user/app/hy3dpaint/DifferentiableRenderer && bash compile_mesh_painter.sh")
```
The cp310 wheel means Python 3.10 — pin `python_version: "3.10"` explicitly when duplicating so a runtime default bump can't break it.
**Requirements notes (2.1)** — fully pinned; the non-obvious entries: `--extra-index-url https://download.blender.org/pypi/` + `bpy==4.0` (Blender-as-pip; installs headless with no display setup — see [`3d-outputs.md`](3d-outputs.md) → Headless Blender — though the Space's OBJ→GLB conversion actually runs on trimesh+pygltflib); `realesrgan==0.3.0` + `basicsr==1.4.2` (texture upscaling — needs the Space's `torchvision_fix.py` shim, applied at the top of `gradio_app.py` *and* again before the texgen import, because basicsr imports the removed `torchvision.transforms.functional_tensor`); `cupy-cuda12x`, `pymeshlab`, `xatlas`, `open3d`, `trimesh`, `pygltflib` (mesh stack); **no torch pin**; `pydantic==2.10.6` (gradio compat).
**Model loading** (module level):
```python
from hy3dshape.pipelines import Hunyuan3DDiTFlowMatchingPipeline # hy3dgen.shapegen on 2.0
shape_pipe = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
"tencent/Hunyuan3D-2.1", subfolder="hunyuan3d-dit-v2-1", use_safetensors=False,
) # 2.0: repo "tencent/Hunyuan3D-2", subfolder "hunyuan3d-dit-v2-0", use_safetensors=True, + .enable_flashvdm()
# Texture stage — wrap in try/except and degrade to shape-only if it fails (official HAS_TEXTUREGEN pattern)
from hy3dpaint.textureGenPipeline import Hunyuan3DPaintPipeline, Hunyuan3DPaintConfig
paint_pipe = Hunyuan3DPaintPipeline(Hunyuan3DPaintConfig(max_num_view=8, resolution=768))
```
**GPU decorators**: `@spaces.GPU(duration=40–60)` shape-only; `@spaces.GPU(duration=90)` (2.0) / `@spaces.GPU(duration=180)` (2.1 PBR) shape+texture. VRAM (2.1, per its README): ~10 GB shape, ~21 GB texture, ~29 GB both — fits ZeroGPU large, but the full PBR path is the heaviest recipe in these references; don't shave the duration.
**Output path gotcha (2.1)**: textured meshes export as **OBJ first, then convert to GLB** via the Space's `convert_utils` (obj2gltf with PBR materials) — direct GLB export from the paint pipeline core-dumps. Keep the conversion step when duplicating.
**Serving quirk**: both official Spaces use a custom `<model-viewer>` HTML iframe + FastAPI `StaticFiles` + `gr.mount_gradio_app` + manual `uvicorn.run` instead of `demo.launch()` — which requires calling `from spaces import zero; zero.startup()` manually before uvicorn. **When building fresh rather than duplicating, skip all of this** — export a GLB, show it in `gr.Model3D`/`LitModel3D`, and let `demo.launch()` do its job. Only keep the iframe machinery when duplicating wholesale.
**Local-run pattern worth copying**: 2.1's `gradio_app.py` defines a no-op `spaces.GPU` decorator when not running on Spaces (`ENV != "Huggingface"`), so the same file runs on a local GPU box unchanged.
**Deploying a finetuned Hunyuan3D variant** — the official 2.1 release ships training code (`hy3dshape/` includes trainers and configs), so "I finetuned Hunyuan3D, make me a demo" is a real request. The shape pipeline resolves `subfolder` inside the model repo:
```python
shape_pipe = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
"user/my-finetuned-hunyuan3d", subfolder="hunyuan3d-dit-v2-1",
)
```
If the user's repo keeps the official layout (config + checkpoint under the dit subfolder), it's a repo-id swap; if they saved a bare checkpoint, mirror the base repo's subfolder structure into their repo first. Finetunes are almost always **shape-only** — keep the stock Paint stage from the base repo for texturing (it conditions on the input image, not the shape checkpoint). Private repo → `HF_TOKEN` Space secret.
**Which Hunyuan variant**: **2.1** — PBR texturing, the one with official training code, the default for finetunes, heaviest. **2.0** — lighter, faster (flashvdm), RGB textures, official Space actually running today (known-good duplicate target); `-mini` and `-mv` (multiview-conditioned) subfolder variants live in the same repo. **Shape-only demo** (skip Paint entirely) — halves the dependency surface (no bpy/realesrgan/basicsr/cupy) and cuts duration to 40–60s; offer it when the user just wants geometry.
3d-outputs.md 9.3 KB
# Mesh outputs: formats, viewers, preprocessing
## Formats
**GLB is the default output format.** It's self-contained (geometry + materials + textures in one binary file), renders in every in-browser viewer, and is what all the major official 3D Spaces produce. Offer OBJ/PLY/STL as secondary downloads, not as the primary view.
| Format | Carries | When to offer |
|---|---|---|
| GLB | geometry + normals + UVs + PBR materials + embedded textures | always — primary output |
| OBJ (+MTL) | geometry, UVs; textures via sidecar files | DCC-tool users; note multi-file awkwardness in a web download |
| PLY | geometry, vertex colors; also the container for gaussian splats (see `3d-gsplat.md`) | point clouds, vertex-colored meshes, splats |
| STL | bare geometry | 3D-printing crowd |
Conversion is trimesh one-liners — the Hunyuan3D Spaces expose exactly this as an "export" accordion:
```python
mesh = trimesh.load("out.glb")
mesh.export("out.obj") # or .ply / .stl — inferred from extension
```
Two exceptions to "just use trimesh":
- **PBR materials**: trimesh's GLB export handles baseColor fine but degrades full PBR (metallic/roughness/normal maps). Hunyuan3D-2.1 exports OBJ then converts with obj2gltf specifically because its direct GLB export core-dumps — when a pipeline ships its own exporter (`to_glb`, `convert_utils`, `o_voxel.postprocess`), use it instead of round-tripping through trimesh.
- **Normals**: pass `include_normals=True` on trimesh GLB exports (SF3D does) — missing normals render matte-black in some viewers.
## Orientation
The #1 "it works but looks wrong" bug. Model output conventions (often Z-up, or −Y-forward from the training renders) don't match the viewers' glTF convention (Y-up, +Z toward camera), so meshes come out lying face-down or backwards. TripoSR's fix:
```python
def to_gradio_3d_orientation(mesh):
mesh.apply_transform(trimesh.transformations.rotation_matrix(-np.pi/2, [1, 0, 0])) # Z-up → Y-up
mesh.apply_transform(trimesh.transformations.rotation_matrix( np.pi/2, [0, 1, 0]))
return mesh
```
The exact rotation is per-model — copy it from the official Space's app (search for `rotation_matrix` or `apply_transform`). If output is mirrored, the model bakes a flipped X; TripoSR's OBJ export flips `mesh.vertices[:, 0]` back. Verify orientation visually during the smoke-test; it can't be caught from exit codes.
## Viewers
- **`gr.Model3D`** — built-in, zero extra deps, fine for untextured or baseColor meshes; also renders gaussian splat `.ply`/`.splat` natively (see `3d-gsplat.md`). Useful kwargs: `display_mode="solid"` (default point cloud rendering ruins meshes in some versions; ignored for splats), `clear_color=(0.25, 0.25, 0.25, 1.0)`, `height=...`. Default choice.
- **`LitModel3D`** (`gradio_litmodel3d==0.0.1`, a Hub custom component) — adds image-based lighting with HDR environment maps. Worth the extra dep for **textured/PBR** output, where flat lighting hides the texture quality (SF3D and trellis-community both use it, SF3D with a selectable `.hdr` set). Textured model + plain `gr.Model3D` undersells the result.
- **Custom `<model-viewer>` iframe + FastAPI static mount** — what the Hunyuan Spaces do. Maximum control, but requires abandoning `demo.launch()` for manual uvicorn plus a manual `spaces.zero.startup()` call. Don't build this fresh; only keep it when duplicating a Space that already has it.
- **Turntable preview** — TRELLIS renders a 120-frame orbit video (`imageio.mimsave`, fps=15) shown in `gr.Video` *before* the user commits to GLB extraction; TRELLIS.2 uses a base64-JPEG JS orbiter. Good pattern when extraction is a separate, slower step; skip it for fast-tier models where the mesh is ready immediately.
Always pair the viewer with `gr.DownloadButton` for the raw file — the viewer is a preview, the file is the deliverable.
## Input preprocessing (image-to-3D)
Every image-to-3D model expects a **segmented foreground object**, roughly centered, on neutral/transparent background. The shared recipe, run on CPU *outside* the GPU function:
1. **Respect an existing alpha channel.** If the upload is RGBA with a real alpha, skip segmentation (TRELLIS checks this first).
2. **Otherwise remove the background** — `rembg` (u2net, onnxruntime; the common choice), `transparent-background` (InSPyReNet; SPAR3D), or BiRefNet. TRELLIS.2 outsources to the `briaai/BRIA-RMBG-2.0` Space via `gradio_client` — fine for an official Space, but a fragile external dependency for a user Space; prefer local rembg.
3. **Crop to the alpha bbox, resize** (≤1024 for TRELLIS-class, 512 for fast tier), **rescale the foreground** to ~85% of frame (`foreground_ratio` slider in the Stability Spaces), composite onto neutral gray or keep alpha.
Show the preprocessed image in the UI before generation — users need to see what the model actually gets, and a bad segmentation explains a bad mesh. Loading the rembg session at startup (TRELLIS runs one dummy `preprocess_image` at boot) avoids a first-click latency spike.
## Temp files and concurrency
Handlers run concurrently; never write to fixed paths. The pattern used by the official Spaces:
```python
demo = gr.Blocks(delete_cache=(600, 600)) # sweep files older than 600s every 600s
@demo.load(outputs=...)
def start_session(req: gr.Request):
session_dir = os.path.join(TMP_ROOT, str(req.session_hash))
os.makedirs(session_dir, exist_ok=True)
```
or simply `tempfile.NamedTemporaryFile(suffix=".glb", delete=False)` per call (TripoSR/SF3D). Either works; never a bare `"output.glb"`.
## Headless Blender (bpy / renders)
Blender shows up in 3D Spaces two ways: as the **`bpy` pip module** (`--extra-index-url https://download.blender.org/pypi/` + `bpy==<pin>`; Hunyuan3D-2.1 pins `bpy==4.0` — which installs cleanly on ZeroGPU with no display setup, though that Space's actual GLB conversion runs on trimesh+pygltflib), or as a **standalone binary** driven by a render script (TRELLIS-dataset-toolkit-style turntables, rigging/preprocessing tools). Spaces containers have no display; the working patterns, all verified from running Spaces:
- **pip `bpy` needs no xvfb.** Mesh ops, Cycles, and Workbench renders work headless — bpy creates its GL context via EGL/Mesa, not X11. The `packages.txt` seen in every working bpy demo Space (e.g. `radames/gradio-blender-bpy`) is just:
```
libegl1-mesa-dev
libgl1-mesa-dev
```
ZeroGPU gotcha: **`import bpy` takes 30–60 s** — never import it inside a `@spaces.GPU` function (it burns the duration budget and aborts the task). Import at module scope, or run a persistent bpy worker in the main process (`VAST-AI/SkinTokens` does file-based IPC to one).
- **A modern Blender binary (≥3.4) needs no xvfb either**: download the tarball at startup, run `blender -b -noaudio --python script.py -- <args>` as a subprocess (`MajorDaniel/UniRig` on ZeroGPU). `packages.txt` then carries the binary's shared-lib deps: `libx11-6 libxi6 libxrender1 libxxf86vm1 libfontconfig1 libsm6 libxkbcommon0 libxkbcommon-x11-0 libgl1-mesa-glx`. Blender's manual is explicit that CLI/background rendering needs no display; a GPU Cycles subprocess must be launched from **inside** `@spaces.GPU` (it inherits the worker's CUDA), while display/env setup is process-global and belongs at module scope.
- **Reach for Xvfb only when forced**: a pinned pre-3.4 Blender binary (no EGL headless support yet), EEVEE on legacy setups, or non-Blender GL stacks (Open3D/VTK offscreen, pyglet). On the **gradio SDK**, don't launch raw `Xvfb :99 &` — the container lacks the `/tmp/.X11-unix` permissions for it (UniRig documents this) — use `pyvirtualdisplay` at module scope, the pattern `gradient-spaces/GuideFlow3D` uses to render Cycles through Blender 3.0.1 headlessly. `packages.txt`:
```
xvfb
libx11-6
libgl1
libxrender1
libxi6
libxkbcommon-x11-0
libsm6
```
and at the very top of `app.py`, before anything touches Blender/GL (plus `pyvirtualdisplay` in requirements.txt):
```python
if os.environ.get("DISPLAY") is None:
from pyvirtualdisplay import Display # drives Xvfb with user-owned sockets
display = Display(visible=0, size=(1920, 1080))
display.start()
os.environ.setdefault("DISPLAY", f":{display.display}")
```
On the **Docker SDK** you control the image: `xvfb-run -a -s '-screen 0 1024x768x24' <cmd>` (or `Xvfb :99 ... & export DISPLAY=:99`), adding Mesa software-GL env on CPU hardware (`LIBGL_ALWAYS_SOFTWARE=1`, `GALLIUM_DRIVER=llvm`).
- **Keep Space renders on Cycles.** EEVEE is GPU-rasterization by design (no CPU path — headless EEVEE exists on Linux ≥3.4 via EGL, but under Xvfb/software-GL it crawls); Cycles renders fine on CPU or on CUDA inside `@spaces.GPU`.
- **pyrender** (not Blender, but the same "needs GL" problem): use EGL, not Xvfb — `os.environ["PYOPENGL_PLATFORM"] = "egl"` with `libgl1-mesa-dev libglu1-mesa-dev freeglut3-dev mesa-common-dev` in packages.txt (`H-Liu1997/EMAGE` on ZeroGPU).
## Examples
`gr.Examples` with a handful of good input images makes or breaks first impressions of a 3D demo. Source them from the official Space's `assets/`/`examples/` dir (they're chosen to work well) or the model repo. On ZeroGPU use `cache_examples=True, cache_mode="lazy"`. Objects that demo well: single centered objects with clear silhouettes — figurines, shoes, furniture, vehicles. Objects that demo poorly: scenes, flat images, humans (most mesh models aren't trained for them), thin structures.
buckets.md 4.3 KB
# Persistent storage with Buckets
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>`.
Buckets are paid (per-TB storage). Check `whoami.canPay` and confirm with the user before creating one. Pricing + free tier: https://huggingface.co/storage.
Full docs: https://huggingface.co/docs/hub/storage-buckets.
## Create + attach
```bash
hf buckets create <ns>/<bucket-name> # --private optional
hf spaces volumes set <ns>/<space> -v hf://buckets/<ns>/<bucket-name>:/data
```
After this, writes to `/data/` in the Space are durable. Reads come from the bucket via the Xet storage backend.
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.
## Write-durable, read-fast pattern
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:
```python
import os, json, uuid
from datetime import datetime, timezone
BUCKET_ID = "<ns>/<bucket-name>"
BUCKET_URL = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve"
_feed = []
def _load_feed():
root = "/data/songs"
if not os.path.isdir(root):
return
for sid in os.listdir(root):
meta = f"{root}/{sid}/meta.json"
if os.path.isfile(meta):
_feed.append(json.load(open(meta)))
_feed.sort(key=lambda s: s["created_at"], reverse=True)
_load_feed() # one scan at startup
@app.api(name="save", time_limit=60)
def save(audio_bytes: bytes, title: str):
sid = uuid.uuid4().hex[:12]
d = f"/data/songs/{sid}"; os.makedirs(d, exist_ok=True)
open(f"{d}/audio.wav", "wb").write(audio_bytes)
meta = {"id": sid, "title": title,
"url": f"{BUCKET_URL}/songs/{sid}/audio.wav",
"created_at": datetime.now(timezone.utc).isoformat()}
json.dump(meta, open(f"{d}/meta.json", "w"))
_feed.insert(0, meta) # cache stays current — no re-scan
return meta
@app.api(name="feed", concurrency_limit=10)
def feed(): return _feed[:50] # zero disk I/O
```
Reference Space using this pattern: https://huggingface.co/spaces/victor/ace-step-jam
## Anti-pattern: bucket as model-weights cache
**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.
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.
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.
## Cache redirects
`/home/user/.cache` is read-only on ZeroGPU. Redirect transient caches at the top of `app.py`, before any library import that uses them:
```python
import os
os.environ.setdefault("HF_HOME", "/data/.cache/huggingface") # or /tmp on non-bucket Spaces
os.environ.setdefault("HF_MODULES_CACHE", "/tmp/hf_modules")
os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib")
```
Missing redirections fail silently or at first matplotlib / transformers / diffusers import.
## Write access from the Space
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>`.
## Security note
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.
debugging.md 11.2 KB
# Debugging and iteration
How to iterate cheaply, read logs, and smoke-test. Dev mode + SSH exists as a last resort (covered at the bottom).
## The rung ladder
Pick the cheapest update mechanism that fits the change. Going one rung too high wastes 30 s – 15 min per cycle.
| Rung | When | Command | Cost |
|---|---|---|---|
| 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 |
| 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 |
| 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 |
`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.
| 4. Factory reboot | Container in inconsistent state (broken pip env, etc.) | `hf spaces restart <id> --factory-reboot` | full rebuild + cold start |
### How hot-reload works
`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.
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).
Independent of dev mode. Marked experimental in the CLI. Requires Gradio SDK 6.1+.
### Footguns
- **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.
- **`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.
- **Concurrent uploads or restart-while-uploading collide.** Wait for one to finish.
- **"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.
## Reading logs
```bash
hf spaces info <id> --expand runtime # stage at a glance
hf spaces logs <id> --build --follow # build log, live
hf spaces logs <id> --follow # run log, live
hf spaces logs <id> --build --tail 500 # bigger window — default is small
```
Find the **first** error in the build log, not the last. Cascading errors after the first are noise.
State machine (terminal states in bold):
```
BUILDING → APP_STARTING → RUNNING
↘ RUNTIME_ERROR
↘ BUILD_ERROR
↘ CONFIG_ERROR
```
For stage-specific lookups, see [`known-errors.md`](known-errors.md).
## Smoke-test patterns
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.
### A. Alive?
```bash
hf spaces info <id> --expand runtime --format json \
| python3 -c "import json,sys; r=json.load(sys.stdin)['runtime']; \
print(r['stage'], r.get('hardware','?'))"
# expect: RUNNING zero-a10g
```
If `requested_hardware` is `cpu-basic` when you wanted GPU, your `--flavor` was rejected silently. Fix with `hf spaces settings <id> --hardware zero-a10g`.
### B. Logs clean post-boot?
```bash
hf spaces logs <id> --tail 200
```
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.
### C. API actually functions?
Default — sync `gr.Interface` / `gr.Blocks` / `gr.ChatInterface` / `gr.Server` `@app.api`:
```python
from gradio_client import Client, handle_file
import os
c = Client("<ns>/<name>", token=os.environ["HF_TOKEN"],
httpx_kwargs={"timeout": 600}) # ≥ @spaces.GPU duration + 60s
print(c.view_api()) # discover endpoints — don't guess api_name
result = c.predict(
handle_file("test.png"), # file inputs need handle_file()
"short prompt",
api_name="/generate", # matches @app.api(name=...) or the function name
)
```
**Streaming endpoints** (function uses `yield` or `TextIteratorStreamer`) — `.predict()` returns only the final value. Iterate chunks via `.submit()`:
```python
job = c.submit("short prompt", api_name="/chat")
for chunk in job: print(chunk, end="")
# or job.result() for the final value
```
**`gr.Server` custom `@app.get/post(...)` routes** don't appear in `view_api()`. Hit them with plain HTTP:
```python
import httpx
r = httpx.post(f"https://<subdomain>.hf.space/your_route",
json={...}, timeout=600,
headers={"Authorization": f"Bearer {os.environ['HF_TOKEN']}"})
```
**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": {...}}`.
**MCP server mode** (`launch(mcp_server=True)`) — different protocol. Use an MCP client.
### D. Output bytes AND logs look right?
HTTP 200 ≠ correct output. Sniff both the returned file and the run log emitted during the call.
```python
head = open(path, "rb").read(16)
# b'glTF...' → glb
# b'\x89PNG' → png
# b'\xff\xd8' → jpeg
# b'RIFF...WEBP' → webp
# b'RIFF...WAVE' → wav
# head[4:8]==b'ftyp' → mp4
# b'ply\n' → ply
```
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).
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.
### What NOT to do
- **Don't launch Playwright / headless browser** to verify backend logic. The Gradio UI calls the same API `gradio_client` does — one `predict` tests both.
- **Don't build mock-mode + local-server harnesses** before pushing. Local-green ≠ Space-green.
- **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.
## Iterating on the Space, not locally
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.
Workflow:
1. Decide SDK + hardware. Write the smallest `app.py` / `Dockerfile` + `requirements.txt` + README frontmatter — just enough that the entry point loads.
2. Push immediately. Don't build a Playwright / mock harness first.
3. Once `RUNNING`: verify with `gradio_client` against the real Space. That's your test loop.
4. Iterate via the cheapest rung.
`python3 -m py_compile app.py` is the maximum local check worth doing.
## Last resort: dev mode + SSH
Use only when:
- A failure is non-deterministic (device-side asserts, OOM under specific shapes, race conditions).
- You need `CUDA_LAUNCH_BLOCKING=1` or `gdb` to localize a CUDA error.
- You'd burn 4+ build cycles trying variations from outside.
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.
### Prerequisites
1. **PRO / Team / Enterprise plan** — dev mode is a paid feature.
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:
- 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).
- Add the **public** key (`~/.ssh/hf_dev.pub`) at https://huggingface.co/settings/keys.
- Keep the **private** key (`~/.ssh/hf_dev`) on the machine they'll SSH from.
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.
### Enable
No `huggingface_hub` Python wrapper yet — use the REST endpoint:
```bash
curl -s -X POST \
-H "Authorization: Bearer $HF_TOKEN" \
-H "Content-Type: application/json" \
"https://huggingface.co/api/spaces/<ns>/<space>/dev-mode" \
-d '{"enabled": true}'
```
### SSH in
```bash
ssh -i ~/.ssh/hf_dev -o BatchMode=yes -o StrictHostKeyChecking=accept-new \
<ns>-<space>@ssh.hf.space
```
Username is `<namespace>-<space>` **lowercase**, with `-` replacing `/`. Dots in the Space name become hyphens too.
### Inside the VM
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).
**`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.
**Edits in `/home/user/app/` don't survive** a restart, sleep, or dev-mode-disable. Only commits persist.
### Smoke-test the fix inside the container
Before exiting dev mode, verify the fix actually works under a real GPU window:
```bash
cat > /home/user/app/_devtest.py <<'PY'
import spaces, torch
from app import predict # or whatever your @spaces.GPU function is
print(predict(<realistic-args>))
PY
python3 _devtest.py
```
### Persist + exit
Commit + push from inside the container (`git config user.email / user.name` first; the HF git remote works). Then disable dev mode:
```bash
curl -s -X POST -H "Authorization: Bearer $HF_TOKEN" \
-H "Content-Type: application/json" \
"https://huggingface.co/api/spaces/<ns>/<space>/dev-mode" \
-d '{"enabled": false}'
```
**Factory-reboot** to apply the pushed state (in dev mode the Space won't rebuild on commits):
```python
from huggingface_hub import HfApi
HfApi(token=HF_TOKEN).restart_space("<ns>/<space>", factory_reboot=True)
```
Then re-run the outside-the-container smoke test. Dev-mode success does **not** guarantee post-rebuild success — different image, different process tree.
gradio.md 9.1 KB
# Gradio for Spaces
Patterns and quirks specific to running Gradio inside a Space. Assumes you're already comfortable with stock Gradio components and `gr.Blocks` / `gr.Interface`.
For deeper Gradio API guidance — components, layouts, event listeners, chatbots, the Gradio 5→6 migration — use the dedicated `huggingface-gradio` skill. Install it with `hf skills add huggingface-gradio` (add `--claude --global` to also install for Claude Code, user-level).
For ZeroGPU-specific decorator + worker semantics, see [`zerogpu.md`](zerogpu.md).
## Themes and layout
- Default theme preference: `gr.themes.Citrus()`. Alternatives: `gr.themes.Soft()` or no theme. Pick once and don't over-style.
- For apps that don't need full-width, constrain with CSS so they're readable on 4K displays:
```python
CSS = """
#col-container { max-width: 1100px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo: ...
```
Always include the `.dark .gradio-container` override with `gr.themes.Citrus()` — without it Citrus's dark mode renders dark text on a dark background (text inherits unset colors). The same fix is harmless (and worth keeping) under other themes.
- Width-cap with `!important` if Gradio 6's own breakpoints fight you — target `main`, `.gradio-container`, and the inner fillable wrapper, otherwise the width caps but goes flush-left.
## Minimal layout most demos converge to
```python
with gr.Row():
prompt = gr.Textbox(show_label=False, placeholder="…", container=False, scale=4)
run = gr.Button("Run", variant="primary", scale=1)
output = gr.Image(...)
with gr.Accordion("Advanced settings", open=False):
...
```
`container=False` on the inline Textbox removes the default outer border for a tighter look.
## `gr.Markdown` for the intro
Be succinct. Title, one-line description, a links section. Don't over-explain how it works — that's what the model card is for.
## `gr.Examples`
**Add `gr.Examples` whenever it makes sense** (the app takes user input and representative inputs exist). It's the first thing a visitor clicks and it doubles as an instant smoke test. Prefer examples that mirror the **official examples from the original repo / model card** — the prompts, images, and settings the authors showcase — over inventing your own.
Keep each example row to the **few variables a user actually changes** (the prompt, the input image). Give the handler **default values for everything else** (steps, guidance, seed, …) so an example row is `["a cat on a windowsill"]`, not a wall of knobs. Design the signature so the interesting inputs come first and the rest default:
```python
@spaces.GPU(duration=60)
def generate(prompt, seed=42, steps=28, guidance=5.0): # only `prompt` varies in examples
...
gr.Examples(
examples=[
["a cat sitting on a windowsill"],
["mountains at sunset, photorealistic"],
],
inputs=[prompt], # just the varied inputs; the rest use the handler defaults
outputs=output,
fn=generate,
cache_examples=True,
cache_mode="lazy",
)
```
Why these flags:
- `cache_examples=True` makes example clicks instant (no re-inference per visitor).
- **`cache_mode="lazy"`** — caches on first user click for each example. **Required on ZeroGPU** (Gradio's default on ZeroGPU is already lazy via `GRADIO_CACHE_MODE=lazy`). Eager would pre-run every example at app startup, but ZeroGPU has no GPU attached at startup — it'd fail and burn the creator's daily quota.
- `cache_examples=True` silently disables `run_on_click` / `run_examples_on_click`. If your app relies on click-only behavior, set `cache_examples=False`.
The cache key is the **example row's file path**, not a content hash. Regenerating an asset in place serves the stale cached output forever. If you replace example files, bump a `cache_version` marker or wipe `.gradio/cached_examples/<id>/`.
Hot-reload (rung 1) does **not** rebuild the cache. A `cache_version` bump needs a real commit + restart.
## Streaming and generators
`gr.Interface(fn=...)` and `.click(fn=...)` both accept generator functions. Each `yield` pushes a new value:
```python
@spaces.GPU(duration=120)
def generate(prompt):
yield gr.update(value=None, label="Starting…")
for k in range(num_steps):
yield gr.update(value=preview(k), label=f"Step {k+1}/{num_steps}")
yield gr.update(value=final, label="Done")
```
Use `gr.update(label=...)` for status narration — feels like a status line without a separate component.
**Caveat**: `gr.Progress(track_tqdm=True)` and `yield` partial outputs fight each other — pick one streaming mechanism.
## Useful UX bits
- `progress=gr.Progress(track_tqdm=True)` in the GPU function gives a free tqdm-driven progress bar.
- Pair a "Randomize seed" checkbox with the seed input, and write the actually-used seed back so users can re-run deterministically:
```python
randomize = gr.Checkbox(label="Randomize seed", value=True)
seed = gr.Number(label="Seed", value=0, precision=0)
@spaces.GPU
def gen(..., seed, randomize_seed):
if randomize_seed:
seed = random.randint(0, 2**31 - 1)
seed = int(seed)
yield ..., gr.update(value=seed) # write back into the Seed input
...
run.click(gen, inputs=[..., seed, randomize], outputs=[..., seed])
```
## Custom HTML components
Stock Gradio components cover 95% of cases. When they don't, `gr.HTML(...)` lets you build contextual custom UI without leaving the Gradio Space (no need to switch to Docker).
Guide: https://www.gradio.app/guides/custom-HTML-components
Example with a 3D camera-angle picker that makes sense in context: https://huggingface.co/spaces/multimodalart/qwen-image-multiple-angles-3d-camera
Don't reach for this if a stock component covers the need.
## Custom frontends — `gr.Server`
For fully custom frontends with their own HTML/JS, while keeping Gradio's queue + GPU scheduling:
```python
from gradio import Server
from fastapi.responses import HTMLResponse
app = Server(title="my-app")
@spaces.GPU(duration=60)
def _run_gpu(prompt): return inference(prompt)
@app.api(name="generate", concurrency_limit=1, time_limit=180)
def generate(prompt: str) -> str:
return _run_gpu(prompt) # @app.api wraps, doesn't stack with @spaces.GPU
@app.get("/", response_class=HTMLResponse)
async def homepage():
return open("index.html").read()
demo = app # HF runtime expects `demo`
if __name__ == "__main__":
demo.launch(ssr_mode=False)
```
Required for the custom `/` route to actually serve:
```bash
hf spaces variables add <ns>/<name> --env GRADIO_SSR_MODE=false
```
`launch(ssr_mode=False)` is ignored on HF — must be the env var.
Valid `@app.api` kwargs: `name`, `description`, `concurrency_limit`, `concurrency_id`, `queue`, `batch`, `max_batch_size`, `api_visibility`, `time_limit`, `stream_every`.
**Don't stack `@spaces.GPU` and `@app.api`** on the same function — silently breaks request flow. Keep them on separate functions.
**Two-ceiling coordination**: both `@spaces.GPU(duration=N)` and `@app.api(time_limit=M)` apply; the lower wins. Set `time_limit` to your max duration across modes — a too-low `time_limit` kills the request even if GPU duration would have allowed it.
Hot-reload (rung 1 in [`debugging.md`](debugging.md)) does **not** work with `gr.Server` — always `hf upload` or commit.
Reference Space: https://huggingface.co/spaces/huggingface-projects/rf-detr-realtime-webcam
## Slow-startup Gradio (big-model Spaces)
For Spaces that take 10–20 min to load weights:
- Set `startup_duration_timeout: 1h` in README frontmatter (default 30 min).
- Disable SSR: `hf spaces variables add <id> --env GRADIO_SSR_MODE=false`. Otherwise the SSR health check times out before the app finishes loading.
## Expose the Space as an MCP server
Launch with `demo.launch(mcp_server=True)` (Gradio 5+) so every API endpoint is also exposed as an MCP tool — free, and makes the Space usable by agents. For it to be useful:
- **Every API-triggered function needs a docstring and type hints.** Each Gradio event handler is auto-exposed over the API; Gradio turns the signature into the MCP tool's input schema and the docstring into its description. A function without them still works but surfaces as an opaque, unusable tool.
- Give the important endpoints stable names (`api_name="generate"` on the `.click(...)`, or `@app.api(name=...)`), so tool names don't churn.
- MCP mode can pull in extra deps (`gradio[mcp]`); if `launch` complains, see the pin note in [`known-errors.md`](known-errors.md).
```python
@spaces.GPU(duration=60)
def generate(prompt: str, seed: int = 42) -> str:
"""Generate an image from a text prompt.
Args:
prompt: what to generate.
seed: RNG seed for reproducibility.
"""
...
btn.click(generate, inputs=[prompt, seed], outputs=out, api_name="generate")
demo.launch(mcp_server=True)
```
## Don't
- `gr.Button(text="X")` — `text=` was removed; use `gr.Button("X")`.
- `gr.Button(type="button")` — drop the kwarg.
- `.click(..., _js=share_js)` — renamed to `js=`.
- `.style(height=...)` — removed in gradio 4+.
- `gr.ImageMask(brush_color=...)` — kwarg removed.
- `demo.launch(mcp_server=True)` on gradio 4.x — only valid on 5+.
grants.md 3.1 KB
# Community GPU grants
When a user has a good use case (open research demo, hobbyist project, educational tool, institutional showcase) and can't pay for the hardware it needs, they can request a free community grant from Hugging Face.
Free personal accounts already get 2 ZeroGPU Spaces, so a grant is now for the cases that go past that:
- a **dedicated GPU** ZeroGPU can't cover (non-PyTorch main model with heavy init, model too big for 96 GB, always-on serving);
- a **Gradio Space beyond the free 2-ZeroGPU cap**, without subscribing to PRO.
## The flow
1. **Build the Space.** If the user still has a free ZeroGPU slot, create it as `--flavor zero-a10g` and iterate normally with real inference before applying.
If they're out of slots, create a **Static** Space instead (`--space-sdk static` — free for everyone) and push the app there; the SDK can be switched to `gradio` in the README frontmatter once the grant lands. Code the app for ZeroGPU anyway — `import spaces`, `@spaces.GPU`, module-scope `.to("cuda")`. In this mode you **can't iterate-with-real-inference** before the grant, so just get the code in place and submit.
For a dedicated-GPU grant, get the app to BUILD cleanly and reach `RUNNING` (even if the runtime would OOM on real input), then submit.
2. **Submit a Community Tab discussion** on the Space. Title:
```
Apply for a GPU community grant: <Personal|Company|Academic> project
```
Pick the closest fit. Body:
```
Description of the app: one paragraph on what it does + who it's for.
Justification: one paragraph on why this should run on ZeroGPU
(open-source, research, educational, etc.).
```
If the user didn't give you a justification, a reasonable default is "Public open-source demo, can't cover the hardware cost — happy to provide more context if helpful."
3. **Wait.** Open and publicly-facing applications by researchers, tinkerers, and institutions are typically approved. Approval can take days.
4. **Once approved**, the hardware is attached automatically — no code change needed (a Static holding Space still needs its `sdk:` flipped to `gradio`). The user comes back and you can iterate / refine with real GPU access.
## When to suggest this
- The use case is a clear public ML demo (not a private tool) and the user is out of free ZeroGPU slots.
- The model needs more than ZeroGPU offers — beyond 48 GB `large` / 96 GB `xlarge`, or a non-PyTorch runtime — and the user can't pay.
## When NOT to suggest this
- The user is on a free account and this is their 1st or 2nd Space — they can create it on ZeroGPU directly; no grant needed.
- Private / commercial / closed-source projects — push the user toward PRO instead.
- `canPay=True` users who just need paid hardware — they can attach it directly.
## Posting the request programmatically
```python
from huggingface_hub import HfApi
api = HfApi(token="hf_...")
api.create_discussion(
repo_id="<ns>/<space>",
repo_type="space",
title="Apply for a GPU community grant: Personal project",
description="<description and justification>",
)
```
The Community Tab must be enabled on the Space (default — keep it on).
inference-providers.md 3.8 KB
# Inference Providers — when not to host the model
Some Spaces don't need a GPU at all. If the model is available through HF Inference Providers (Cerebras, Fireworks, Together, Replicate, OpenRouter, etc.), the Space can be a thin Gradio shell that proxies to a hosted endpoint:
- Zero VRAM, no real work inside `@spaces.GPU`, no model download.
- Works for models too large to fit on ZeroGPU (120B+).
- No GPU at all — see [Hardware](#hardware) below for which flavor to pick.
## When to use this pattern
- **Stateless chat or text completion** with a big model.
- **The user wants a public demo of a frontier-scale model** that obviously doesn't fit on a single 48 GB MIG.
- **The user wants to ship something fast** without worrying about quantization / sharding.
## When NOT to use this pattern
- The model isn't available on any Inference Provider. Check with:
```bash
curl "https://huggingface.co/api/models/<ns>/<repo>?expand[]=inferenceProviderMapping"
```
- The Space needs **custom decoding** (special sampling, tool use, retrieval, anything stateful or interactive across calls).
- The Space needs **multimodal** beyond what the provider exposes.
- The user explicitly wants to own the inference stack (model loading, decoding, performance tuning).
For those, host the model yourself on ZeroGPU — see [`zerogpu.md`](zerogpu.md).
## Two billing modes
Choose based on who pays for inference.
### Mode A — Space creator pays (simple)
Set `HF_TOKEN` as a Space secret. The Space uses `InferenceClient` directly. Every visitor's call is billed to the Space creator's account.
```python
import os, gradio as gr
from huggingface_hub import InferenceClient
client = InferenceClient(api_key=os.environ["HF_TOKEN"], provider="fireworks-ai")
def chat(msg, history):
return client.chat_completion(
model="<org>/<model>",
messages=[*history, {"role": "user", "content": msg}],
max_tokens=512,
).choices[0].message.content
gr.ChatInterface(chat).launch()
```
Use when you want users to "just click and try it" — no sign-in friction. Cost is on you.
### Mode B — Visitor pays (recommended for public demos)
`gr.LoginButton` + `gr.load("models/...")` with `accept_token=button`. Each visitor signs in with their HF account; inference is billed to **their** account.
```python
import gradio as gr
with gr.Blocks(fill_height=True) as demo:
with gr.Sidebar():
button = gr.LoginButton("Sign in")
gr.load("models/<org>/<model>", accept_token=button, provider="fireworks-ai")
demo.launch()
```
README frontmatter needs:
```yaml
hf_oauth: true
hf_oauth_scopes:
- inference-api
```
This is the **recommended pattern for public demos** — sustainable cost-wise, and visitors get to use their own provider quotas (which most have paid for or get free).
## Hardware
No GPU needed, so `cpu-basic` is the natural fit — but it requires a paid plan.
On a free account, create the Space with `--flavor zero-a10g` instead. ZeroGPU refuses to start without at least one decorated function, so add a no-op one and leave the provider calls outside it:
```python
import spaces
@spaces.GPU(duration=1)
def _noop(): # ZeroGPU requires ≥1 decorated function; never called
pass
```
Nothing ever requests a GPU, so no quota is burned. Just remember the Space still counts against the free 2-Space ZeroGPU cap — don't spend a slot here if the user is saving it for a real GPU demo.
## Anti-pattern: `@spaces.GPU` wrapping a provider call
If you do use Inference Providers, do **not** wrap the call in `@spaces.GPU`. The decorator reserves a GPU slot on your Space for the full `duration=`, but the function does no GPU work — just an HTTP call out. You burn your own ZeroGPU quota for nothing.
Whatever hardware a provider-proxy Space sits on, no provider call belongs inside `@spaces.GPU`.
known-errors.md 13.3 KB
# Known errors
Check if this is a known issue before trying your own fix. Entries are keyed by the substring that actually appears in `runtime.errorMessage`, the build log, or a Python traceback — grep this file for the error you saw.
If you hit something not listed here and figure out a fix, please ask your human to PR it back so future runs benefit.
---
## Build / config errors
These come from the Space build pipeline before the app starts. Read with `hf spaces logs <id> --build --tail 500` — find the **first** error, not the last.
### `CONFIG_ERROR: torch version in requirements.txt is not compatible with ZeroGPU`
**Cause**: `requirements.txt` pins `torch==X.Y.Z` to a version outside the supported set (`2.8.0`, `2.9.1`, `2.10.0`, `2.11.0`).
**Fix**: Unpin torch (preferred — the runtime preinstalls the latest supported version), or pin to one of the supported values.
### `Cannot install … because these package versions have conflicting dependencies` / `ResolutionImpossible`
**Cause**: A dep conflicts with the Gradio SDK pinned by `sdk_version:` in README. Most commonly `pydantic`, `uvicorn`, `huggingface_hub`, or `jinja2` pinned to old values that the SDK no longer accepts.
**Fix**: Unpin the offender. For `gradio[mcp]` specifically, `uvicorn>=0.31.1` and `pydantic>=2.11.10` are required.
### Build hangs in dependency resolution > 10 min
**Cause**: pip backtracking through a deep version space.
**Fix**: Pin the conflicting transitive dep. The `--build` logs will show which one. Bump `startup_duration_timeout: 1h` in README frontmatter if heavy downloads are expected.
### `ModuleNotFoundError: No module named 'pkg_resources'`
**Cause**: setuptools 81 dropped `pkg_resources`; an old package's `setup.py` imports it.
**Fix**: Bump or unpin the offender. Typical culprits: `deepspeed==0.15.x` (training-only — usually safe to drop from inference Spaces), `openai-whisper==20231117`.
### `400 Bad Request` from `/api/validate-yaml` during `create_repo` / `upload_file`
**Cause**: README frontmatter failed server validation. Most common: `short_description` over the (undocumented) character cap — target ≤ 60.
**Fix**: Shorten `short_description`. Long descriptions go in the README body. Also double-check `colorFrom`/`colorTo` are one of `red|yellow|green|blue|indigo|purple|pink|gray`.
### `403 Forbidden` from `create_repo` for a Gradio / Docker Space
**Cause**: Gradio and Docker Spaces run on compute and need a paid plan (PRO / Team / Enterprise). The only free exception is ZeroGPU — 2 Spaces for personal accounts in good standing (verified email, account older than 30 days).
**Fix**: On a free account, pass `space_hardware="zero-a10g"` rather than omitting it — `cpu-basic` is gated too, so dropping the flavor makes this worse, not better. If ZeroGPU is also rejected, the account is over its 2-Space cap or not in good standing: delete an unused ZeroGPU Space, upgrade to PRO, or ship a Static Space and apply for a [community grant](grants.md). Keep `hardware:` out of README frontmatter (silently ignored anyway).
### `403 Forbidden` from `create_commit(..., create_pr=True)`
**Cause**: Upstream Space has Discussions disabled.
**Fix**: Ask the maintainer to enable Discussions, or push directly if you have write access.
---
## Startup / RUNTIME_ERROR
These come from `hf spaces logs <id> --tail 500`.
### `RuntimeError: CUDA has been initialized before importing the spaces package`
**Cause**: Something triggered CUDA init in the main process before `import spaces`. Usually wrong import order; sometimes a third-party lib eagerly initializing CUDA at import time (e.g. `numba.cuda`).
**Fix**: Reorder so `import spaces` is first. For numba-using stacks (NeMo, RAPIDS bits):
```python
import os
os.environ.setdefault("NUMBA_DISABLE_CUDA", "1")
import spaces
```
### `RuntimeError: No @spaces.GPU function detected during startup`
**Cause**: The function bound to `.click(fn=...)` / `.submit(...)` isn't decorated. Decorating an inner helper doesn't count — the startup scan only walks Gradio's registered handlers.
**Fix**: Decorate the function Gradio binds. If that conflicts with another decorator, wrap explicitly:
```python
@spaces.GPU(duration=60)
def gpu_inner(...): ...
def gradio_handler(...): return gpu_inner(...)
```
(Or just decorate `gradio_handler` directly.)
### `ImportError: cannot import name 'HfFolder' from 'huggingface_hub'`
**Cause**: Old gradio (`4.44` and similar) imports `HfFolder` from `huggingface_hub`, which was removed in recent hub releases.
**Fix**: Two options.
- Pin `huggingface-hub==0.25.0` in `requirements.txt` (keeps old gradio happy).
- Bump `sdk_version` in README to `5.x` or `6.x` (also fixes a lot of other API breaks).
If a Gradio custom component locks the major (`gradio-image-prompter`, `gradio_litmodel3d`, …), install it with `--no-deps` so its `gradio<5.0` requirement doesn't bind.
### `ImportError: cannot import name 'is_traceable_wrapper_subclass' from 'torch.utils._python_dispatch'`
**Cause**: A dep with `torchaudio<2.1` / `torch<2` in its `setup.py` (e.g. `demucs`, `audiocraft`) downgraded torch silently. The build succeeded, the app booted, and `import spaces` then died on a missing torch symbol.
**Fix**: Install the offender from `app.py` with `--no-deps` *before* `import spaces`:
```python
import subprocess, sys
subprocess.run([sys.executable, "-m", "pip", "install", "--no-deps",
"git+https://github.com/facebookresearch/demucs"], check=True)
import spaces
```
List its actual runtime deps (`dora-search einops julius lameenc openunmix pyyaml tqdm` for demucs) yourself in `requirements.txt`.
### `_pickle.UnpicklingError: Weights only load failed`
**Cause**: `torch.load` weights-only default flipped to `True` in torch 2.6. Old checkpoints pickling numpy/object globals fail.
**Fix**: For trusted upstream checkpoints, monkey-patch before the package import:
```python
import torch
_orig = torch.load
torch.load = lambda *a, **k: _orig(*a, **{**k, "weights_only": k.get("weights_only", False)})
```
### Stuck at `ZeroGPU init – 10.0%` then 60 s timeout
**Cause**: A library called `cuInit` in the parent process, poisoning the fork (most often `numba.cuda` via NeMo). The actual `@spaces.GPU` body never starts.
**Fix**: `os.environ.setdefault("NUMBA_DISABLE_CUDA", "1")` as the first line of `app.py`, before `import spaces`.
### `RUNTIME_ERROR` right after long `APP_STARTING`, logs sparse
**Cause**: Boot exceeded `startup_duration_timeout` (default 30 min). Big-model loads commonly trigger this.
**Fix**: Bump `startup_duration_timeout: 1h` in README frontmatter. For Gradio 6 specifically, also set `GRADIO_SSR_MODE=false` via `hf spaces variables add <id> --env GRADIO_SSR_MODE=false` to dodge SSR health-check timeouts during slow boot.
### `RUNNING` but the public URL returns 404
**Cause**: The Space is private. Anonymous Client / browser hits return 404.
**Fix**: Authenticate. `gradio_client.Client(space, token=os.environ["HF_TOKEN"])`. The kwarg is `token=`, not `hf_token=`.
### `workload was not healthy after 30 min`
**Cause**: Infra-side scheduling or a build that genuinely can't finish in time.
**Fix**: Usually not actionable in code. Bump `startup_duration_timeout` if heavy downloads are expected; otherwise wait or report.
### Exit code 128 / containerd / scheduling failure
**Cause**: HF infra glitch.
**Fix**: `hf spaces restart <id> --factory-reboot`. If it persists, retry later or report. Not fixable in code.
---
## Inference-time errors
These appear in `hf spaces logs <id> --follow` while a request is running.
### `ZeroGPU illegal duration`
**Cause**: `@spaces.GPU(duration=N)` is larger than the visitor's tier per-call cap.
**Fix**: Lower `N`. Tier caps live in the [ZeroGPU docs](https://huggingface.co/docs/hub/spaces-zerogpu).
### `ZeroGPU quota exceeded (X requested vs Y left)`
**Cause**: The visitor's remaining quota < `requested duration`. The comparison is `requested vs remaining`, not `actual vs remaining` — a 10-second task left at the default 60 s blocks the user as soon as their remaining drops below 60 s.
**Fix**: Lower `duration` to the realistic worst case. For input-dependent runtime, use a callable estimator.
### `RuntimeError: NVML_SUCCESS == r INTERNAL ASSERT FAILED at .../CUDACachingAllocator.cpp`
**Cause**: Allocator fragmentation under transient memory spikes (high-res pixel-space ops, large attention activations, SR models, video DiTs). Not a clean OOM.
**Fix**: Set expandable segments at the **very top** of `app.py`, before any torch import:
```python
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces
import torch
```
Usually a single-line fix that replaces lowering resolution or moving to `xlarge`.
### Call hangs forever on first `@spaces.GPU` entry
**Cause**: The decorated function returned a CUDA tensor. Unpickling it in the main process triggers `torch.cuda._lazy_init()`, which ZeroGPU blocks.
**Fix**: Convert to CPU before returning: `return tensor.cpu()` or `.cpu().numpy()`. For `gr.State`, scrub before yielding.
### `PicklingError` at call entry
**Cause**: An argument crossing the fork boundary contains an unpicklable object — file handle, lock, lambda, closure, or `gr.SelectData`.
**Fix**: Extract the picklable fields in a thin un-decorated wrapper, pass plain values to the `@spaces.GPU` function. For `gr.SelectData` specifically, pull out `evt.index[0]`, `evt.index[1]` etc. outside the decorator.
### `RecursionError` inside `gr.SelectData.__getattr__`
**Cause**: Same as above — `gr.SelectData` doesn't survive pickle.
**Fix**: Same — extract its fields before crossing the boundary.
### `CUDA error … flash_fwd_launch_template.h: no kernel image is available for execution on the device` (or `:188: invalid argument`)
**Cause**: A Flash Attention 3 kernel was loaded — directly via `kernels-community/{flash-attn3,vllm-flash-attn3,sgl-flash-attn3}`, or indirectly via an old `xformers` wheel that auto-dispatched to FA3. FA3 has no Blackwell sm_120 build.
**Fix**: Use `attn_implementation="sdpa"`, or `"flash_attention_2"` with the FA2 wheel from `multimodalart/zerogpu-blackwell-wheels`. For xformers, the prebuilt wheel from the same dataset auto-dispatches to FA2 — no monkey-patch.
### `NotImplementedError: sgl_flash_attn3 is only supported on sm80 and above with CUDA >= 12.3`
**Cause**: `kernels-community/sgl-flash-attn3` rejects sm_120 at runtime despite the error wording. Same root cause as the FA3 entry above.
**Fix**: Same — SDPA or FA2.
### `ImportError: cannot import name 'flash_attn_varlen_func' from 'flash_attn'` / model insists on `attn_implementation="flash_attention_2"`
**Cause**: The model imports flash_attn at module top with no escape hatch, and the runtime doesn't ship it.
**Fix**: Install the prebuilt `flash_attn-2.8.3-cp310-cp310-linux_x86_64.whl` from `multimodalart/zerogpu-blackwell-wheels`. Requires `python_version: "3.10"` in README (wheel is cp310 only). Real `flash_attn_2_cuda` satisfies xformers' `flash_attn_gpu` probe too.
For transformers `AutoModel`-style configs that aren't a hard import, swap `attn_implementation="flash_attention_2"` → `"sdpa"`. Torch-native, zero deps.
### `selective_scan_cuda.so undefined symbol` / `_torchaudio.abi3.so undefined symbol`
**Cause**: A direct-URL prebuilt CUDA wheel pinned to an old torch ABI (`cu12torch2.4cxx11abiFALSE`, etc.) — won't load on the current runtime.
**Fix**: Drop the URL-pinned wheel from `requirements.txt`. Use a torch-current wheel from `multimodalart/zerogpu-blackwell-wheels`, kernels-community, or upstream's release page.
### `TypeError: 'dict' object is not hashable` inside `jinja2/utils.py:get`
**Cause**: Old gradio (4.44) + modern starlette / jinja2 cache clash.
**Fix**: Either pin `jinja2<3.2` + `starlette<0.40` (keeps old gradio), or bump `sdk_version` past 5.0.
---
## Smoke-test / client errors
### `Client.__init__() got an unexpected keyword argument 'hf_token'`
**Cause**: Older `gradio_client` API used `hf_token=`; current uses `token=`.
**Fix**: `Client(space, token=os.environ["HF_TOKEN"])`.
### `httpx.ReadTimeout` on `client.predict(...)`
**Cause**: Default timeout too small for the GPU duration.
**Fix**: `Client(..., httpx_kwargs={"timeout": 600})`. Set this to at least your `@spaces.GPU(duration=N)` plus 60 s.
### `404` on what looks like a valid endpoint name
**Cause**: Streaming endpoint (function uses `yield`), or a custom `gr.Server` `@app.get/post` route that doesn't appear in `view_api()`.
**Fix**: For streaming, use `client.submit(...).result()` (or iterate the job). For custom routes, use `httpx.post(base_url + "/route", ...)` directly — bypass `gradio_client`.
### Result file looks empty / dimensions wrong
**Cause**: HTTP 200 ≠ correct output. The model snapped to a different size, or the wrong endpoint was hit.
**Fix**: Sniff the returned file's magic bytes (`glTF`, `\x89PNG`, `RIFF…WEBP`, `RIFF…WAVE`, `[4:8]==b"ftyp"`) and check returned dimensions match what was requested.
---
## Submitting new entries
If you hit an error not in this file and figure out the fix, please ask your human to PR it back to this skill. Format:
- A 1-line heading with the exact error substring an agent would grep for.
- **Cause**: one sentence on what triggered it.
- **Fix**: concrete commands or code. If the fix needs more than 5 lines of narrative, point to another reference file (e.g. [`debugging.md`](debugging.md), [`zerogpu.md`](zerogpu.md)) for depth.
requirements.md 11.2 KB
# requirements.txt for Spaces
Rules for what to pin, what to leave alone, where to source CUDA wheels, and which torch-side-cars drift silently.
## What's preinstalled (do not list)
The Gradio SDK base image already installs these on every hardware tier — listing them in `requirements.txt` causes resolution failures or, worse, lets pip silently drift the runtime out of compatibility:
| Package | Pinning rules |
|---|---|
| `gradio` | Don't list. Locked by `sdk_version:` in README frontmatter; pinning here is ignored or breaks. |
| `spaces` | Don't list. Platform-pinned; a user pin always loses. |
| `huggingface_hub` | Don't list by default. Pin only as a workaround for old `gradio<5` that imports the removed `HfFolder` symbol (see [`known-errors.md`](known-errors.md)). |
| `torch` | **Pinnable, but only within `{2.8.0, 2.9.1, 2.10.0, 2.11.0}`.** Anything outside causes `CONFIG_ERROR: torch version in requirements.txt is not compatible`. Default is to leave unpinned (runtime preinstalls 2.11), but pinning is appropriate when (a) a specific version is known-good for your model, (b) you're matching a CUDA-extension wheel's `torch2.X` tag, or (c) a dep would otherwise drag torch outside the supported set. When you pin torch, also pin `torchvision` / `torchaudio` to the matching minor — see the "Torch-family side-car drift" section below. |
## What to list
Everything you actually `import`, including the often-forgotten:
- `torchvision`, `torchaudio` — **not** preinstalled. Leave unpinned; pip resolves against the installed `torch` major.minor.
- `accelerate` — needed whenever you use `device_map=`. Listing it also silences `low_cpu_mem_usage=False` warnings.
- `sentencepiece` — required by most LLM tokenizers; rarely transitive.
- `einops` — required by `flash_attn.layers.rotary` and many model repos.
- Domain libs: `diffusers`, `transformers`, `safetensors`, `pillow`, `numpy`, etc.
If a research repo ships a Python package directory (`models/`, `pipeline/`, …), just upload the directory with the rest of the Space — the whole repo root is importable as `/home/user/app`. **Do not** try to reference local paths from `requirements.txt`.
## Pinning torch
ZeroGPU accepts only `2.8.0`, `2.9.1`, `2.10.0`, `2.11.0`. Default is unpinned (runtime preinstalls the latest). Pinning is fine — and sometimes warranted — within that set:
- A specific torch is known-good for your model (numerics, attention kernel availability, etc.).
- A direct-URL CUDA wheel encodes a `torch2.X` tag (see "Prebuilt CUDA wheels" below) — pin torch to match.
- A dep's `setup.py` would otherwise downgrade torch outside the supported set.
`2.8.0` is the safest fallback for old requirements that refuse modern torch. `2.10.0` / `2.11.0` is the sweet spot for new code. When you pin torch, also pin `torchvision` / `torchaudio` to the matching minor — see the side-car drift section.
When a dep would silently downgrade torch (e.g. some forks of `demucs`, `audiocraft` pin `torchaudio<2.1`), install the offender from `app.py` with `--no-deps` rather than pinning torch around it:
```python
import subprocess, sys
subprocess.run([sys.executable, "-m", "pip", "install", "--no-deps",
"git+https://github.com/facebookresearch/demucs"], check=True)
import spaces # safe now — torch wasn't touched
```
List the offender's real runtime deps yourself in `requirements.txt`.
## Torch-family side-car drift
`torchvision`, `torchaudio`, `torchcodec` are built against a specific `torch` major.minor. Listing them unpinned **usually** works, but two known drift patterns:
- `torchaudio==2.11.0` (and later) **dropped its `Requires-Dist: torch==X.Y.Z` line**. With torch pinned to 2.10, pip silently resolves torchaudio to 2.11.0 and the import fails on ABI mismatch.
- `torchcodec` declares no torch dependency in PyPI metadata at all.
Verification after `pip install` or `uv lock --upgrade`:
```bash
curl -s https://pypi.org/pypi/<pkg>/<version>/json \
| python3 -c "import json,sys,re; rd=json.load(sys.stdin)['info'].get('requires_dist') or []; \
print('\n'.join(x for x in rd if re.match(r'^torch(?![a-z])', x)) or '(no torch constraint)')"
```
When PyPI is silent, fall back to the project's README compatibility table (torchcodec's lives at https://github.com/pytorch/torchcodec).
## Prebuilt CUDA wheels — the Blackwell wheels dataset
This is the **first** thing to reach for when a CUDA-extension package has no upstream wheel matching the ZeroGPU torch / CUDA / cxx11-abi cell. Prefer it over any runtime workaround (`pip install git+…` inside `@spaces.GPU`, committed stub packages, `sys.modules` injection, monkey-patch shims), all of which are slower, fragile, and eat `duration` budget. Canonical prebuilt sm_120 wheels:
> https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels
Wheels live at `wheels/<cell>/<wheel>`. A **cell** encodes torch × CUDA × Python as `pt<torch>-cu<cuda>-cp<pyver>`. Every cell ships the same seven packages:
`flash_attn` (two versions: `2.8.3` and `2.7.4.post1`), `xformers`, `pytorch3d`, `nvdiffrast`, `diff_gaussian_rasterization`, `torchmcubes`.
Current cells (12):
| torch | CUDA | Python cells available |
|---|---|---|
| 2.8.0 (`pt28`) | 12.8 | cp310, cp311, cp312 |
| 2.9.1 (`pt291`) | 12.8 | cp310 |
| 2.10.0 (`pt210`) | 12.8 / 13.0 | cp310 (cu128), cp312 (cu130) |
| 2.11.0 (`pt211`) | 13.0 | cp312, cp313 |
| 2.12.0 (`pt212`) | 13.0 | cp310, cp311, cp312, cp313 |
### Picking a cell
1. **Match `cp<pyver>` to your `python_version:`.** The wheels are cp-ABI-specific — a `cp310` wheel needs Python 3.10, `cp312` needs 3.12, etc. (`flash_attn` now ships cp310 **through** cp313, so this is a free choice, not a forced pin to 3.10 as in older versions of this doc.)
2. **The wheels are torch-minor-tolerant.** The `flash_attn` / `xformers` filenames encode no torch version, so a `pt212-cu130-cp310` wheel runs fine on the live torch-2.11 cp310 runtime. `flash_attn` ships cp310 through cp313, so the Python choice is free. Pick the highest-torch cell for your Python version unless you've pinned an older torch — then match it (torch 2.8 → a `pt28-cu128-cp3XX` cell).
3. **Copy the *exact* filename from the cell you pick.** The `xformers` build hash differs across cells (`0.0.34+3da0fc92…` on the cu130 / torch≥2.10 cells, `0.0.34+41531cee…` on the cu128 / torch 2.8–2.9 cells). Don't hardcode one filename across cells — list the cell (`hf download --repo-type dataset multimodalart/zerogpu-blackwell-wheels --include "wheels/<cell>/*"` or the Hub file browser) and copy what's there.
Reference by direct URL in `requirements.txt`:
```
https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/<cell>/<wheel>
```
### Per-package status
Each package's version is constant across cells; only the `cp`/torch/CUDA tags in the filename change. The "instead of" column is the runtime workaround to avoid — the wheel is the clean path.
| Package | Instead of | Version + caveats |
|---|---|---|
| `flash_attn` | committing a `flash_attn/` stub package; `sys.modules["flash_attn"] = …` injection | **2.8.3** (default) or **2.7.4.post1** (repos that pin `flash-attn<2.8`). Ships **cp310–cp313**. Needs `einops` for `flash_attn.layers.rotary`. Built `FLASH_ATTN_CUDA_ARCHS=120` (sm_120 only). This is FlashAttention-**2** — FA3/FA4 do **not** run on sm_120 (no TMEM); see [`zerogpu.md`](zerogpu.md) → Attention backends. Its real `flash_attn_2_cuda` also satisfies xformers' `flash_attn_gpu` probe. |
| `xformers` | an MEA→SDPA monkey-patch shim; a Cutlass-force shim | **0.0.34** (`Requires: torch>=2.10`). **Build hash differs per cell** — copy the exact filename. Auto-dispatch picks FA2 (`fa2F`) on sm_120; classic Cutlass / FA3 reject sm_120 but auto-dispatch never selects them. |
| `pytorch3d` | a runtime `pip install git+…pytorch3d.git` inside `@spaces.GPU` | **0.7.9**. Needs `numpy`, `iopath`, `fvcore` listed. No torch pin in metadata; loads cleanly on torch 2.11. |
| `nvdiffrast` | a runtime build with `TORCH_CUDA_ARCH_LIST=12.0` | **0.4.0**. Needs `numpy`. `RasterizeGLContext` is a deprecation alias for `RasterizeCudaContext` — no headless-GL footgun. |
| `diff_gaussian_rasterization` | a runtime build from `graphdeco-inria/diff-gaussian-rasterization.git` | **Upstream Inria API only** (returns 2-tuple `(color, radii)`). Does NOT match the ashawkey fork (4-tuple incl. alpha+depth) used by `ashawkey/LGM`, `dylanebert/LGM-mini`, etc. Forks need their own wheel. |
| `torchmcubes` | a runtime `pip install git+…torchmcubes.git` | **0.1.0**. **sm_120 only** (no fatbin for older archs). Works on ZeroGPU / Blackwell; not portable to a dedicated T4 / L4 / A10G Space. |
### Pattern
Resolve the exact filenames from your chosen cell, then:
```
# requirements.txt (cell = pt212-cu130-cp310 → needs python_version "3.10")
numpy
einops
https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt212-cu130-cp310/flash_attn-2.8.3-cp310-cp310-linux_x86_64.whl
https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt212-cu130-cp310/xformers-0.0.34+3da0fc92.d20260528-cp39-abi3-linux_x86_64.whl
```
```yaml
# README frontmatter — pin Python to match the wheel cell's cp tag
python_version: "3.10"
```
**Do not** install these from `@spaces.GPU` startup. A `subprocess.check_call` pip-install at first GPU acquire is strictly worse than the wheel URL — slower cold start, eats `duration` budget, breaks reproducibility, and the build sometimes exceeds the `@spaces.GPU(duration=1500)` cap.
### When you need a wheel that's not in the dataset
Three options, in preference order:
1. **kernels-community** — https://huggingface.co/kernels-community handles ABI matching for you. Often the simplest path; no version pinning needed.
2. **Upstream wheel matrix** — e.g. flash-attention's releases page ships a fairly complete `cu12 / torch / Python` matrix at https://github.com/Dao-AILab/flash-attention/releases. Pin `torch==X.Y.Z` in `requirements.txt` to match the wheel's `torch2.X` tag.
3. **Build it yourself and host on HF Hub.** Last resort — see [`debugging.md`](debugging.md) for the in-`@spaces.GPU` source-build pattern as a stopgap while a wheel is being built.
## Reading a CUDA wheel filename
```
flash_attn-2.8.3+cu130torch2.12cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
```
| Tag | Meaning |
|---|---|
| `cu130` | CUDA major version (13.0) |
| `torch2.12` | torch major.minor the wheel was compiled against |
| `cxx11abiFALSE` | C++ stdlib ABI choice (`TRUE` or `FALSE`) |
| `cp310-cp310` | CPython version (3.10) |
ABI / symbol mismatches at any of these → `ImportError` on first import. Pin `torch` to match `torch2.X`. Set `python_version:` to match `cp3XX`.
## Don't pin `xformers`
Leave bare in `requirements.txt` (or use the prebuilt URL above). Pip picks the wheel matching your installed torch.
## Don't pin `spaces`
Even if a `uv export` produces it, exclude with `--no-emit-package spaces`. The platform always pins its own version.
## Specifically about Python version
Pinning `python_version:` is effectively required:
- ZeroGPU officially supports **3.10.13** and **3.12.12**.
- The runtime default is 3.10.
- Pinning to a `cp3XX` wheel matrix (e.g. `cp310` flash_attn wheel) forces matching Python.
Both `"3.12"` and `"3.12.12"` forms are accepted in YAML.
zerogpu.md 20.7 KB
# ZeroGPU
Read this whenever the Space targets ZeroGPU (`zero-a10g` flavor). The SKILL.md's 3-rule summary is a starting point; this file covers the model in enough detail to debug and design.
For numerical limits (per-tier daily quota minutes, runs-per-day caps, current backing GPU, supported Python / torch versions): https://huggingface.co/docs/hub/spaces-zerogpu. Those values change over time and are deliberately kept out of this skill.
## The mental model
A ZeroGPU Space runs as **two processes**:
- **Main web process** — long-lived. Imports `app.py`, launches Gradio. Holds no VRAM and, after the startup "pack" step, no model weights in RAM either.
- **GPU worker** — short-lived. Forked per `@spaces.GPU` request (or reused if warm). Eventually killed by the ZeroGPU scheduler when another Space needs the slot. Your code never kills its own worker.
`import spaces` monkey-patches `torch.cuda.*` in the main process so that `.to("cuda")` and `torch.cuda.is_available()` work at module scope **without** a real GPU attached. Module-level `model.to("cuda")` is intercepted: the tensor data physically stays in main-process RAM at this point, with a CUDA-presenting "fake" tensor registered alongside. At a startup "pack" step, the backend writes those original CPU tensors to disk via `O_DIRECT` and frees the RAM. After pack, main holds no weights anywhere.
When a `@spaces.GPU` call lands, the scheduler routes it to a worker:
- **Cold worker** — forked from the main process; torch is unpatched; real CUDA is initialized; weights are streamed disk → pinned host → VRAM via a double-buffered pipeline. This is the cold-start cost.
- **Warm worker** — alive worker bound to the same slot; init is skipped; weights stay on VRAM from the previous call.
A warm worker eventually dies when another Space needs the slot. Occasional cold starts on a low-traffic Space are normal.
## The three rules
### 1. `import spaces` before any CUDA-touching import
```python
import spaces # FIRST
import torch # then this
```
If something initializes CUDA before `import spaces`, the patch can't apply and you get `RuntimeError: CUDA has been initialized before importing the spaces package`. For libraries that eagerly init CUDA on import (e.g. `numba.cuda`, NeMo via numba), set the disable env *before* the import:
```python
import os
os.environ.setdefault("NUMBA_DISABLE_CUDA", "1")
import spaces
```
### 2. Load models at module scope, `.to("cuda")` eagerly
```python
pipe = DiffusionPipeline.from_pretrained("...", torch_dtype=torch.bfloat16).to("cuda")
```
Do **not** lazy-load inside `@spaces.GPU`. The hijack is designed for module-level placement; deferring it puts tens of seconds of checkpoint I/O + dtype cast + GPU move inside every cold request.
Use the **string `"cuda"`** — never an integer device id. ZeroGPU re-allocates device ids per request, so `.to(0)`, `device_map={"": 0}`, `torch.cuda.set_device(0)` silently break.
For plain `from_pretrained` loads, use `.to("cuda")`, **not** `device_map="cuda"` (which routes through `accelerate.set_module_tensor_to_device` and calls `torch._C._cuda_init()` at load time, bypassing the hijack). The exception is loaders that are ZeroGPU-aware — notably the `bitsandbytes` quantization path; `from_pretrained(..., quantization_config=BitsAndBytesConfig(...))` works with `device_map="cuda"`.
**Preloading multiple variants** (e.g. base + refiner, image + video model) is fine as long as their combined VRAM fits. Load all of them sequentially at module scope into a dict, then key per request. Don't unload/reload between requests — that puts the load cost back on the user.
### 3. Decorate the function Gradio binds
ZeroGPU's startup scan walks Gradio's registered event handlers for `@spaces.GPU`-marked functions. If you decorate `inner_helper` but `click(fn=outer)` is what's wired up, you get `RuntimeError: No @spaces.GPU function detected during startup`. Always decorate the function passed to the event handler.
```python
@spaces.GPU(duration=60)
def generate(prompt):
return pipe(prompt).images[0]
btn.click(fn=generate, inputs=prompt_box, outputs=image_out)
```
## Sizing duration
`@spaces.GPU(duration=N)` means "reserve N seconds of GPU time." Two failure modes:
- **`ZeroGPU illegal duration`** — `N` exceeds the visitor's tier cap. Lowering `duration` is the only fix.
- **`ZeroGPU quota exceeded`** — the visitor's remaining quota is less than `requested`. Compared as `requested vs remaining`, not `actual vs remaining` — so a 10-second task left at the default 60 s blocks the user as soon as their remaining drops below 60 s.
Smaller `duration` also ranks **higher** in the queue. Both reasons push toward declaring the realistic worst case, not a comfortable margin.
**Pick the value — don't guess.** A too-high duration deploys cleanly then errors on the first call; too-low silently truncates. Methodology:
1. Ship with a placeholder (e.g. 180 s).
2. Instrument with `time.perf_counter()` and return the seconds in the response.
3. Run 2–3 representative calls via `gradio_client`.
4. Set `duration = round(measured_max × 1.4)`.
For input-dependent runtime, pass a **callable**:
```python
def _estimate(prompt, steps, *args, **kwargs):
# Swallow extras with *args, **kwargs — Gradio passes progress= positionally
# and a strict signature will raise "takes 5 positional arguments but 6 were given"
return min(240, 60 + int(steps * 3.5))
@spaces.GPU(duration=_estimate)
def generate(prompt, steps, ..., progress=gr.Progress(track_tqdm=True)):
...
```
## Sizing memory: `large` vs `xlarge`
`size="large"` (default) is half the backing card (48 GB on Blackwell). `size="xlarge"` is the full card (96 GB) and costs **2× quota** per second — plus higher queue waits. Use `large` unless the workload genuinely OOMs.
Rough VRAM sizing:
| Mode | Memory rule | 7B | 27B | 70B |
|------|------------|------|------|------|
| bf16 | `params × 2` GB | 14 GB ✓ large | 54 GB → xlarge | 140 GB → quant + xlarge |
| int8 | `params × 1` GB | 7 GB ✓ large | 27 GB ✓ large | 70 GB → xlarge |
| 4-bit (NF4 / int4) | `params × ~0.55` GB | 4 GB ✓ large | 15 GB ✓ large | 40 GB ✓ large |
Numbers are for weights only; activations and KV cache add on top (significant for long context).
## Quantization
ZeroGPU supports two quantization stacks: **`bitsandbytes`** (drop-in for transformers, well-trodden) and **`torchao`** (torch-native, newer, smaller install). Pick by what your model's `from_pretrained` actually wires up; if both work, default to `bitsandbytes` for transformers LLMs and `torchao` for diffusers.
### bitsandbytes (NF4 / int8)
```python
import spaces, torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
bnb = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
quantization_config=bnb,
device_map="cuda", # OK here — bnb's loader is ZeroGPU-aware
dtype=torch.bfloat16,
).eval()
```
This is the one case where `device_map="cuda"` is **safe** on ZeroGPU at module scope (bitsandbytes' loader path intercepts cleanly). For non-bnb loads, stick to `.to("cuda")`.
`load_in_8bit=True` swaps the 4-bit block for int8 — same hijack-safe loader. Bigger but higher quality, no `compute_dtype` knob.
### torchao
```python
import spaces, torch
from diffusers import DiffusionPipeline
from torchao.quantization import quantize_, Int8WeightOnlyConfig
pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16).to("cuda")
quantize_(pipe.transformer, Int8WeightOnlyConfig()) # mutates in place
```
`torchao` is more flexible (fine-grained per-module quantization, `Int4WeightOnlyConfig`, `Float8WeightOnlyConfig`, etc.) and works with diffusers' `from_pretrained(..., quantization_config=TorchAoConfig(...))` integration too. No CUDA build dependency — installs as a wheel.
### Attention backends
**Default to `attn_implementation="sdpa"`** — torch-native, works everywhere on sm_120, and is the right choice for the overwhelming majority of Spaces. Reach for a Flash-Attention backend only when the **upstream repo already references FA** (its config/model code defaults to or recommends `flash_attn`) — match what it expects rather than forcing SDPA. If FA then breaks on Blackwell, fall back to SDPA.
**Flash Attention 2** — when you do need it, use the prebuilt wheel at `multimodalart/zerogpu-blackwell-wheels` ([`requirements.md`](requirements.md)), cp310–cp313. Drop the wheel URL in `requirements.txt`; no monkey-patch, no runtime build. The wheel's real `flash_attn_2_cuda` also satisfies xformers' import-time probes.
**xformers** — same wheels dataset; auto-dispatch picks FA2 on sm_120 with no monkey-patch.
**FA2 is the ceiling on ZeroGPU Blackwell — FA3 and FA4 cannot run on sm_120.** The RTX PRO 6000 (sm_120) lacks the TMEM / `tcgen05` tensor-memory subsystem the FA3/FA4 kernels are built on; those kernels only exist for Hopper (sm_90a) and datacenter Blackwell (sm_100a). This is a **hardware** limit, not a packaging gap — no wheel or branch fixes it:
- `kernels-community/flash-attn3` (any revision, including `fake-ops-return-probs`), `vllm-flash-attn3`, `sgl-flash-attn3` all either fail to load (no matching build) or hard-fault at call time with `CUDA error: no kernel image is available for execution on the device` — which **kills the ZeroGPU worker** (surfaces as `GPU task aborted`); it does not fall back.
- Verified empirically on the live runtime (`NVIDIA RTX PRO 6000 Blackwell … sm_120`, torch 2.11 / cu130) and confirmed upstream — every framework (vLLM, SGLang) falls back to FA2 on sm_120.
So on ZeroGPU the ladder is **SDPA (default) → FA2 (only if the repo uses FA)**. Don't wire in FA3/FA4 — a stray `config.json` `kernels` entry loading `flash-attn3` will abort the worker on first GPU call.
## Concurrency
Handlers run **concurrently by default**. Three rules:
1. **No mutable global state.** Handlers writing to a module-level dict / list race each other.
2. **No fixed output paths.** Two concurrent calls writing to `output.png` clobber each other (and leak data across users). Use `tempfile.NamedTemporaryFile(suffix=...)`.
3. **Read-only globals are safe** — models, tokenizers, configs loaded once and only read inside handlers.
## Process isolation and pickle
`@spaces.GPU` runs in a separate fork. Arguments and return values cross via pickle:
- **Only picklable objects** in/out. File handles, locks, lambdas, closures over unpicklable state → `PicklingError`.
- **Never return CUDA tensors.** Unpickling in the main process triggers `torch.cuda._lazy_init()`, which ZeroGPU blocks → the call hangs. Convert to CPU first: `return tensor.cpu()` or `.cpu().numpy()`.
- CPU tensors, numpy arrays, PIL Images, plain Python objects work fine.
- `gr.SelectData` is a special case — its `__getattr__` recurses under pickle. Extract the fields you need (`evt.index[0]`, etc.) in a thin un-decorated wrapper, pass plain values to the `@spaces.GPU` function.
### `gr.State` across the fork
`gr.State` is pickled on every yield. The handler receives a **copy**:
- In-place mutations inside the fork are invisible to other handlers until you explicitly `yield` the mutated value back.
- Yielding `gr.update()` for a state slot **skips** the update — other handlers continue to see pre-yield value.
- For large state, minimize how often you yield it — ideally once at the end.
- CUDA tensors inside state must be CPU-d before yielding (same `_lazy_init` issue).
## Generators and streaming
`@spaces.GPU` supports generator functions — first-class for progressive UI updates:
```python
@spaces.GPU(duration=120)
def generate(prompt):
yield gr.update(value=None, label="Starting…")
for step in range(num_steps):
latent = step_fn(...)
yield gr.update(value=preview(latent), label=f"Step {step+1}/{num_steps}")
yield gr.update(value=final_image, label="Done")
```
`gr.Progress(track_tqdm=True)` and `yield` compete with each other — pick one.
For streaming previews **inside** a diffusers `callback_on_step_end`, use a thread + queue inside the decorator (forks share threads):
```python
@spaces.GPU(duration=180)
def generate(prompt, num_steps):
q = queue.Queue()
DONE = object()
def cb(pipe, step, t, kw):
q.put((step, taef1_preview(kw["latents"])))
return kw
def run():
out = pipeline(prompt=prompt, num_inference_steps=num_steps,
callback_on_step_end=cb,
callback_on_step_end_tensor_inputs=["latents"])
q.put((DONE, out))
threading.Thread(target=run, daemon=True).start()
while True:
idx, payload = q.get()
if idx is DONE: break
yield gr.update(value=payload, label=f"Step {idx+1}/{num_steps}")
```
**Do not** use `ProcessPoolExecutor` / `multiprocessing.Pool` inside `@spaces.GPU` — the daemonic fork can't spawn children (`AssertionError: daemonic processes are not allowed to have children`). Threads only.
## Compilation (AoTI)
`torch.compile` (JIT) is **not supported** on ZeroGPU — the forked GPU worker can't host the compile daemon. The supported path is PyTorch **ahead-of-time inductor (AoTI)**, wrapped by the `spaces` package (torch 2.8+, `spaces` ≥ 0.50). Its real value: compile a graph **once, offline**, publish it to the Hub, and have the serving Space load it — so serving cold starts pay no compile cost.
### The `spaces` AoTI API
- `spaces.aoti_capture(module)` — context manager. Run one real forward pass inside it; it patches `module.forward` to record that call's `args`/`kwargs` and abort the run. Gives you real example inputs for export.
- `spaces.aoti_compile(exported, inductor_configs=None)` → an in-memory `ZeroGPUCompiledModel`.
- `spaces.aoti_compile_and_save(package_dir, exported, inductor_configs=None)` — compile and write `{package_dir}/root/package.pt2`.
- `spaces.aoti_apply(compiled, module)` — swap `module.forward` for an in-memory compiled model, same process.
- `spaces.aoti_blocks_load(module, repo_id, variant=None)` — the high-level loader. For a module exposing `_repeated_blocks` (most diffusers transformers), it downloads `{BlockClass}[.{variant}]/package.pt2` from `repo_id` and patches every matching block. Weights stay **runtime inputs**, so one compiled block-graph serves any checkpoint with the same block architecture (e.g. a base and its distilled/turbo variant share one graph).
### Recommended workflow: precompile the repeated block, load at runtime
Split into a **compile Space** (run by hand, occasionally) and the **serving Space**, connected by a Hub **model** repo (`aoti_blocks_load` downloads with the default `repo_type="model"`).
**Compile Space** — capture one repeated block's inputs, export, compile, save, upload:
```python
import os, spaces, torch, tempfile, shutil
from pathlib import Path
from huggingface_hub import HfApi
pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16).to("cuda")
block = pipe.transformer.transformer_blocks[0] # one representative repeated block
BLOCK = type(block).__name__
@spaces.GPU(duration=1500)
def compile_and_upload():
with spaces.aoti_capture(block) as call: # capture the block's real inputs…
pipe("a prompt", num_inference_steps=1) # …from the first block call of a 1-step run
exported = torch.export.export(
block, call.args, call.kwargs,
dynamic_shapes=None, # start static; see note below
strict=False,
)
tmp = Path(tempfile.mkdtemp())
spaces.aoti_compile_and_save(tmp, exported) # -> tmp/root/package.pt2
out = Path(tempfile.mkdtemp()); (out / BLOCK).mkdir()
shutil.copy(tmp / "root" / "package.pt2", out / BLOCK / "package.pt2")
HfApi(token=os.environ["HF_TOKEN"]).upload_folder(
folder_path=str(out), repo_id=REPO, repo_type="model")
```
The repo ends up as `{BlockClass}[.{variant}]/package.pt2`, optionally with a `config[.variant].json` listing custom `kernels` to fetch at load.
**Serving Space** — one line at module scope, with an eager fallback:
```python
pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16).to("cuda")
try:
spaces.aoti_blocks_load(pipe.transformer, REPO) # variant="fp8da" if you saved a variant
except Exception as e:
print(f"AoTI load failed ({e!r}); running eager")
```
Only the repeated block is compiled, so the artifact is small and the same graph patches all N layers; compilation (minutes) happens offline, never on a serving cold start.
### Footguns
- **Construct the block identically in both Spaces.** The compiled graph's constant FQNs must line up with the serving module. If the block chooses kernels/norms via env var or import probe (e.g. a triton fused RMSNorm vs the pure-torch path), pin the *same* choice in compile and serving.
- **Dynamic shapes.** `dynamic_shapes=None` bakes in the one resolution you captured. To serve variable sequence length / image size, pass `torch.export.Dim(...)` for those axes (e.g. `{"hidden_states": {1: torch.export.Dim("seq")}}`) — this is per-model tuning.
- **Data-dependent inputs don't export.** A block taking per-sample python int lists (some double-stream blocks) can make `torch.export` refuse to make them dynamic — those stay eager. Single-stream blocks taking only packed tensors export cleanly.
- **Custom kernels.** Ship a `config[.variant].json` with a `kernels` list (`repo_id` + `revision`); `aoti_blocks_load` calls `kernels.get_kernel(...)` before loading so the op is registered. (FA3 still won't run on sm_120 — see Attention backends.)
- **Simpler in-process variant.** For a one-off, skip the Hub round-trip: `spaces.aoti_apply(spaces.aoti_compile(exported), module)` compiles and applies in the same process — but you re-compile on every cold start.
### Reference Spaces
- `multimodalart/Boogu-Image-0.1-Edit-aoti-compile` (compile + upload) and `multimodalart/Boogu-Image` (serving via block loading) — the blocks pattern end to end.
- `zerogpu-aoti/Qwen-Image`, `zerogpu-aoti/Wan2` — artifact repos showing the `{BlockClass}.{variant}/package.pt2` + `config.{variant}.json` layout.
- Deeper background on inductor configs and dynamic shapes: https://huggingface.co/blog/zerogpu-aoti
## Local development
**Do NOT** wrap `import spaces` in `try/except` with a no-op fallback. Off-ZeroGPU, the `spaces` package is *already* a true no-op — the heavyweight behavior is gated on `SPACES_ZERO_GPU=1`, set only on ZeroGPU. `@spaces.GPU` returns the undecorated function unchanged elsewhere. The Gradio base image installs `spaces` on every hardware tier, so a duplicate onto T4 / A10G / CPU works without code changes too.
That said: **iterate ON the Space, not locally.** The Space environment (Python, torch, CUDA, drivers, env vars) differs from yours; passing local tests doesn't prove the Space works. Push early — even with the app not fully polished — and use the rung ladder ([`debugging.md`](debugging.md)) against the live URL.
## Allocator config for memory pressure
If your workload hits transient allocation spikes (high-res pixel-space ops, large attention activations, SR models, video DiTs) and you see:
```
RuntimeError: NVML_SUCCESS == r INTERNAL ASSERT FAILED at .../CUDACachingAllocator.cpp
```
set expandable segments at the **very top** of `app.py`, before any torch import:
```python
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces
import torch
```
Often single-line fix for what looks like an OOM. See [`known-errors.md`](known-errors.md).
## Example caching
`gr.Examples` defaults on ZeroGPU:
- `cache_examples=True`
- `cache_mode="lazy"` (eager would pre-run examples at startup, but no GPU is attached at startup)
Don't override to `cache_mode="eager"` on ZeroGPU — it will fail or burn the creator's daily quota. The cache is keyed by example **file path**, not content hash: regenerating an asset in place serves the stale cached output. Bump a `cache_version` constant if you replace example files.
## Real-time sessions
For real-time apps (webcam, audio streaming), the per-call fork model is too costly. ZeroGPU supports reusable "real-time sessions" — one GPU allocation amortized across many small requests. Reference Spaces:
- https://huggingface.co/spaces/diffusers/unofficial-SDXL-Turbo-i2i-t2i
- https://huggingface.co/spaces/huggingface-projects/rf-detr-realtime-webcam
## When things go wrong
For specific error strings (CUDA init order, illegal duration, allocator asserts, PicklingError, returning CUDA tensors, …): [`known-errors.md`](known-errors.md). It covers the ZeroGPU-specific patterns alongside everything else and is the single error lookup for the skill.
When the log endpoint can't explain a failure (device-side asserts, OOM under specific shapes, race conditions in pickle), dev mode + SSH is the last-resort tool — see [`debugging.md`](debugging.md).
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/huggingface/skills/blob/main/LICENSE