huggingface-zerogpu-zh
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "huggingface-zerogpu-zh" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-d78f6b2caa16b6964a42976047d463a4c6f99aa057ed03392eb72983e97836fa. Verify the upstream source and version against https://skillhub.cn/skills/org-02qudk26/huggingface-zerogpu-zh before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
huggingface-zerogpu-zh: A development guide for Gradio Spaces GPU demos based on ZeroGPU.
Introduction source: third_party · org-02qudk26 · 1.0.0 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Audience
- Translation pending; see source documentation.
- Inputs and outputs
- Not specified in the source documentation.
- Software, accounts and paid services
- Not specified in the source documentation.
- Limits and differences
- Not specified in the source documentation.
- Testing
- Not tested
Browse files
Frontmatter
name: huggingface-zerogpu
displayName: Hugging Face ZeroGPU
description: 基于 Gradio Spaces 与 Hugging Face Spaces ZeroGPU 的 AI 演示与 GPU 计算。当用户编写或审查使用 `@spaces.GPU` 的代码、为 ZeroGPU Space 配置 `python_version` 或 `requirements.txt`,或处理 ZeroGPU 特有代码约束(基于 pickle 的进程隔离、`gr.State` 跨 worker 边界语义、禁用 `torch.compile` 而改用 AoTI、仅 CUDA wheel 构建——构建与运行时均无 `nvcc`、large 与 xlarge 规格、动态 duration 可调用对象)时使用。只要用户提到 ZeroGPU、`@spaces.GPU` 或 `spaces` Python 包,或遇到 ZeroGPU 特有的代码错误(如跨 worker 边界的 `PicklingError`、`illegal duration`、`flash-attn` wheel 构建失败),即使未明确要求 ZeroGPU 编码指导,也应使用本技能。在代码中遇到 `import spaces` 或 `@spaces.GPU` 时触发。
summary: 基于 ZeroGPU 的 Gradio Spaces GPU 演示开发指南。
tags: [ZeroGPU, Gradio, Hugging Face, GPU, Spaces]
version: 1.0.0Hugging Face ZeroGPU
针对基于 ZeroGPU 硬件在 Hugging Face Spaces 上运行 ML 演示的规则与模式。涵盖 @spaces.GPU、duration 与配额调优、进程隔离、CUDA 可用性模型、并发安全性,以及 CUDA 构建约束。
适用范围
本技能适用于使用 ZeroGPU 硬件的 Gradio SDK Spaces。Docker 与 Static Spaces 无法调度到 ZeroGPU,而 Streamlit 应用目前也以 Docker Spaces 形式运行——因此本技能仅适用于 Gradio。关于通用 Gradio 编码(组件、布局、事件监听器),请参阅本仓库中的 huggingface-gradio 技能。权威的 ZeroGPU 文档位于 https://huggingface.co/docs/hub/spaces-zerogpu——其中列出了当前的后台 GPU、运行时版本与档位阈值,这些内容会随时间变化,请以文档为准。
参考文件
| 参考 | 阅读时机 |
|---|---|
references/concurrency.md |
编写 ZeroGPU 代码时始终与 SKILL.md 一起阅读——处理器默认并行运行 |
references/how-zerogpu-works.md |
当思考冷启动、worker 复用、为何模块级预热不会延续到请求、或为何返回 CUDA 张量会挂起时 |
references/how-quota-works.md |
当选择 duration 值、调试 illegal duration 与 quota exceeded 错误,或解释为何默认 60s 会阻塞短任务时 |
references/cuda-and-deps.md |
当安装 CUDA 依赖包(如 flash-attn)、固定 torch 侧车(side-car)版本,或读取 wheel 文件名标签时 |
硬件
ZeroGPU 暴露两种映射到后台整卡一部分的 GPU 规格:
size |
后台 GPU 所占比例 | 配额成本 |
|---|---|---|
large (默认) |
一半 | 1x |
xlarge |
整卡 | 2x |
默认 large 提供半个物理 GPU,因此显存带宽与算力都显著低于整卡规格。只有当工作负载确实额外需要显存或算力时,才使用 xlarge。
后台 GPU 会不经通知地变更。 ZeroGPU 已经历数次跨 GPU 代际的迁移;较早的资料可能会提到 A100 或 H200,但那些已经过时。在为工作负载确定规格前,请始终查阅 ZeroGPU 文档 以了解当前的后台 GPU 与每种规格的精确 VRAM。
基本模式
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"]
关键规则:
- 在模块级实例化模型并立即调用
.to("cuda")。ZeroGPU 会透明地处理实际的设备映射(见下文 CUDA 可用性模型)。 - 用
@spaces.GPU装饰 GPU 函数。该装饰器在 ZeroGPU 之外是无操作(no-op),因此在所有环境中保留它都是安全的。 - 将
duration设为匹配实际最坏情况工作负载的值(默认 60s)。平台会将请求的 duration与用户的剩余配额进行预比对——而不是与实际运行时间——因此一个 10 秒的任务若保留默认的 60s,一旦用户剩余配额低于 60s 就会因quota exceeded而失败。声明的duration越小,在节点级队列中排名也越靠前。详见下文“Duration 与配额”。 - 不支持
torch.compile。请改用 PyTorch 的预编译(AoTI,ahead-of-time compilation)(torch 2.8+)。 - 谨慎使用
size="xlarge"。它会分配整张后台 GPU,但成本翻倍(2x 配额)且往往排队更久。
@spaces.GPU(duration=120)
def generate_image(prompt: str):
return pipe(prompt).images[0]
CUDA 可用性模型
真实的 GPU 访问仅在 @spaces.GPU 装饰的函数内部可用。在这些函数之外,GPU 并未挂载到进程上。
不过,import spaces 会对 torch 进行猴子补丁(monkey-patch),使得:
torch.cuda.is_available()全局返回True。- 模块级的
.to("cuda")/device="cuda"调用不会报错地成功。
这是有意为之的。模块级的 model.to("cuda") 调用会向 ZeroGPU 后端注册张量,后者在启动时的“打包”(pack)步骤将其写入磁盘卸载目录,并释放相应的 RAM。当一次 @spaces.GPU 调用到来时,一个 fork 出的 GPU worker 进程通过固定内存(pinned-memory)管道将这些权重从磁盘流式载入 VRAM。热 worker(在同一 GPU 槽位上跨请求复用)会将权重驻留在 GPU 上,从而跳过磁盘 → VRAM 这一步。面向用户的规则是:在模块级写入 device="cuda" 即可生效——完整生命周期见 references/how-zerogpu-works.md。
| 操作 | 位置 | 原因 |
|---|---|---|
model.to("cuda") / pipe(..., device="cuda") |
模块级 | ZeroGPU 注册张量并管理设备迁移 |
| 实际 CUDA 计算(推理等) | @spaces.GPU 内部 |
真实 GPU 仅在被装饰的调用期间挂载 |
基于 torch.cuda.is_available() 分支判断 |
避免依赖它 | 由于猴子补丁,它始终返回 True |
不要在模块级运行推理或 CUDA 核函数——真实 GPU 并未挂载,因此操作要么静默地在 CPU 上运行,要么失败。
设备选择惯用法依然有效
在 ZeroGPU 下,标准惯用法仍然正确:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = AutoModel.from_pretrained("...").to(device)
- ZeroGPU ——
is_available()为True(经猴子补丁),因此模型被注册以进行自动设备迁移。 - 专用 GPU Spaces / 本地 GPU ——
is_available()真正为True。 - CPU Spaces / 本地 CPU —— 解析为
"cpu"。
不要硬编码 device="cuda" —— 这会在纯 CPU 环境下出错。
预加载是正确默认
在模块级加载模型,而不是在首次请求时惰性加载。Space 进程在任何用户到达之前就已启动,因此冷启动成本只需支付一次。惰性加载(global model; if model is None: ...、@lru_cache 包装器、在首次调用时实例化的工厂函数)只是把这笔成本转嫁到了第一位用户身上。
本地开发:只需安装 spaces
不要将 import spaces 包在 try/except 中,并为本地运行把 spaces.GPU 重定义为无操作回退。在 ZeroGPU 之外,spaces 包本身就已经是一个真正的无操作:
- 重量级行为(CUDA 猴子补丁、客户端初始化、启动钩子)受
SPACES_ZERO_GPU环境变量控制,该变量仅在 ZeroGPU 上设置。 @spaces.GPU在 ZeroGPU 之外会原样返回未装饰的函数。- 顶层的
import spaces只执行轻量级导入。
Gradio SDK 基础镜像在每个硬件档位上都安装了 spaces。因此,即使将一个 Space 复制到专用 GPU(T4、L4、A10G 等)或 CPU basic 上,也无需改动代码——import spaces 仍然成功,@spaces.GPU 成为透明的透传。
反模式
try:
import spaces
except ImportError:
class spaces: # type: ignore
@staticmethod
def GPU(func=None, **kwargs):
return func if func else (lambda f: f)
问题:
- 该回退必须模仿每一次
@spaces.GPU调用的形态——裸装饰器、duration=...、size=...、生成器、aoti_*辅助函数——并且会随着spacesAPI 的增长而漂移。 - 它会把
spaces从requirements.txt中隐藏掉,尽管该 Space 在部署时就需要它。 - 它在解决一个并不存在的问题:真正的包在本地已经是无操作。
正确做法
将 spaces 加入依赖,并无条件导入它:
import spaces
@spaces.GPU
def generate(prompt: str) -> str:
...
Duration 与配额
当你声明 @spaces.GPU(duration=N) 时,会发生三件事:
- 档位上限检查 —— 每个访客档位都有单调用
duration上限。声明的duration大于该上限时,无论剩余配额多少,都会立即因ZeroGPU illegal duration而失败。(档位数值会随时间变化——见 ZeroGPU 文档。) - 配额预检查 —— 平台将
请求的 duration与用户的剩余配额比较。若剩余 < 请求,调用会因ZeroGPU quota exceeded而失败——即使实际工作本可容纳。错误消息会显示明确的数字,例如"60s requested vs. 30s left"。因此,一个保留默认 60s 的 10 秒任务,一旦用户剩余配额低于 60s 就会阻塞用户。 - 队列优先级 —— 队列是节点级的(同一节点上所有 Space 的请求竞争 GPU 槽位),声明的
duration越短排名越高。
这三点都倾向于声明最小的实际 duration——包括对短任务也是如此。对 10 秒的任务显式使用 @spaces.GPU(duration=15),可避免过早的 quota exceeded 拒绝,并在队列中排名更高。
xlarge会使请求翻倍。 当size="xlarge"时,请求值 = N * 2,这既适用于档位上限检查,也适用于配额预检查。因此@spaces.GPU(duration=60, size="xlarge")在内部相当于一次 120s 的请求。
针对可变工作负载的动态 duration
对于运行时依赖输入的工作负载,传入一个估计每次请求的可调用对象。静态的高 duration 会把低档位用户挡在门外(其档位上限可能小于该静态值),并为轻量输入不必要地预留配额。
def estimate_duration(prompt, steps):
return int(steps * 3.5)
@spaces.GPU(duration=estimate_duration)
def generate(prompt, steps):
return pipe(prompt, num_inference_steps=steps).images[0]
关于 illegal duration 与 quota exceeded 的完整区别、每日运行次数限制、24 小时配额窗口,以及按量计费,请参阅 references/how-quota-works.md。
进程隔离与 Pickle
@spaces.GPU 装饰的函数运行在由 ZeroGPU 调度器管理的独立进程中。参数与返回值通过 pickle 序列化跨越进程边界。
后果:
- 只有可 pickle 的对象才能传入或返回。文件句柄、数据库连接、锁、lambda,以及依赖不可 pickle 状态的闭包,都会抛出
PicklingError。 - 不要直接返回 CUDA 张量。 在主进程中反序列化 CUDA 张量会触发
torch.cuda._lazy_init(),而 ZeroGPU 会阻止它。先转换到 CPU:返回tensor.cpu()或tensor.cpu().numpy()。 - CPU 张量、numpy 数组、PIL 图像,以及普通 Python 对象都可以正常工作。
- 大对象会产生序列化开销。优先返回轻量结果(张量、数组、文件路径、base64 字符串),而不是复杂的对象图。
跨边界的 gr.State 语义
由于处理器运行在独立进程中,gr.State 的值在每次 yield 时都会被 pickle——它们不是按引用共享的。
- 生成器收到的是状态的副本(
id()与调用方不同)。 - 生成器内部的原地修改,在其他处理器看来是不可见的,直到被修改的状态被显式 yield 回去。
- 对
gr.State槽位 yieldgr.update()会跳过该更新——其他处理器继续看到 yield 前的值。 - 每次返回状态对象的 yield 都会通过 pickle 创建一个新副本。
实践建议:
- 不要假设
gr.State在 ZeroGPU 上具有引用语义。 在生成器中修改状态并期望另一处理器看到这些修改的代码,会静默地使用陈旧数据。 - 每次包含
gr.State值的 yield 都会触发一次完整的 pickle 往返。 对于大状态(模型会话、帧缓冲),尽量减少 yield 它的频率——理想情况下在最后 yield 一次。在中间 yield 时对状态槽位使用gr.update()。 - 状态中的 CUDA 张量在 yield 前必须先移到 CPU —— 原因同上
torch.cuda._lazy_init()问题。
并发
在 ZeroGPU 上,处理器默认并发运行。这不是可选项。在单用户测试中正常的代码,在生产环境中可能静默地损坏或泄漏数据。
三条规则。完整说明与示例见 references/concurrency.md。
- 不要使用可变的全局状态。 并发请求会相互覆盖。
- 不要为输出使用固定的文件路径。 并发请求会覆盖同一文件。使用
tempfile生成唯一路径。 - 只读的全局状态是安全的。 模型对象、分词器、启动时加载一次且请求期间只读的配置是安全的,并且推荐使用。
调用粒度
每次进入 @spaces.GPU 函数都带有不小的成本——跨越进程边界的 pickle 往返、worker 预热、CUDA 重新挂载,以及重新经过节点级队列。在热循环中调用被装饰的函数会成倍放大这些成本,并增加一种新的失败模式:后续迭代可能无法获取 GPU 槽位,使整个任务在中途停滞。
装饰拥有该循环的外层函数,而不是每次迭代的 worker:
# 避免 —— N 帧对应 N 次 GPU 进入
def process_video(frames):
return [process_frame(f) for f in frames]
@spaces.GPU(duration=...)
def process_frame(frame):
...
# 推荐 —— 整个视频只需一次 GPU 进入
@spaces.GPU(duration=...)
def process_video(frames):
return [process_frame(f) for f in frames]
def process_frame(frame):
...
如果循环混合了繁重的 CPU 工作与 GPU 工作,把整个循环包装起来会把那段 CPU 时间也计入用户的配额。当这部分成本不可忽略时,将 GPU 工作批处理,使 CPU 前/后处理留在装饰器之外,是一种视情况而定的优化——并非默认做法。
CUDA 构建约束
HF Spaces 在纯 CPU 环境中构建 Docker 镜像。在 ZeroGPU 上,构建阶段没有 nvcc,因为基础镜像是 python:3.13(专用 GPU Spaces 使用 nvidia/cuda:*-devel-* 并在构建时带有 nvcc)。因此,唯一发行形式是 sdist 的 CUDA 依赖包——例如裸 flash-attn——无法通过 ZeroGPU 上的 requirements.txt 安装。只有预编译的 wheel 可用。
ZeroGPU 运行时确实可用 nvcc,自 2025-07 起从 CUDA devel 镜像挂载到 /cuda-image(最初为支持 AoTI 而加入)。这正是 @spaces.GPU 调用内部能够实现 torch.export / AoTI 工作流的原因。
要点:每一个 CUDA 依赖包都从预编译 wheel 安装。如果 PyPI 上没有可用的 wheel,就在外部构建一个(例如托管在 HF Hub 上)并固定其 URL。对于 flash-attn,上游发布页提供了一份相当完整的 wheel 矩阵,覆盖大多数 Python × CUDA × torch 的组合。
关于 wheel 标签读取(cxx11 ABI、cu12torch2.X、cp3XX)、torch 家族侧车漂移,以及 kernels-community 回退,请参阅 references/cuda-and-deps.md。
示例缓存
gr.Examples 的行为依赖环境。具体到 ZeroGPU:
cache_examples默认True(Spaces 设置GRADIO_CACHE_EXAMPLES=true)。cache_mode默认"lazy"(Spaces 仅在 ZeroGPU 上设置GRADIO_CACHE_MODE=lazy)。
ZeroGPU 默认使用 lazy,是因为即时(eager)缓存会在应用启动时预运行每个示例,但 ZeroGPU 在启动时没有挂载 GPU——只在请求处理期间才有。对受 GPU 约束的示例进行即时缓存会在那里失败。
当 cache_examples=True 时,run_on_click / run_examples_on_click 参数会被静默忽略。如果你的应用依赖“仅在点击时填充”的行为,请显式设置 cache_examples=False 以保留它。
要在本地复现 ZeroGPU 的示例缓存行为:
GRADIO_CACHE_EXAMPLES=true GRADIO_CACHE_MODE=lazy python app.py
依赖管理
README frontmatter 中的 python_version 固定
为 ZeroGPU 固定 python_version 实际上是必需的。运行时默认目前是 Python 3.10,因此在没有显式固定的情况下,使用 3.11+ 的本地环境会在 Space 上安装失败。固定到一个 ZeroGPU 支持的版本(3.12 是合理的默认);权威的支持版本列表见 ZeroGPU 文档——不要硬编码完整列表,请以文档为准。
# README.md frontmatter
python_version: "3.12"
"3.12" 与 "3.12.12" 两种形式都被接受。
不要在 requirements.txt 中固定 spaces
Space 平台会固定它自己的 spaces 版本。requirements.txt 中与之冲突的固定会导致 pip 解析在构建时失败。
规则:不要在
requirements.txt中包含spaces。
如何做到取决于你的工具链:
- 手写
requirements.txt:直接省略spaces。 - uv(由
pyproject.toml管理):在pyproject.toml中声明spaces,以便 uv 共同解析传递约束(尤其是spaces固定的psutil),然后将其从导出中排除:uv export --no-hashes --no-dev --no-emit-package spaces -o requirements.txt如果
pyproject.toml中没有spaces,uv 就无法看到其传递约束,可能在构建时解析出不兼容的版本。 - pip-tools(
pip-compile)/ Poetry:使用等价的排除机制。
固定 torch 以匹配 wheel 标签
如果你通过直接 URL 安装 CUDA 依赖的 wheel,wheel 文件名编码了它构建所针对的 torch 主.次版本(如 cu12torch2.8)。在 requirements.txt 中固定 torch==X.Y.Z 以匹配——否则 pip 可能将 torch 解析到不同版本,导致 Space 在首次导入时失败。详情与 kernels-community 替代方案见 references/cuda-and-deps.md。
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供 Hugging Face ZeroGPU 的完整开发指南,覆盖 GPU 调度、进程隔离、CUDA 约束等关键技术
- 解决用户在 ZeroGPU 上部署 AI 演示时的核心痛点,如 PicklingError、duration 配额管理、gr.State 跨进程语义
Highlights
- 触发条件明确且覆盖全面,包括 @spaces.GPU 装饰器、import spaces、ZeroGPU 特有错误等
- 边界清晰,能有效区分于通用 Gradio 或普通 GPU 开发场景
Areas to improve
-
description 写错位置 Reported severity: Minor
顶层 frontmatter 中 description 字段为空,实际描述内容位于 skill_body 内部
Recommendation: 建议将 description 内容移至顶层 frontmatter 字段,以符合规范
Highlights
- 文档结构清晰,包含适用范围、硬件规格、基本模式、依赖管理等完整章节
- 配有丰富的代码示例和参考文件指引,便于用户理解与实施
Highlights
- 工具来源明确(Hugging Face Spaces、spaces 包),参数说明准确
- 覆盖主要异常场景并提供解决方案,对高风险操作(如 xlarge 配额翻倍)有明确警示
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Domains or addresses referenced in the document
These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.
- huggingface.co
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Not specified in the source documentation.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.