Huggingface Spaces
Hugging FaceOfficialPublished by Hugging Face
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- Medium risk
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
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/huggingface/huggingface-spaces/downloadUnzip 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:
Check the
hfCLI is installed:which hf. If not,pip install -U huggingface_hub.Check the user is logged in:
hf auth whoami. If not, runhf 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.Note
whoami'scanPayandisProflags — 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 10If 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.GPUand 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 onzero-a10gwith 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. Seereferences/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 × 2GB; 48 GB fits ≤24B params at bf16, or much larger with quantization — seereferences/zerogpu.mdfor 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-sdkis required.--flavorselects hardware.zero-a10gis the (legacy) identifier for ZeroGPU. Omitting it givescpu-basic— which is itself gated behind a paid plan, so on a free account pass--flavor zero-a10gexplicitly. Runhf spaces hardwarefor 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=valbecomes 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 viahf spaces secrets set <id> KEY=val.--env KEY=valis 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--flavorat creation, or later viahf 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:
import spacesbefore torch / any CUDA-touching import. It monkey-patchestorch.cuda.*; once CUDA is initialized in the main process, it's too late.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.GPUentry. Lazy loading inside the decorator costs every user.Decorate the function Gradio binds. Estimate
durationto 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.Exampleswhenever 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. Usecache_examples=True, cache_mode="lazy". Seereferences/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 athttps://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/tree/main/wheels. Full mapping + caveats inreferences/requirements.md.
Per-SDK depth
Gradio patterns (themes,
gr.Examples, streaming, custom HTML components,gr.Server):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 buildandapp_file: dist/index.htmlin frontmatter.ZeroGPU specifics (decorator semantics, sizing, AoTI, generators, concurrency, pickle /
gr.Stateacross the worker boundary):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.
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 runtimeB. Logs clean post-boot? Read the run log to confirm startup finished without warnings or silent fallbacks:
hf spaces logs <ns>/<name> --tail 200Look 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/mp4And 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 /dataBuckets 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:
Read the logs:
hf spaces logs <id> --build --follow(build error) orhf spaces logs <id> --follow(runtime error). Find the first error, not the last.Grep
references/known-errors.mdfor 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.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 read | File |
|---|---|
| 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 alignment | references/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 URLs | references/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
- ATTRIBUTION.mdAdded by AutoGineer880 B
- LICENSELicence file added by AutoGineer11.1 KiB
- README.md412 B
- SKILL.md17.5 KiB
- references/3d-cuda-extensions.md9.1 KiB
- references/3d-generation.md8.6 KiB
- references/3d-gsplat.md7.2 KiB
- references/3d-models.md19.6 KiB
- references/3d-outputs.md9.3 KiB
- references/buckets.md4.3 KiB
- references/debugging.md11.3 KiB
- references/gradio.md9.2 KiB
- references/grants.md3.1 KiB
- references/inference-providers.md3.8 KiB
- references/known-errors.md13.3 KiB
- references/requirements.md11.3 KiB
- references/zerogpu.md20.9 KiB
references/3d-models.md
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; the overall workflow in 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 readhttps://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.whlWheel 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):
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.pythat no-opstorch.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-splattingdiff-gaussian-rasterizationfrom a shallow git cloneafterwards,
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:
pipeline = TrellisImageTo3DPipeline.from_pretrained("user/my-finetuned-trellis") # or Trellis2ImageTo3DPipelineIf 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
.plypath 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=120is 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):
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 — cleaner than the JIT build when building fresh.)
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 pathsPreprocessing 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"):
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.
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).
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:
# 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 → 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):
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:
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.
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