# AGENTS.md ## What this is A Hugging Face **ZeroGPU Space** — the denoising half of a two-Space MiniMax-H3 deployment (video + soundtrack, unquantized bf16). Gradio 6.20.0 app, entrypoint `app.py`. The other half, `multimodalart/qwen3vl-conditioner` (62 GiB Qwen3-VL), is called over the gradio API on every request. The pipeline is split in `h3_split_blocks.py`: `MiniMaxH3GeneratorBlocks` subclasses diffusers' `SequentialPipelineBlocks` with the `text_encoder` step removed. The entire wire format between the halves is two tensors — `prompt_embeds` `(1, num_text_tokens, 5120)` bf16 + `text_token_tags` int64 — carried as one safetensors file with `height`/`width`/`num_frames` in its metadata. ## Critical rules - **`import spaces` must precede anything that initializes CUDA** (first import in `app.py`; it patches `torch.cuda` so the 77.3 GB load happens at startup on CPU). Importing torch first silently breaks placement. - **`diffusers` is not from PyPI.** It installs from `refs/pull/14371/head` of huggingface/diffusers, pinned to commit `665f5782` (see `requirements.txt`). The PR is WIP and moves: when re-pinning, re-check `h3_split_blocks.py` against the new head's block class names, and update the pin and the comment together. - **Canvas labels are a cross-Space contract.** `CANVASES` keys in `app.py` go over the wire by label and must stay identical to the conditioner's table — an unknown label is rejected there. Adding a canvas means editing both Spaces. - **This half cannot run standalone** (no conditioner → no request) and **nothing here can be tested end-to-end offline**: every generate calls the live conditioner Space. - Changing the wire format, canvas table, or frame-count arithmetic breaks the split — coordinate with the conditioner Space. ## Non-obvious constraints - Frames are snapped to `17 * n + 5` at 24 fps (`snap_frames`). UI duration is 2–14 s because 15 s rounds to 362 frames, which the checkpoint refuses. - **Autoencoders must stay float32** (`_keep_in_fp32_modules`): a bf16 audio VAE decodes the soundtrack ~20 dB too quiet. `load_components(dtype=torch.bfloat16)` is for the transformer only. - `H3_PLACEMENT` default is **`pack`** in code (pack the transformer at startup; the ~10 GB fp32 VAEs move on the first GPU call). `lazy` moves all 72 GiB on the first GPU call; `offload` needs `_arm_decode_hooks` or the VAE decodes never offload. The README's env table says `lazy` — the code is authoritative. - `@spaces.GPU(duration=get_duration, ...)`: the duration estimate must keep covering the request (linear + quadratic in latent rows) or the call is evicted. If you raise steps or canvas sizes, re-check `_DUR_B`/`_DUR_C`. - `_generate` returns only the three outputs because a `@spaces.GPU` return crosses a process boundary by pickling; the pipeline state stays on the card. - `upsample` is deliberately the **last** positional arg of `generate` so positional API clients that predate it are unaffected — keep it last. - Attention backend default `_native_cudnn`; flash-attention 3 is sm90-only and this pool is sm120 — don't switch without measuring. - **LoRA bucket cache**: every downloaded LoRA (turbo, NSFW, custom) is copied to the mounted bucket at `/data/loras` (`_fetch_lora_file`), so a restart loads it from the bucket instead of re-downloading. Falls back to the HF cache when the bucket isn't mounted or a write fails; a corrupt cached file is deleted and re-downloaded. `H3_LORA_CACHE_DIR` overrides the path (tests use it). The bucket (`observantdistressed/minimax-h3-storage`) is mounted read-write at `/data` — deleting it breaks the cache, not the Space. - **Debug logging**: `_log(msg, level)` prints timestamped `[gen][HH:MM:SS][LEVEL]` lines to stdout (the Space logs). `generate` logs the full request on entry and a full traceback on failure; `_generate`/`encode_remote`/`get_duration`/LoRA load+merge log timings. Keep `flush=True` — log lines must not buffer. ## Dependency pins (all deliberate) - `torch==2.11.0` (cu130 wheel index); bumping breaks the AoTI key match (silent fallback to eager). - `transformers==5.8.0` — "a different minor changes the conditioning": the Qwen3-VL processor decides the vision patch count. - `huggingface-hub==1.24.0` because diffusers pins `<2`. - No `kernels` pin on purpose: `kernels>=0.12.3` breaks transformers 5.8.0 at import. Do not add one. - `gradio==6.20.0` must match `sdk_version` in the README frontmatter (the Space config). ## AoTI (`h3_aoti.py`) - `maybe_load` is the runtime path: off unless `H3_AOTI=1`, and only for the exact key `bf16/torch2.11/sm120/dynamic`; any mismatch falls back to eager. **A mismatched compiled package segfaults rather than raising** — hence the strict key check. `H3_AOTI_TEMB_ROWS` (default 4) must match the published package. - `export_block` / `compile_and_save` / `upload` are the **build path** for the separate `multimodalart/minimax-h3-aoti` repo: requires a same-arch GPU and `HF_TOKEN`, runs on GPU time, and the Space itself never calls it. - `spaces_constant_binding_patch.py` patches `spaces`' AoTI loader so anonymously-lifted constants bind instead of segfaulting; keep it importable (missing is tolerated with a warning). ## Layout - `app.py` — Gradio UI + request flow (`generate` → remote `/encode` → `@spaces.GPU _generate` → `encode_video` mux). `load_models()` runs at import; a syntax/import error kills the whole Space at startup. - `h3_split_blocks.py` — the split block classes for both partitions (`t2va` and `ref2va`) and both halves. - `h3_aoti.py` — AoTI runtime patch + export/compile/upload build path. - `spaces_constant_binding_patch.py` — AoTI constant-binding patch (compile side + load side). - `packages.txt` (`ffmpeg`) — ZeroGPU apt packages, Space-level, not pip. `examples/` holds keyframe images for `gr.Examples`. ## Repository Map A full codemap is available at `codemap.md` in the project root. Before working on any task, read `codemap.md` to understand: - Project architecture and entry points - Directory responsibilities and design patterns - Data flow and integration points between modules For deep work on a specific folder, also read that folder's `codemap.md`. ## Verification No tests, lint, or CI in this repo. Local sanity check: ``` python -m py_compile app.py h3_aoti.py h3_split_blocks.py spaces_constant_binding_patch.py ``` Full verification is running the Space itself — 77.3 GB startup download plus a real generation against the live conditioner — treat that as an expensive manual gate, not a routine step. ## Pushing to the Space - **Do not push after every implementation.** Every push restarts the Space and re-runs the 77.3 GB startup load, so pushes are expensive. Batch related changes into one push. - **Judge when a push is necessary yourself.** Push when: the user explicitly asks for it, a fix must reach the live Space, or a change is complete, verified, and user-visible. Do not push for intermediate steps, local-only work, doc-only edits, or changes that can safely wait to be batched with the next push. - A passing local sanity check (see Verification) is necessary but not sufficient — it never requires a push by itself. - Push with `HF_TOKEN=... python push.py ""`. The token is a live secret — never print it, and rotate it if it ever leaks. ## Cloned Dependency Source Read-only dependency source repositories are available under `.slim/clonedeps/repos/` for inspection. Do not edit these clones. - `.slim/clonedeps/repos/huggingface__diffusers/` — huggingface/diffusers at the exact pinned commit `665f5782` (sparse-checked to `src/diffusers/modular_pipelines/`); the `SequentialPipelineBlocks` + MiniMax-H3 block classes `h3_split_blocks.py` subclasses and `h3_aoti.py` exports. - `.slim/clonedeps/repos/multimodalart__qwen3vl-conditioner/` — the sibling conditioner Space at `main`; the `CANVASES`/wire-format contract this Space must match, plus the `h3_core` / `prompt_rewrite` modules this repo references.