Generated banner for Huggingface Spaces
Generated logo for Huggingface Spaces

Huggingface Spaces

Hugging FaceOfficialPublished by Hugging Face

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Medium risk

From the author

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.
— the description by Hugging Face

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to managing Hugging Face Spaces, covering the entire lifecycle from initial setup and hardware selection to deployment, debugging, and persistent storage. It emphasizes the use of the Hugging Face CLI and provides specific patterns for Gradio, Docker, and Static SDKs, with a heavy focus on optimizing for ZeroGPU environments. The skill includes best practices for dependency management, handling CUDA extensions for 3D models, and implementing robust smoke-testing procedures to ensure application reliability.

What it does

  • Guides the creation and configuration of Gradio, Docker, and Static Spaces.
  • Provides instructions for selecting and managing hardware tiers, including ZeroGPU and dedicated instances.
  • Offers debugging workflows for build and runtime errors using logs and smoke tests.
  • Explains how to manage environment variables, secrets, and persistent storage via buckets.
  • Details the integration of 3D generation models, including handling native CUDA extensions.
  • Outlines the process for verifying application health and API responsiveness.

When to use it

  • When you need to host a machine learning application or demo on Hugging Face.
  • When you need to port an existing application to run on ZeroGPU hardware.
  • When a Space is failing to build or run and requires systematic troubleshooting.
  • When you need to manage secrets or persistent storage for a hosted application.
  • When you are deploying specialized 3D generation models requiring custom CUDA extensions.

Advantages

  • Standardizes the deployment process for various ML application types.
  • Provides clear, actionable paths for optimizing performance on ZeroGPU.
  • Reduces trial-and-error by offering a library of known error fixes.
  • Ensures consistent and reliable application verification through structured testing.
  • Simplifies complex tasks like managing 3D model dependencies and hardware allocation.

Usage examples

“Create a new Gradio Space for my image generation model and set it up for ZeroGPU.”
The agent will initialize a new Space repository, configure the necessary frontmatter, and provide the code structure required to utilize ZeroGPU effectively.
“My Space is failing to build with a CUDA error. How do I fix it?”
The agent will guide you through checking the build logs, identifying the specific dependency issue, and applying the correct prebuilt wheel or configuration fix.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/huggingface/huggingface-spaces/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip huggingface-spaces.zip -d .agents/skills

Documentation by Hugging Face

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.

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:

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.

  • 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). 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 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. This avoids hosting the model at all.

4. Create the Space

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:

---
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
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:

  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.

  • 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.

Per-SDK depth

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.

7. Verify

Don't trust RUNNING alone — the app can be running but broken. Four steps, in order:

A. Alive? Stage + hardware:

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:

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:

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:

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.

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:

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.

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 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. 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 readFile
How ZeroGPU works + correct patterns (decorator, sizing, pickle, generators, real-time, AoTI)references/zerogpu.md
Iterate + debug: logs, rung ladder, smoke testing (and dev mode + SSH as a last resort)references/debugging.md
Error-string lookup — the single place for all error symptoms (Spaces, ZeroGPU, Gradio, deps)references/known-errors.md
Pinning deps, picking wheels, torch-family alignmentreferences/requirements.md
gr.Examples (add when it makes sense), themes, custom HTML components, gr.Server, MCP server (mcp_server=True)references/gradio.md
Persistent storage, public bucket URLsreferences/buckets.md
Community grant requests (hardware the user can't pay for)references/grants.md
Provider proxy (zero-VRAM big LLM via Cerebras / Fireworks / Together / etc.)references/inference-providers.md
3D Spaces: generation, CUDA extensions, output formats, and model recipes (incl. gaussian splatting)references/3d-generation.md

Files

references/zerogpu.md

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
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:

import os
os.environ.setdefault("NUMBA_DISABLE_CUDA", "1")
import spaces
2. Load models at module scope, .to("cuda") eagerly
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.

@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:

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:

ModeMemory rule7B27B70B
bf16params × 2 GB14 GB ✓ large54 GB → xlarge140 GB → quant + xlarge
int8params × 1 GB7 GB ✓ large27 GB ✓ large70 GB → xlarge
4-bit (NF4 / int4)params × ~0.55 GB4 GB ✓ large15 GB ✓ large40 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)
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
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), 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:

@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):

@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).

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:

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:

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) 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:

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.

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:

When things go wrong

For specific error strings (CUDA init order, illegal duration, allocator asserts, PicklingError, returning CUDA tensors, …): 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.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs an API key, Needs Python, Needs Node.js

Security

What our scanner noticed· Medium risk

  • References to credential files
  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Hugging Face
Publisher
Hugging Face (Official)
Source
huggingface/skills · skills/huggingface-spaces · commit 25910b3
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Hugging Face.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download huggingface-spaces.zip