mlclaw 0.1.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/mlclaw/SKILL.md +70 -18
- package/Dockerfile +21 -4
- package/README.md +77 -24
- package/assets/hf-logo.svg +8 -0
- package/assets/hf-tooling/manifest.json +50 -0
- package/assets/hf-tooling/skills/hf-cli/SKILL.md +218 -0
- package/assets/hf-tooling/skills/hf-mem/SKILL.md +79 -0
- package/assets/hf-tooling/skills/huggingface-best/SKILL.md +134 -0
- package/assets/hf-tooling/skills/huggingface-datasets/SKILL.md +107 -0
- package/assets/hf-tooling/skills/huggingface-gradio/SKILL.md +298 -0
- package/assets/hf-tooling/skills/huggingface-gradio/examples.md +613 -0
- package/assets/hf-tooling/skills/huggingface-local-models/SKILL.md +113 -0
- package/assets/hf-tooling/skills/huggingface-local-models/references/hardware.md +38 -0
- package/assets/hf-tooling/skills/huggingface-local-models/references/hub-discovery.md +178 -0
- package/assets/hf-tooling/skills/huggingface-local-models/references/quantization.md +256 -0
- package/assets/hf-tooling/skills/huggingface-papers/SKILL.md +239 -0
- package/assets/hf-tooling/skills/huggingface-spaces/SKILL.md +239 -0
- package/assets/hf-tooling/skills/huggingface-spaces/references/buckets.md +89 -0
- package/assets/hf-tooling/skills/huggingface-spaces/references/debugging.md +236 -0
- package/assets/hf-tooling/skills/huggingface-spaces/references/gradio.md +200 -0
- package/assets/hf-tooling/skills/huggingface-spaces/references/grants.md +56 -0
- package/assets/hf-tooling/skills/huggingface-spaces/references/inference-providers.md +85 -0
- package/assets/hf-tooling/skills/huggingface-spaces/references/known-errors.md +232 -0
- package/assets/hf-tooling/skills/huggingface-spaces/references/requirements.md +169 -0
- package/assets/hf-tooling/skills/huggingface-spaces/references/zerogpu.md +349 -0
- package/assets/hf-tooling/skills/huggingface-tool-builder/SKILL.md +120 -0
- package/assets/hf-tooling/skills/huggingface-tool-builder/references/baseline_hf_api.py +57 -0
- package/assets/hf-tooling/skills/huggingface-tool-builder/references/baseline_hf_api.sh +40 -0
- package/assets/hf-tooling/skills/huggingface-tool-builder/references/baseline_hf_api.tsx +57 -0
- package/assets/hf-tooling/skills/huggingface-tool-builder/references/find_models_by_paper.sh +230 -0
- package/assets/hf-tooling/skills/huggingface-tool-builder/references/hf_enrich_models.sh +96 -0
- package/assets/hf-tooling/skills/huggingface-tool-builder/references/hf_model_card_frontmatter.sh +188 -0
- package/assets/hf-tooling/skills/huggingface-tool-builder/references/hf_model_papers_auth.sh +171 -0
- package/assets/hf-tooling/skills/huggingface-zerogpu/SKILL.md +289 -0
- package/assets/hf-tooling/skills/huggingface-zerogpu/references/concurrency.md +79 -0
- package/assets/hf-tooling/skills/huggingface-zerogpu/references/cuda-and-deps.md +66 -0
- package/assets/hf-tooling/skills/huggingface-zerogpu/references/how-quota-works.md +74 -0
- package/assets/hf-tooling/skills/huggingface-zerogpu/references/how-zerogpu-works.md +50 -0
- package/assets/hf-tooling/templates/.agents/mcp/huggingface.json +11 -0
- package/assets/hf-tooling/templates/.env.example +5 -0
- package/assets/hf-tooling/templates/examples/huggingface/README.md +16 -0
- package/assets/hf-tooling/templates/examples/huggingface/bucket-sync.md +19 -0
- package/assets/hf-tooling/templates/examples/huggingface/dataset-upload.py +22 -0
- package/assets/hf-tooling/templates/examples/huggingface/hf-discover.md +13 -0
- package/assets/hf-tooling/templates/examples/huggingface/runtime-inspection.py +9 -0
- package/assets/mlclaw-control-ui/assets/index-D2TFes32.js +9 -0
- package/assets/mlclaw-control-ui/assets/index-DP72PFuv.css +1 -0
- package/assets/mlclaw-control-ui/index.html +13 -0
- package/assets/mlclaw.svg +298 -124
- package/dist/hf-tooling-seed.js +261 -0
- package/dist/mlclaw-space-runtime.js +6746 -3321
- package/dist/mlclaw.mjs +428 -178
- package/entrypoint.sh +4 -0
- package/mlclaw.ps1 +4 -2
- package/mlclaw.sh +5 -3
- package/openclaw.default.json +1 -0
- package/package.json +16 -2
- package/space/README.md +32 -2
- package/tsconfig.json +3 -2
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
|
|
3
|
+
# Hugging Face Model Papers Tool with Authentication
|
|
4
|
+
# Fetches papers referenced by Hugging Face models using HF_TOKEN if available
|
|
5
|
+
|
|
6
|
+
set -euo pipefail
|
|
7
|
+
|
|
8
|
+
# Help function
|
|
9
|
+
show_help() {
|
|
10
|
+
cat << EOF
|
|
11
|
+
Hugging Face Model Papers Tool with Authentication
|
|
12
|
+
|
|
13
|
+
This tool fetches papers referenced by Hugging Face models.
|
|
14
|
+
Supports authentication via HF_TOKEN environment variable.
|
|
15
|
+
|
|
16
|
+
Usage:
|
|
17
|
+
$0 [OPTIONS]
|
|
18
|
+
|
|
19
|
+
Options:
|
|
20
|
+
MODEL_ID Specific model to analyze (e.g., microsoft/DialoGPT-medium)
|
|
21
|
+
--trending [N] Show papers for top N trending models (default: 5)
|
|
22
|
+
--help Show this help message
|
|
23
|
+
|
|
24
|
+
Environment Variables:
|
|
25
|
+
HF_TOKEN Hugging Face API token (optional, for private models)
|
|
26
|
+
|
|
27
|
+
Examples:
|
|
28
|
+
# Get papers for a specific model
|
|
29
|
+
$0 microsoft/DialoGPT-medium
|
|
30
|
+
|
|
31
|
+
# Get papers with authentication
|
|
32
|
+
HF_TOKEN=your_token_here $0 your-private-model
|
|
33
|
+
|
|
34
|
+
# Get papers for top 3 trending models
|
|
35
|
+
$0 --trending 3
|
|
36
|
+
|
|
37
|
+
EOF
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
# Function to make authenticated API calls
|
|
41
|
+
hf_api_call() {
|
|
42
|
+
local url="$1"
|
|
43
|
+
local headers=()
|
|
44
|
+
|
|
45
|
+
# Add authentication header if HF_TOKEN is set
|
|
46
|
+
if [[ -n "${HF_TOKEN:-}" ]]; then
|
|
47
|
+
headers+=(-H "Authorization: Bearer $HF_TOKEN")
|
|
48
|
+
fi
|
|
49
|
+
|
|
50
|
+
curl -s "${headers[@]}" "$url" 2>/dev/null || echo '{"error": "Network error"}'
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
# Function to extract papers from text
|
|
54
|
+
extract_papers() {
|
|
55
|
+
local text="$1"
|
|
56
|
+
local title="$2"
|
|
57
|
+
|
|
58
|
+
echo "$title"
|
|
59
|
+
|
|
60
|
+
# Find ArXiv URLs
|
|
61
|
+
local arxiv_urls=$(echo "$text" | grep -oE 'https?://arxiv\.org/[^[:space:]\])]+' | head -5)
|
|
62
|
+
if [[ -n "$arxiv_urls" ]]; then
|
|
63
|
+
echo "ArXiv Papers:"
|
|
64
|
+
echo "$arxiv_urls" | sed 's/^/ • /'
|
|
65
|
+
fi
|
|
66
|
+
|
|
67
|
+
# Find DOI URLs
|
|
68
|
+
local doi_urls=$(echo "$text" | grep -oE 'https?://doi\.org/[^[:space:]\])]+' | head -3)
|
|
69
|
+
if [[ -n "$doi_urls" ]]; then
|
|
70
|
+
echo "DOI Papers:"
|
|
71
|
+
echo "$doi_urls" | sed 's/^/ • /'
|
|
72
|
+
fi
|
|
73
|
+
|
|
74
|
+
# Find arxiv IDs in format YYYY.NNNNN
|
|
75
|
+
local arxiv_ids=$(echo "$text" | grep -oE 'arXiv:[0-9]{4}\.[0-9]{4,5}' | head -5)
|
|
76
|
+
if [[ -n "$arxiv_ids" ]]; then
|
|
77
|
+
echo "ArXiv IDs:"
|
|
78
|
+
echo "$arxiv_ids" | sed 's/^/ • /'
|
|
79
|
+
fi
|
|
80
|
+
|
|
81
|
+
# Check for paper mentions
|
|
82
|
+
if echo "$text" | grep -qi "paper\|publication\|citation"; then
|
|
83
|
+
local paper_mentions=$(echo "$text" | grep -i -A1 -B1 "paper\|publication" | head -6)
|
|
84
|
+
if [[ -n "$paper_mentions" ]]; then
|
|
85
|
+
echo "Paper mentions:"
|
|
86
|
+
echo "$paper_mentions" | sed 's/^/ /'
|
|
87
|
+
fi
|
|
88
|
+
fi
|
|
89
|
+
|
|
90
|
+
if [[ -z "$arxiv_urls" && -z "$doi_urls" && -z "$arxiv_ids" ]]; then
|
|
91
|
+
echo "No papers found in model card"
|
|
92
|
+
fi
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
# Function to get model papers
|
|
96
|
+
get_model_papers() {
|
|
97
|
+
local model_id="$1"
|
|
98
|
+
|
|
99
|
+
echo "=== $model_id ==="
|
|
100
|
+
|
|
101
|
+
# Get model info from API with authentication
|
|
102
|
+
local api_url="https://huggingface.co/api/models/$model_id"
|
|
103
|
+
local response=$(hf_api_call "$api_url")
|
|
104
|
+
|
|
105
|
+
if echo "$response" | grep -q '"error"'; then
|
|
106
|
+
echo "Error: Could not fetch model '$model_id'"
|
|
107
|
+
if [[ -z "${HF_TOKEN:-}" ]]; then
|
|
108
|
+
echo "Note: This might be a private model. Try setting HF_TOKEN environment variable."
|
|
109
|
+
fi
|
|
110
|
+
return 1
|
|
111
|
+
fi
|
|
112
|
+
|
|
113
|
+
# Parse basic info
|
|
114
|
+
local downloads=$(echo "$response" | jq -r '.downloads // 0')
|
|
115
|
+
local likes=$(echo "$response" | jq -r '.likes // 0')
|
|
116
|
+
echo "Downloads: $downloads | Likes: $likes"
|
|
117
|
+
|
|
118
|
+
# Get model card
|
|
119
|
+
local card_url="https://huggingface.co/$model_id/raw/main/README.md"
|
|
120
|
+
local card_content=$(curl -s "$card_url" 2>/dev/null || echo "")
|
|
121
|
+
|
|
122
|
+
if [[ -n "$card_content" ]]; then
|
|
123
|
+
extract_papers "$card_content" "Papers from model card:"
|
|
124
|
+
else
|
|
125
|
+
echo "Could not fetch model card"
|
|
126
|
+
fi
|
|
127
|
+
|
|
128
|
+
# Check tags for arxiv references
|
|
129
|
+
local arxiv_tag=$(echo "$response" | jq -r '.tags[]' 2>/dev/null | grep arxiv || true)
|
|
130
|
+
if [[ -n "$arxiv_tag" ]]; then
|
|
131
|
+
echo "ArXiv from tags: $arxiv_tag"
|
|
132
|
+
fi
|
|
133
|
+
|
|
134
|
+
echo
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
# Function to get trending models
|
|
138
|
+
get_trending_models() {
|
|
139
|
+
local limit="${1:-5}"
|
|
140
|
+
|
|
141
|
+
echo "Fetching top $limit trending models..."
|
|
142
|
+
|
|
143
|
+
local trending_url="https://huggingface.co/api/trending?type=model&limit=$limit"
|
|
144
|
+
local response=$(hf_api_call "$trending_url")
|
|
145
|
+
|
|
146
|
+
echo "$response" | jq -r '.recentlyTrending[] | .repoData.id' | head -"$limit" | while read -r model_id; do
|
|
147
|
+
if [[ -n "$model_id" ]]; then
|
|
148
|
+
get_model_papers "$model_id"
|
|
149
|
+
fi
|
|
150
|
+
done
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
# Main
|
|
154
|
+
if [[ $# -eq 0 ]]; then
|
|
155
|
+
echo "Error: No arguments provided"
|
|
156
|
+
show_help
|
|
157
|
+
exit 1
|
|
158
|
+
fi
|
|
159
|
+
|
|
160
|
+
if [[ "$1" == "--help" ]]; then
|
|
161
|
+
show_help
|
|
162
|
+
exit 0
|
|
163
|
+
elif [[ "$1" == "--trending" ]]; then
|
|
164
|
+
if [[ -n "${2:-}" ]] && [[ "$2" =~ ^[0-9]+$ ]]; then
|
|
165
|
+
get_trending_models "$2"
|
|
166
|
+
else
|
|
167
|
+
get_trending_models 5
|
|
168
|
+
fi
|
|
169
|
+
else
|
|
170
|
+
get_model_papers "$1"
|
|
171
|
+
fi
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: huggingface-zerogpu
|
|
3
|
+
description: AI demos and GPU compute with Gradio Spaces and Hugging Face Spaces ZeroGPU. Use when writing or reviewing code that uses `@spaces.GPU`, configuring `python_version` or `requirements.txt` for a ZeroGPU Space, or handling ZeroGPU-specific code constraints — pickle-based process isolation, `gr.State` semantics across the worker boundary, no `torch.compile` (use AoTI instead), CUDA wheel-only builds (no `nvcc` at build or runtime), large vs xlarge sizing, and dynamic duration callables. Make sure to use this skill whenever the user mentions ZeroGPU, `@spaces.GPU`, or the `spaces` Python package, or hits ZeroGPU-specific code errors like `PicklingError` across the worker boundary, `illegal duration`, or `flash-attn` wheel-build failures — even when the user does not explicitly ask for ZeroGPU coding guidance. Trigger on `import spaces` or `@spaces.GPU` in code.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Hugging Face ZeroGPU
|
|
7
|
+
|
|
8
|
+
Rules and patterns for ML demos on Hugging Face Spaces with **ZeroGPU** hardware. Covers `@spaces.GPU`, duration and quota tuning, process isolation, the CUDA availability model, concurrency safety, and CUDA build constraints.
|
|
9
|
+
|
|
10
|
+
## Scope
|
|
11
|
+
|
|
12
|
+
This skill is for **Gradio SDK Spaces using ZeroGPU hardware**. Docker and Static Spaces cannot schedule onto ZeroGPU, and Streamlit apps now run as Docker Spaces — so this skill applies only to Gradio. For general Gradio coding (components, layouts, event listeners), see the `huggingface-gradio` skill in this repo. The authoritative ZeroGPU docs live at https://huggingface.co/docs/hub/spaces-zerogpu — refer to them for the current backing GPU, runtime version lists, and tier thresholds, all of which change over time.
|
|
13
|
+
|
|
14
|
+
## Reference Files
|
|
15
|
+
|
|
16
|
+
| Reference | When to read |
|
|
17
|
+
|-----------|--------------|
|
|
18
|
+
| `references/concurrency.md` | Always read alongside SKILL.md when writing ZeroGPU code — handlers run in parallel by default |
|
|
19
|
+
| `references/how-zerogpu-works.md` | When reasoning about cold-starts, worker reuse, why module-scope warmup does not carry to requests, or why returning CUDA tensors hangs |
|
|
20
|
+
| `references/how-quota-works.md` | When choosing `duration` values, debugging `illegal duration` vs `quota exceeded` errors, or explaining why default 60s blocks short tasks |
|
|
21
|
+
| `references/cuda-and-deps.md` | When installing CUDA-dependent packages (e.g. `flash-attn`), pinning torch side-cars, or reading wheel filename tags |
|
|
22
|
+
|
|
23
|
+
## Hardware
|
|
24
|
+
|
|
25
|
+
ZeroGPU exposes two GPU sizes that map to a fraction of the backing card:
|
|
26
|
+
|
|
27
|
+
| `size` | Slice of backing GPU | Quota cost |
|
|
28
|
+
|--------|----------------------|------------|
|
|
29
|
+
| `large` *(default)* | Half | 1x |
|
|
30
|
+
| `xlarge` | Full | 2x |
|
|
31
|
+
|
|
32
|
+
Default `large` gives half a physical GPU, so memory bandwidth and compute are significantly lower than the full card's specs. Use `xlarge` only when the workload genuinely needs the extra memory or compute.
|
|
33
|
+
|
|
34
|
+
> **Backing GPU changes without notice.** ZeroGPU has already migrated across GPU generations several times; older write-ups may name A100 or H200, but those are outdated. For the current backing GPU and exact per-size VRAM, always check the [ZeroGPU docs](https://huggingface.co/docs/hub/spaces-zerogpu) before sizing workloads.
|
|
35
|
+
|
|
36
|
+
## Basic Pattern
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import spaces
|
|
40
|
+
import torch
|
|
41
|
+
from transformers import pipeline
|
|
42
|
+
|
|
43
|
+
pipe = pipeline("text-generation", model="...", device="cuda")
|
|
44
|
+
|
|
45
|
+
@spaces.GPU
|
|
46
|
+
def generate(prompt: str) -> str:
|
|
47
|
+
return pipe(prompt, max_new_tokens=100)[0]["generated_text"]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Key rules:
|
|
51
|
+
|
|
52
|
+
1. **Instantiate models at module scope** and call `.to("cuda")` eagerly. ZeroGPU handles the actual device mapping transparently (see CUDA availability model below).
|
|
53
|
+
2. **Decorate GPU functions with `@spaces.GPU`**. The decorator is a no-op outside ZeroGPU, so it is safe to keep in all environments.
|
|
54
|
+
3. **Set `duration` to match the realistic worst-case workload** (default 60s). The platform pre-checks `requested duration` against the user's `remaining quota` — not against the actual run time — so a 10-second task left at the 60s default fails with `quota exceeded` as soon as the user's remaining quota drops below 60s. Smaller declared `duration` also ranks higher in the node-level queue. See "Duration and Quota" below.
|
|
55
|
+
4. **`torch.compile` is NOT supported.** Use PyTorch [ahead-of-time compilation (AoTI)](https://huggingface.co/blog/zerogpu-aoti) (torch 2.8+) instead.
|
|
56
|
+
5. **Use `size="xlarge"` sparingly.** It allocates the full backing GPU, but costs 2x quota and tends to queue longer.
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
@spaces.GPU(duration=120)
|
|
60
|
+
def generate_image(prompt: str):
|
|
61
|
+
return pipe(prompt).images[0]
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## CUDA Availability Model
|
|
65
|
+
|
|
66
|
+
Real GPU access is **only** available inside `@spaces.GPU`-decorated functions. Outside those functions, the GPU is not attached to the process.
|
|
67
|
+
|
|
68
|
+
However, `import spaces` **monkey-patches `torch`** so that:
|
|
69
|
+
|
|
70
|
+
- `torch.cuda.is_available()` returns `True` globally.
|
|
71
|
+
- `.to("cuda")` / `device="cuda"` calls at module scope succeed without error.
|
|
72
|
+
|
|
73
|
+
This is intentional. Module-scope `model.to("cuda")` calls register tensors with the ZeroGPU backend, which writes them to a disk offload directory at a startup "pack" step and frees the corresponding RAM. When a `@spaces.GPU` call lands, a forked GPU worker process streams those weights from disk into VRAM via a pinned-memory pipeline. Warm workers (reused across requests on the same GPU slot) keep weights resident on the GPU and skip the disk → VRAM step. The user-facing rule: write `device="cuda"` at module scope and it works — see `references/how-zerogpu-works.md` for the full lifecycle.
|
|
74
|
+
|
|
75
|
+
| Action | Where | Why |
|
|
76
|
+
|--------|-------|-----|
|
|
77
|
+
| `model.to("cuda")` / `pipe(..., device="cuda")` | **Module scope** | ZeroGPU registers the tensor and manages device migration |
|
|
78
|
+
| Actual CUDA computation (inference, etc.) | **Inside `@spaces.GPU`** | Real GPU is only attached during the decorated call |
|
|
79
|
+
| Branching on `torch.cuda.is_available()` | Avoid relying on it | Always returns `True` due to the monkey-patch |
|
|
80
|
+
|
|
81
|
+
Do not run inference or CUDA kernels at module scope — the real GPU is not attached, so operations either silently run on CPU or fail.
|
|
82
|
+
|
|
83
|
+
### Device selection idiom still works
|
|
84
|
+
|
|
85
|
+
The standard idiom remains correct under ZeroGPU:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
89
|
+
model = AutoModel.from_pretrained("...").to(device)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
- **ZeroGPU** — `is_available()` is `True` (monkey-patched), so the model is registered for automatic device migration.
|
|
93
|
+
- **Dedicated GPU Spaces / local GPU** — `is_available()` is genuinely `True`.
|
|
94
|
+
- **CPU Spaces / local CPU** — resolves to `"cpu"`.
|
|
95
|
+
|
|
96
|
+
Do not hardcode `device="cuda"` — it breaks on CPU-only environments.
|
|
97
|
+
|
|
98
|
+
### Eager loading is the right default
|
|
99
|
+
|
|
100
|
+
Load models at module scope, not lazily on first request. The Space process starts before any user arrives, so cold-start cost is paid once. Lazy loading (`global model; if model is None: ...`, `@lru_cache` wrappers, factory functions instantiating on first call) just pushes that cost onto the first user.
|
|
101
|
+
|
|
102
|
+
## Local Development: Just Install `spaces`
|
|
103
|
+
|
|
104
|
+
Do **not** wrap `import spaces` in `try/except` and redefine `spaces.GPU` as a no-op fallback for local runs. Off-ZeroGPU, the `spaces` package is already a true no-op:
|
|
105
|
+
|
|
106
|
+
- Heavyweight behavior (CUDA monkey-patching, client init, startup hooks) is gated on the `SPACES_ZERO_GPU` env var, set only on ZeroGPU.
|
|
107
|
+
- `@spaces.GPU` returns the undecorated function unchanged off-ZeroGPU.
|
|
108
|
+
- Top-level `import spaces` performs only lightweight imports.
|
|
109
|
+
|
|
110
|
+
The Gradio SDK base image installs `spaces` on every hardware tier. So even after duplicating a Space onto a dedicated GPU (T4, L4, A10G, etc.) or CPU basic, no code changes are needed — `import spaces` still succeeds and `@spaces.GPU` becomes a transparent passthrough.
|
|
111
|
+
|
|
112
|
+
### Anti-pattern
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
try:
|
|
116
|
+
import spaces
|
|
117
|
+
except ImportError:
|
|
118
|
+
class spaces: # type: ignore
|
|
119
|
+
@staticmethod
|
|
120
|
+
def GPU(func=None, **kwargs):
|
|
121
|
+
return func if func else (lambda f: f)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Problems:
|
|
125
|
+
|
|
126
|
+
1. The fallback must mimic every `@spaces.GPU` call shape — bare decorator, `duration=...`, `size=...`, generators, `aoti_*` helpers — and drifts as the `spaces` API grows.
|
|
127
|
+
2. It hides `spaces` from `requirements.txt`, even though the Space needs it at deploy time.
|
|
128
|
+
3. It solves a non-problem: the real package is already a no-op locally.
|
|
129
|
+
|
|
130
|
+
### Do this instead
|
|
131
|
+
|
|
132
|
+
Add `spaces` to dependencies and import it unconditionally:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
import spaces
|
|
136
|
+
|
|
137
|
+
@spaces.GPU
|
|
138
|
+
def generate(prompt: str) -> str:
|
|
139
|
+
...
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Duration and Quota
|
|
143
|
+
|
|
144
|
+
Three things happen when you declare `@spaces.GPU(duration=N)`:
|
|
145
|
+
|
|
146
|
+
1. **Tier-max check** — each visitor tier has a per-call `duration` cap. Declaring `duration` larger than the cap fails immediately with `ZeroGPU illegal duration`, regardless of remaining quota. (Tier numbers change over time — see the [ZeroGPU docs](https://huggingface.co/docs/hub/spaces-zerogpu).)
|
|
147
|
+
2. **Quota pre-check** — the platform compares `requested duration` against the user's `remaining quota`. If `remaining < requested`, the call fails with `ZeroGPU quota exceeded` — even if the actual work would have fit. The error message shows the explicit numbers, e.g. `"60s requested vs. 30s left"`. A 10-second task left at the default 60s therefore blocks the user once their remaining quota drops below 60s.
|
|
148
|
+
3. **Queue priority** — the queue is node-level (requests from all Spaces on the same node compete for GPU slots), and shorter declared `duration` ranks higher.
|
|
149
|
+
|
|
150
|
+
All three favor declaring the smallest realistic `duration` — including for short tasks. Explicit `@spaces.GPU(duration=15)` on a 10-second task avoids premature `quota exceeded` rejections and ranks higher in the queue.
|
|
151
|
+
|
|
152
|
+
> **`xlarge` doubles the request.** `requested = N * 2` when `size="xlarge"`, both for the tier-max check and the quota pre-check. So `@spaces.GPU(duration=60, size="xlarge")` is internally a 120s request.
|
|
153
|
+
|
|
154
|
+
### Dynamic duration for variable workloads
|
|
155
|
+
|
|
156
|
+
For workloads whose runtime depends on inputs, pass a callable that estimates per request. A static high `duration` locks out low-tier users (whose tier cap may be smaller than the static value) and unnecessarily reserves quota for light inputs.
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
def estimate_duration(prompt, steps):
|
|
160
|
+
return int(steps * 3.5)
|
|
161
|
+
|
|
162
|
+
@spaces.GPU(duration=estimate_duration)
|
|
163
|
+
def generate(prompt, steps):
|
|
164
|
+
return pipe(prompt, num_inference_steps=steps).images[0]
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
For the full distinction between `illegal duration` vs `quota exceeded`, runs-per-day limits, the 24h quota window, and pay-as-you-go billing, see `references/how-quota-works.md`.
|
|
168
|
+
|
|
169
|
+
## Process Isolation and Pickle
|
|
170
|
+
|
|
171
|
+
`@spaces.GPU`-decorated functions run in a **separate process** managed by the ZeroGPU scheduler. Arguments and return values cross the process boundary via **pickle serialization**.
|
|
172
|
+
|
|
173
|
+
Consequences:
|
|
174
|
+
|
|
175
|
+
- **Only picklable objects** can be passed in or returned. Open file handles, database connections, locks, lambdas, and closures over unpicklable state will raise `PicklingError`.
|
|
176
|
+
- **Do NOT return CUDA tensors directly.** Unpickling a CUDA tensor in the main process triggers `torch.cuda._lazy_init()`, which ZeroGPU blocks. Convert to CPU first: return `tensor.cpu()` or `tensor.cpu().numpy()`.
|
|
177
|
+
- CPU tensors, numpy arrays, PIL Images, and plain Python objects work fine.
|
|
178
|
+
- Large objects incur serialization overhead. Prefer lightweight returns (tensors, arrays, file paths, base64 strings) over complex object graphs.
|
|
179
|
+
|
|
180
|
+
### `gr.State` semantics across the boundary
|
|
181
|
+
|
|
182
|
+
Because handlers run in a separate process, `gr.State` values are **pickled on every yield** — they are NOT shared by reference.
|
|
183
|
+
|
|
184
|
+
- The generator receives a **copy** of the state (`id()` differs from the caller's).
|
|
185
|
+
- In-place mutations inside the generator are **invisible** to other handlers until the mutated state is explicitly yielded back.
|
|
186
|
+
- Yielding `gr.update()` for a `gr.State` slot **skips the update** — other handlers continue to see the pre-yield value.
|
|
187
|
+
- Each yield that returns the state object creates a **new copy** via pickle.
|
|
188
|
+
|
|
189
|
+
Practical guidance:
|
|
190
|
+
|
|
191
|
+
- **Do NOT assume reference semantics for `gr.State`** on ZeroGPU. Code that mutates state in a generator and expects another handler to see those mutations will silently use stale data.
|
|
192
|
+
- **Every yield including a `gr.State` value triggers a full pickle round-trip.** For large state (model sessions, frame buffers), minimize how often you yield it — ideally once at the end. Use `gr.update()` for the state slot on intermediate yields.
|
|
193
|
+
- **CUDA tensors inside state must be moved to CPU before yielding** — same `torch.cuda._lazy_init()` issue as above.
|
|
194
|
+
|
|
195
|
+
## Concurrency
|
|
196
|
+
|
|
197
|
+
Handlers run **concurrently by default** on ZeroGPU. This is not opt-in. Code that worked in single-user testing can silently corrupt or leak data in production.
|
|
198
|
+
|
|
199
|
+
Three rules. Full treatment with examples in `references/concurrency.md`.
|
|
200
|
+
|
|
201
|
+
1. **No mutable global state.** Concurrent requests overwrite each other.
|
|
202
|
+
2. **No fixed file paths for outputs.** Concurrent requests clobber the same file. Use `tempfile` for unique paths.
|
|
203
|
+
3. **Read-only globals are safe.** Model objects, tokenizers, configs loaded once at startup and only read during requests are safe and encouraged.
|
|
204
|
+
|
|
205
|
+
## Call Granularity
|
|
206
|
+
|
|
207
|
+
Each entry into a `@spaces.GPU` function carries non-trivial cost — pickle round-trip across the process boundary, worker warm-up, CUDA re-attach, and a fresh pass through the node-level queue. Calling a decorated function from inside a hot loop multiplies these costs and adds a new failure mode: a later iteration may fail to acquire a GPU slot, stalling the whole job mid-way.
|
|
208
|
+
|
|
209
|
+
Decorate the outer function that owns the loop, not the per-iteration worker:
|
|
210
|
+
|
|
211
|
+
```python
|
|
212
|
+
# Avoid — N GPU entries for N frames
|
|
213
|
+
def process_video(frames):
|
|
214
|
+
return [process_frame(f) for f in frames]
|
|
215
|
+
|
|
216
|
+
@spaces.GPU(duration=...)
|
|
217
|
+
def process_frame(frame):
|
|
218
|
+
...
|
|
219
|
+
|
|
220
|
+
# Prefer — one GPU entry for the whole video
|
|
221
|
+
@spaces.GPU(duration=...)
|
|
222
|
+
def process_video(frames):
|
|
223
|
+
return [process_frame(f) for f in frames]
|
|
224
|
+
|
|
225
|
+
def process_frame(frame):
|
|
226
|
+
...
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
If the loop mixes heavy CPU work with GPU work, wrapping the whole loop charges that CPU time against the user's quota. When that cost is material, batching the GPU work so CPU pre/post-processing stays outside the decorator is a situational optimization — not the default.
|
|
230
|
+
|
|
231
|
+
## CUDA Build Constraints
|
|
232
|
+
|
|
233
|
+
HF Spaces builds Docker images in a CPU-only environment. **On ZeroGPU, the build phase has no `nvcc`** because the base image is `python:3.13` (dedicated-GPU Spaces use `nvidia/cuda:*-devel-*` and have `nvcc` at build time). A CUDA-dependent package whose only distribution is sdist — e.g. bare `flash-attn` — therefore cannot be installed via `requirements.txt` on ZeroGPU. Only pre-built wheels work.
|
|
234
|
+
|
|
235
|
+
ZeroGPU **runtime** does have `nvcc` available, mounted from a CUDA devel image at `/cuda-image` since 2025-07 (originally added for AoTI support). This is what makes `torch.export` / AoTI workflows possible inside `@spaces.GPU` calls.
|
|
236
|
+
|
|
237
|
+
**Bottom line**: install every CUDA-dependent package from a pre-built wheel. If no wheel is available on PyPI, build one externally (e.g. host on HF Hub) and pin the URL. For `flash-attn`, the upstream releases page ships a fairly complete wheel matrix covering most Python × CUDA × torch combinations.
|
|
238
|
+
|
|
239
|
+
For wheel-tag reading (cxx11 ABI, `cu12torch2.X`, `cp3XX`), torch-family side-car drift, and the kernels-community fallback, see `references/cuda-and-deps.md`.
|
|
240
|
+
|
|
241
|
+
## Example Caching
|
|
242
|
+
|
|
243
|
+
`gr.Examples` behavior is environment-dependent. On ZeroGPU specifically:
|
|
244
|
+
|
|
245
|
+
- `cache_examples` defaults to `True` (Spaces sets `GRADIO_CACHE_EXAMPLES=true`).
|
|
246
|
+
- `cache_mode` defaults to `"lazy"` (Spaces sets `GRADIO_CACHE_MODE=lazy` only on ZeroGPU).
|
|
247
|
+
|
|
248
|
+
ZeroGPU defaults to `lazy` because eager caching pre-runs every example at app startup, but ZeroGPU has **no GPU attached at startup** — only during request handling. Eager caching of GPU-bound examples would fail there.
|
|
249
|
+
|
|
250
|
+
When `cache_examples=True`, the `run_on_click` / `run_examples_on_click` parameter is silently ignored. If your app relies on click-populates-only behavior, set `cache_examples=False` explicitly to preserve it.
|
|
251
|
+
|
|
252
|
+
To reproduce ZeroGPU example-caching behavior locally:
|
|
253
|
+
|
|
254
|
+
```bash
|
|
255
|
+
GRADIO_CACHE_EXAMPLES=true GRADIO_CACHE_MODE=lazy python app.py
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## Dependency Management
|
|
259
|
+
|
|
260
|
+
### `python_version` pin in README frontmatter
|
|
261
|
+
|
|
262
|
+
Pinning `python_version` is **effectively required** for ZeroGPU. The runtime default is currently Python 3.10, so a local environment using 3.11+ will fail to install on the Space without an explicit pin. Pin to a ZeroGPU-supported version (3.12 is a reasonable default); the authoritative supported list lives in the [ZeroGPU docs](https://huggingface.co/docs/hub/spaces-zerogpu) — do not hardcode the full list, refer to the docs.
|
|
263
|
+
|
|
264
|
+
```yaml
|
|
265
|
+
# README.md frontmatter
|
|
266
|
+
python_version: "3.12"
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Both `"3.12"` and `"3.12.12"` forms are accepted.
|
|
270
|
+
|
|
271
|
+
### Do not pin `spaces` in `requirements.txt`
|
|
272
|
+
|
|
273
|
+
The Space platform pins its own `spaces` version. A conflicting pin in `requirements.txt` causes pip resolution to fail at build time.
|
|
274
|
+
|
|
275
|
+
> **Rule**: Do not include `spaces` in `requirements.txt`.
|
|
276
|
+
|
|
277
|
+
How to achieve this depends on your tooling:
|
|
278
|
+
|
|
279
|
+
- **Hand-written `requirements.txt`**: simply omit `spaces`.
|
|
280
|
+
- **uv** (`pyproject.toml`-managed): declare `spaces` in `pyproject.toml` so uv co-resolves transitive constraints (notably `psutil`, which `spaces` pins), then exclude it from the export:
|
|
281
|
+
```bash
|
|
282
|
+
uv export --no-hashes --no-dev --no-emit-package spaces -o requirements.txt
|
|
283
|
+
```
|
|
284
|
+
Without `spaces` in `pyproject.toml`, uv cannot see its transitive constraints and may resolve incompatible versions at build time.
|
|
285
|
+
- **pip-tools** (`pip-compile`) / **Poetry**: use the equivalent exclude mechanism.
|
|
286
|
+
|
|
287
|
+
### Pin `torch` to match wheel tags
|
|
288
|
+
|
|
289
|
+
If you install a CUDA-dependent wheel via direct URL, the wheel filename encodes the `torch` major.minor it was built against (e.g. `cu12torch2.8`). Pin `torch==X.Y.Z` in `requirements.txt` to match — otherwise pip may resolve `torch` to a different version and the Space fails on first import. Details and the kernels-community alternative are in `references/cuda-and-deps.md`.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# Concurrency Safety
|
|
2
|
+
|
|
3
|
+
Gradio handlers run **in parallel by default on ZeroGPU**. Code that works fine in single-user testing can silently corrupt or leak data in production. Always assume handlers execute concurrently.
|
|
4
|
+
|
|
5
|
+
## No mutable global state
|
|
6
|
+
|
|
7
|
+
Per-request or per-user data must not live in module-level mutable variables. Concurrent requests will overwrite each other.
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
# BAD — concurrent requests overwrite each other
|
|
11
|
+
results = {}
|
|
12
|
+
|
|
13
|
+
def process(text):
|
|
14
|
+
results["output"] = expensive_compute(text) # race condition
|
|
15
|
+
return results["output"]
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
# GOOD — pure function, no shared mutable state
|
|
20
|
+
def process(text):
|
|
21
|
+
return expensive_compute(text)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
For state that must persist within a single user session, use `gr.State`:
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
with gr.Blocks() as demo:
|
|
28
|
+
history = gr.State(value=[])
|
|
29
|
+
|
|
30
|
+
def add_message(msg, hist):
|
|
31
|
+
hist.append(msg)
|
|
32
|
+
return hist, hist
|
|
33
|
+
|
|
34
|
+
btn.click(fn=add_message, inputs=[msg, history], outputs=[chatbot, history])
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Note that on ZeroGPU, `gr.State` is pickled across the worker boundary on every yield — see "Process Isolation and Pickle" in SKILL.md for the implications.
|
|
38
|
+
|
|
39
|
+
## No fixed file paths for outputs
|
|
40
|
+
|
|
41
|
+
Hardcoded output filenames cause concurrent requests to overwrite each other's files. This corrupts outputs and, worse, can leak one user's data to another.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
# BAD — concurrent calls clobber the same file
|
|
45
|
+
def generate_image(prompt):
|
|
46
|
+
image = pipe(prompt).images[0]
|
|
47
|
+
image.save("output.png")
|
|
48
|
+
return "output.png"
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
# GOOD — unique path per invocation
|
|
53
|
+
import tempfile
|
|
54
|
+
|
|
55
|
+
def generate_image(prompt):
|
|
56
|
+
image = pipe(prompt).images[0]
|
|
57
|
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
|
|
58
|
+
image.save(f.name)
|
|
59
|
+
return f.name
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The same applies to any intermediate files (audio, video, CSV exports). Always generate a unique path per invocation.
|
|
63
|
+
|
|
64
|
+
## Read-only globals are safe
|
|
65
|
+
|
|
66
|
+
Model objects, tokenizers, and configs loaded once at startup and only read during requests are safe and encouraged. This is the standard ZeroGPU pattern: load at module scope, read inside `@spaces.GPU` handlers.
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
# SAFE — loaded once at module scope, read-only during requests
|
|
70
|
+
model = load_model().to("cuda")
|
|
71
|
+
tokenizer = load_tokenizer()
|
|
72
|
+
|
|
73
|
+
@spaces.GPU
|
|
74
|
+
def predict(text):
|
|
75
|
+
tokens = tokenizer(text, return_tensors="pt").to("cuda")
|
|
76
|
+
return model.generate(**tokens)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The "no mutable global state" rule targets *writes* from handlers, not reads. A handler that only reads from a global is concurrency-safe.
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# CUDA Dependencies on ZeroGPU
|
|
2
|
+
|
|
3
|
+
Detailed guidance for installing CUDA-dependent packages on ZeroGPU. SKILL.md establishes the bottom line — wheels are the recommended path because the ZeroGPU build phase has no `nvcc`. This document covers wheel filename tag reading, the kernels-community fallback, and torch-family side-car drift.
|
|
4
|
+
|
|
5
|
+
## When no wheel is available on PyPI
|
|
6
|
+
|
|
7
|
+
Common workarounds, in preference order:
|
|
8
|
+
|
|
9
|
+
1. **Pre-built wheel via direct URL.** For `flash-attn`, the upstream project ships a fairly complete matrix at https://github.com/Dao-AILab/flash-attention/releases — check there first and pin the matching wheel URL.
|
|
10
|
+
2. **Build the wheel yourself and host it** (e.g. on a public HF Hub repo) when no upstream wheel matches the Space environment.
|
|
11
|
+
3. **Use a kernels-community kernel** (see below) — handles ABI matching for you, no version pinning needed.
|
|
12
|
+
|
|
13
|
+
## Reading a CUDA wheel filename
|
|
14
|
+
|
|
15
|
+
A wheel filename like
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
flash_attn-2.8.0.post2+cu12torch2.8cxx11abiFALSE-cp312-cp312-linux_x86_64.whl
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
encodes four build-time choices:
|
|
22
|
+
|
|
23
|
+
| Tag | Meaning |
|
|
24
|
+
|-----|---------|
|
|
25
|
+
| `cu12` | CUDA major version |
|
|
26
|
+
| `torch2.8` | torch major.minor the wheel was compiled against |
|
|
27
|
+
| `cxx11abiFALSE` | C++ stdlib ABI choice (`TRUE` or `FALSE`) |
|
|
28
|
+
| `cp312-cp312` | CPython version (3.12) |
|
|
29
|
+
|
|
30
|
+
The wheel's compiled C-extension will `ImportError` on ABI/symbol mismatches if any of these drift at install time.
|
|
31
|
+
|
|
32
|
+
If you hand pip a wheel URL without pinning the surrounding environment, pip may resolve `torch` to a version different from the wheel's build target, and the Space will fail on first import. Therefore:
|
|
33
|
+
|
|
34
|
+
- Pin `torch==X.Y.Z` in `requirements.txt` to match the wheel's `torch2.X` tag.
|
|
35
|
+
- Set `python_version:` in the Space frontmatter to match the `cp3XX` tag.
|
|
36
|
+
- Check the runtime's cxx11-ABI choice against the wheel; if unsure, try the opposite ABI wheel.
|
|
37
|
+
|
|
38
|
+
## Prefer kernels-community when unsure
|
|
39
|
+
|
|
40
|
+
If you are not sure about the ZeroGPU runtime's torch / Python / ABI combination, prefer a [kernels-community](https://huggingface.co/kernels-community) kernel (e.g. `kernels-community/flash-attn2`) instead of a raw wheel URL. The kernels runtime handles ABI matching on your behalf, so no version pinning is required in your Space.
|
|
41
|
+
|
|
42
|
+
## torch-family side-car drift
|
|
43
|
+
|
|
44
|
+
`torchvision`, `torchaudio`, `torchcodec`, and similar side-car packages are built against a specific `torch` major.minor (and CUDA major). On ZeroGPU, the runtime's supported `torch` list lags behind PyPI, so projects often pin a non-latest `torch` — and a bare `uv add <side-car>` can silently resolve to a newer release that targets a different `torch` / CUDA, producing ABI/import failures even though `uv lock` succeeded without warnings.
|
|
45
|
+
|
|
46
|
+
Concretely observed (2026-04) with `torch==2.9.1` pinned:
|
|
47
|
+
|
|
48
|
+
- `torchaudio` resolves to `2.11.0`, which targets torch 2.11 / CUDA 13. The `2.11.0` release **dropped the `Requires-Dist: torch==X.Y.Z` line** that every earlier release had, so uv sees no constraint and picks it.
|
|
49
|
+
- `torchcodec` resolves to a release targeting torch 2.11. No torchcodec release on PyPI declares a `torch` dependency at all; the compatibility table lives only in the project README.
|
|
50
|
+
- `torchvision` happens to resolve correctly because torchvision still declares `Requires-Dist: torch==X.Y.Z`. Which side-cars are affected changes over time — treat every torch-family package as suspect, not just these.
|
|
51
|
+
|
|
52
|
+
### Verify at add/upgrade time
|
|
53
|
+
|
|
54
|
+
After any `uv add <torch-side-car>` or `uv lock --upgrade`, verify the resolved version targets the same `torch` major.minor as pinned. Two-step fallback because PyPI metadata is not always sufficient:
|
|
55
|
+
|
|
56
|
+
1. Query PyPI for the resolved version's `requires_dist`:
|
|
57
|
+
```bash
|
|
58
|
+
curl -s https://pypi.org/pypi/<pkg>/<version>/json \
|
|
59
|
+
| python3 -c "import json,sys,re; rd=json.load(sys.stdin)['info'].get('requires_dist') or []; print('\n'.join(x for x in rd if re.match(r'^torch(?![a-z])', x)) or '(no torch constraint declared)')"
|
|
60
|
+
```
|
|
61
|
+
If a `torch==X.Y.Z` line appears and matches the pinned torch, good. If it appears and does NOT match, the side-car is wrong — pin it down explicitly.
|
|
62
|
+
2. If the query prints `(no torch constraint declared)`, PyPI metadata is silent and cannot be trusted. Fall back to the project's own compatibility table (GitHub README / docs site) — torchcodec, for example, maintains one at https://github.com/pytorch/torchcodec. Pick the side-car version the table maps to the pinned torch major.minor, and pin it explicitly.
|
|
63
|
+
|
|
64
|
+
### Preventive pin
|
|
65
|
+
|
|
66
|
+
Once the correct side-car version is known, pin it in `pyproject.toml` alongside torch so uv cannot drift on future `uv lock --upgrade`. The side-car version numbers for a given torch major.minor change each release; always re-verify, do not copy a mapping from an older project.
|