HuggingFace ZeroGPU: Having Agents Write Gradio GPU Demos in Compliance with ZeroGPU Rules

Preface

Running a GPU-enabled Gradio demo on Hugging Face Spaces often faces cost as the first hurdle: dedicated GPU Spaces either require payment or queuing, and moving locally written code onto the platform easily exposes issues specific to it—PicklingError, mismatches between declared duration and actual quota, flash-attn unable to find nvcc during build, or embedding torch.compile in a Space that simply won’t run. Official ZeroGPU documentation updates with hardware generations and quota policies, making it hard to get everything right from memory alone.

huggingface-zerogpu is an Agent Skill maintained by Hugging Face in the skills repository. It encodes the coding conventions, runtime models, and common error mappings for ZeroGPU in SKILL.md, enabling clients like Cursor, Codex, and Claude Code to follow them automatically when writing or troubleshooting code. The sections below describe which problems it solves, what capabilities it covers, and how to install and use it.

What Is This

huggingface-zerogpu targets the scenario “building Gradio AI demos and GPU computations using ZeroGPU on Hugging Face Spaces.” The Skill’s YAML description specifies it should be activated when users write or review code using @spaces.GPU, configure ZeroGPU Spaces’ python_version or requirements.txt, or handle ZeroGPU-specific constraints (pickle-based process isolation, gr.State semantics across worker boundaries, lack of support for torch.compile, CUDA available only via wheels, large / xlarge tiers, dynamic duration, etc.).

The scope has hard boundaries: only Spaces using Gradio SDK + ZeroGPU hardware. Docker Spaces and Static Spaces cannot be scheduled to ZeroGPU; Streamlit currently runs as a Docker Space and is therefore outside this Skill’s scope. General Gradio components and layouts should be covered by the companion huggingface-gradio Skill in the same repository. Authoritative runtime parameters (current backing GPU, runtime version list, tier thresholds) are governed by the ZeroGPU official documentation, which updates as the platform changes.

Core Features

The main Skill body and accompanying references cover the following aspects (all sourced from the official SKILL.md and its citations).

Hardware Specifications and Quotas

ZeroGPU maps a portion of a physical card through size:

size Occupation Quota consumption
large (default) Half card 1x
xlarge Full card 2x

The default large tier has significantly lower memory bandwidth and compute than the full card tier; use xlarge only when you genuinely need additional memory or compute. The documentation stresses that the backing GPU may be swapped without notice, so specific models mentioned in older articles might be outdated; consult the official docs before sizing.

Basic Coding Patterns

Typical approach: load the model at module scope pointing to cuda, and wrap the actual inference function with @spaces.GPU:

import spaces
import torch
from transformers import pipeline

pipe = pipeline("text-generation", model="...", device="cuda")

@spaces.GPU
def generate(prompt: str) -> str:
    return pipe(prompt, max_new_tokens=100)[0]["generated_text"]

Key rules include:

  1. Instantiate models in module scope with .to("cuda") or device="cuda"; ZeroGPU handles subsequent device migration.
  2. Keep GPU computation inside functions decorated with @spaces.GPU only; the decorator is a no-op in non-ZeroGPU environments, so it can remain in the code.
  3. Declare duration for the worst-case scenario (default 60 seconds). The platform pre-checks “requested duration” against a user’s remaining quota, not actual runtime; if a short task uses the 60-second default while the user’s remaining quota is lower, they’ll receive quota exceeded. Smaller duration often queues earlier.
  4. torch.compile is unsupported; instead use PyTorch 2.8+ ahead-of-time compilation (AoTI). Official blog posts explain ZeroGPU-specific guidance.
  5. Use size="xlarge" cautiously: it consumes the full card, doubles quota usage, and often results in longer queues.

Long-running tasks can explicitly declare duration, for example:

@spaces.GPU(duration=120)
def generate_image(prompt: str):
    return pipe(prompt).images[0]

CUDA Availability Model

The real GPU attaches to the process only while a @spaces.GPU function executes; outside module scope there is no GPU. However, importing spaces monkey-patches torch so torch.cuda.is_available() globally returns True, and module-level .to("cuda") does not error—this registers weights to the ZeroGPU backend, which packs/offloads them during startup and then streams them into VRAM in the GPU worker.

Therefore: do not run inference or CUDA kernels at module scope; continue using patterns like device = torch.device("cuda" if torch.cuda.is_available() else "cpu") to avoid hardcoding device="cuda" and breaking CPU Spaces or local CPU environments. Models should be eager-loaded at module scope, not deferred to the first user request (lazy / lru_cache transfers cold-start cost to the first visitor).

Local Development and the spaces Package

Locally, you only need to install spaces. Do not write your own no-op spaces.GPU via try/except: in non-ZeroGPU environments the heavyweight behavior is gated by the SPACES_ZERO_GPU environment variable, and @spaces.GPU already passes through. Gradio SDK base images install spaces on all hardware tiers, so copying to a dedicated GPU or CPU Space usually requires no import changes.

Companion References (Inside the Skill)

File When to consult
references/concurrency.md Read when writing ZeroGPU code; handlers parallelize by default
references/how-zerogpu-works.md Cold starts, worker reuse, module-level warmup not persisting across requests, returning CUDA tensors hanging, etc.
references/how-quota-works.md Choosing duration, illegal duration, and quota exceeded
references/cuda-and-deps.md CUDA dependencies like flash-attn, torch sidecar versions, wheel tags

The Skill description also lists triggering scenarios: when users mention ZeroGPU, @spaces.GPU, the spaces package, or encounter cross-worker PicklingError, illegal duration, or flash-attn wheel build failures. Even without explicitly requesting ZeroGPU guidance, the Skill should activate.

Installation and Activation

Hugging Face Skills follow the Agent Skills format. The repository is huggingface/skills. The huggingface-zerogpu path:

https://github.com/huggingface/skills/tree/main/skills/huggingface-zerogpu

Installation per client (excerpted from the repository README, subject to your environment):

Claude Code

  1. Register the plugin marketplace: /plugin marketplace add huggingface/skills
  2. You may first install the CLI Skill: /plugin install hf-cli@huggingface/skills
  3. Install this Skill: hf skills add huggingface-zerogpu (or the skill name per repository convention; same as hf skills add <skill-name>)

Codex

Copy or symlink skills/huggingface-zerogpu to Codex’s standard .agents/skills location (e.g., $REPO_ROOT/.agents/skills or $HOME/.agents/skills). The client will discover SKILL.md following the Agent Skills standard.

Cursor

The repository provides .cursor-plugin/plugin.json and MCP configuration; the marketplace entry focuses on hf-cli. When installing additional workflow Skills, the documentation recommends:

hf skills add <skill-name>

Replace <skill-name> with huggingface-zerogpu (or the name listed by Hub CLI).

Gemini CLI

You can install via repository extension, e.g.:

gemini extensions install https://github.com/huggingface/skills.git --consent

If the Agent doesn’t support Skills, the repository provides agentsmd/AGENTS.md as a fallback bundle.

Typical Use (Agent Side)

Once the Skill is enabled, the Agent should act in accordance with the Skill and the ZeroGPU documentation, not infer from general PyTorch/CUDA habits:

  1. Create or review a Gradio Space with ZeroGPU hardware, ensuring requirements.txt / python_version satisfy CUDA wheel constraints (no nvcc build).
  2. Add @spaces.GPU to the inference entry point, and set duration and necessary size based on real worst-case time.
  3. When handling concurrency and gr.State, read references/concurrency.md and the process isolation notes, avoiding passing unpicklable objects across workers.
  4. For quota exceeded / illegal duration, consult references/how-quota-works.md to adjust declared duration and quota understanding.
  5. For compilation optimization, avoid torch.compile and switch to the AoTI path.

Developers still maintain business logic in the repository’s app.py (or equivalent entry point). The Skill does not alter the Hub deployment workflow but constrains patches and review notes produced by the Agent.

Suitable Scenarios and Notes

Who it’s for

  • Gradio developers who want a free-tier GPU demo on Spaces or are prototyping.
  • Teams using AI coding assistants to write ZeroGPU Spaces, hoping to reduce platform-specific bugs.
  • Maintainers who want to map keywords like @spaces.GPU, quota, PicklingError to correct fix patterns.

Limitations and pitfalls

  • Only Gradio + ZeroGPU; Docker / Static / Streamlit paths are not covered by the main Skill document.
  • Backing GPU and documentation thresholds change; hardware names in articles or the Skill may be outdated—always defer to official docs.
  • The default duration=60 isn’t friendly to short tasks and strongly affects quota pre-checks.
  • torch.compile isn’t available; CUDA extension dependencies must use prebuilt wheels.
  • Handlers parallelize by default; shared state must be designed alongside the concurrency reference.

The huggingface-spaces Skill in the same repository covers a broader Spaces lifecycle (multiple SDKs, dedicated hardware, debugging, etc.); ZeroGPU details are specialised by huggingface-zerogpu.

Conclusion

ZeroGPU lowers the barrier to showcasing GPU inference demos on the Hub, but its execution model, quota, and build chains differ from ordinary CUDA development. huggingface-zerogpu codifies these rules into an Agent-executable Skill aligned with the official docs and repository references, suitable for use when writing Spaces or troubleshooting issues.

羽毛球分组比赛记分
小程序二维码

欢迎使用《羽毛球分组比赛记分》微信小程序

Xiaoye