Repository navigation
Studio H3-Image: prompt cache, pinned streaming and the H3 attention levers - #17495
Conversation
The H3-Image pipeline names its encoder entry point encode_prompt, so the shared in-memory prompt cache wraps it, and the H3-Image backend load installs it like every other load. A repeated prompt (new seed, batch) with the same reference pixels reuses the Qwen3-VL conditioning; the VAE reference latents are still sampled per render. UNSLOTH_DIFFUSION_PROMPT_CACHE=0 turns it off. A test asserts that every backend method that commits a load installs the cache.
… prefetch The streamed DiT blocks and encoder layers moved from pageable host memory with .to(non_blocking=True) on the compute stream, which is a synchronous copy. A shared streamer for custom loaders (diffusion_offload_prefetch.stream_module_list) now gives each streamed member a diffusers ModuleGroup with slab-packed pinned host copies on its own copy stream and drives them with the existing GroupPrefetcher: one member copies while the previous one runs, fenced by events, and a forward that stops part way (the encoder read at layer 50) still releases what it queued. Buffers go back to their host copies too (the int8 encoder keeps its weights as buffers). Pinning is budgeted twice and falls back to the pageable streamer when either does not hold: the new locked copies must fit the free host RAM (less max(4 GiB, 15%)), and H3-Image counts them on top of what its plan already holds on the host (host-side DiT blocks, the encoder, 4 GB), so a host the plan fits still fits with every pin. The streamed DiT, placed before the encoder loads, takes that room first. The planner keeps device room for the prefetched member; the low-host tier, which loads the encoder per prompt, keeps its encoder layers pageable. Kill switches: UNSLOTH_H3_IMAGE_PINNED_STREAM=0 (H3-Image) and UNSLOTH_DIFFUSION_ASYNC_PREFETCH=0 (every prefetcher). Per-render streamer counters are in the render stats.
…ored DiT The H3 attention levers now gate on module structure (attention forward and processor signatures, per-head RMSNorm q/k, to_out, separate or fused QKV, a processor module with _apply_rotary_emb) instead of diffusers' MiniMaxH3 classes, and the strided processor is built once per stock base processor, so the vendored MiniMax-H3-Image attention takes them unchanged. Video keeps the same modules and the same class. install_h3_image_speed runs once after placement: on the resident tiers the fused int8 QKV (through the row pads), Studio's int8 GEMM (its Linears drop the row pad) and the fused SwiGLU act quant; on every CUDA tier the automatic attention pick (flash on sm80 / sm89), the strided SDPA layout and the fused q/k norm + RoPE. Regional compile of the blocks is opt-in (UNSLOTH_H3_IMAGE_COMPILE=1). UNSLOTH_H3_IMAGE_SPEED=0 keeps everything stock; every lever also honours its video switch. The engaged levers are on the pipe and in the load report.
…eclares MiniMax-H3-Image's INT8 DiT checkpoint runs INT8 attention on its 50 DiT blocks. A shared map in diffusion_attention (checkpoint_attention_backend) turns a declared attention kind into the Studio backend of the same arithmetic class: INT8 attention is the existing probe-gated sage backend. H3-Image routes its DiT blocks (not the token refiner) to sage when the DiT scheme is int8, or when a hosted file declares attention in its metadata. Sage must pass its accuracy probe on the card, else every processor keeps the backend it had. UNSLOTH_H3_IMAGE_INT8_ATTENTION=0 keeps native attention, =1 turns it on for any scheme.
It is the one non-exact lever-4 part on the streamed tier, and the 6-step sampler carries its last-bit difference into a different image. On the L4 FP8 streamed tier it landed further from the bf16 reference on both gated prompts, while on the A100 INT8 resident tier the full set (with the fused SwiGLU) held the reference. Each tier now ships the set that held its gate: on for the resident tiers, off for the streamed one. UNSLOTH_H3_IMAGE_QK_ROPE=1 / 0 forces it either way; the video default is unchanged.
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3d7c51c748
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| from .diffusion_memory import _pinned_memory_capped | ||
|
|
||
| if _pinned_memory_capped(): | ||
| return "pinned host memory is capped on this OS" | ||
| return None |
There was a problem hiding this comment.
Honor the global host-pinning opt-out in the new streamer
On CUDA hosts with UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN=0, this refusal check still permits the pinned streamer. Unlike _streamed_pin_plan and _pin_top_level_group in diffusion_memory.py, it never checks that override, and stream_module_list subsequently creates persistent pinned copies through ModuleGroup and the pinned arena. Loading H3-Image can therefore lock many gigabytes of host memory despite the user's explicit opt-out, whereas its previous pageable streamer did not. Check the global pinning override here and fall back to ModuleListStreamer when it is disabled.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c95475c: the refusal check now returns early when UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN is 0 / off / false / no, so the pageable streamer is kept; a test covers it.
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…rmers (unslothai#17576) ## Summary When a diffusion load picks a gated attention backend that needs the Hugging Face `kernels` package (`sage`, `_flash_3_hub`, `flash_4_hub`, and since unslothai#17495 an INT8 MiniMax-H3-Image DiT routes to `sage` on its own), Studio installs `kernels` on demand with no version. pip takes the newest release (0.18.2 today). With Studio's pinned transformers 5.5.0 that breaks the next process: transformers before 5.13 builds `kernels.LayerRepository` objects with neither a revision nor a version while `transformers.integrations.hub_kernels` imports, and kernels 0.15 and newer reject that: ``` ValueError: Either a revision or a version must be specified. ``` The process that installed it keeps working, but every later Studio start fails `from diffusers import DiffusionPipeline` for every image model until `kernels` is removed by hand. The Studio installer already ships `kernels==0.12.3`, so the on-demand install runs where `kernels` is missing: environments set up without the installer's extras step, or where that step was skipped or failed. This PR: 1. **Pins the on-demand install to the installed transformers.** Next to transformers < 5.13 it installs `kernels==0.12.3`. From 5.13 on (the first release whose hub_kernels mapping passes `version=` to every `LayerRepository`) it installs `kernels>=0.12.3`. 0.12.3 is the release the Studio installer already ships (`requirements/extras-no-deps.txt`) and the floor `flash_4_hub` requires. The pin is exact rather than `<0.15` because the install uses `--no-deps`, and kernels 0.14.0 to 0.16.x import a separate `kernels-data` package that would be left out, so the install could not be imported. huggingface_hub < 1.10 also gets 0.12.3. 2. **Checks the install before keeping it.** After pip, `import transformers.activations` runs in a fresh interpreter. If it fails, the install is rolled back (uninstalled, or the previous version reinstalled) and `kernels` is hidden from this process, so the load falls back to the default attention backend with a warning that says why. 3. **Self-heals installs an older Studio already broke.** Before diffusers is imported (`close_dynamo_import_window` and the background media import window), a once-per-process check reads the `kernels` and `transformers` versions from package metadata. Only when they predict the conflict does it run the import check in a subprocess, and only when that fails with this exact `ValueError` does it reinstall `kernels` at the right spec. If installs are turned off (`UNSLOTH_DIFFUSION_ATTENTION_INSTALL=0`), the repair fails, or `kernels` was already imported in this process, it hides `kernels` from this process instead. transformers' hub_kernels catches the resulting `ImportError` and imports without hub kernels, and the log gives the one-line pip command that fixes it. A healthy install costs two metadata reads. There are no UI or flow changes. The FA4 dependency upgrade (`kernels==0.12.3`) is unchanged and already below the ceiling. ## How the transformers boundary was found I fetched `transformers/integrations/hub_kernels.py` for each release from 5.5.0 to 5.17.0. In 5.12.1 the mapping still builds `LayerRepository(repo_id=..., layer_name=...)` without a version. In 5.13.0 every entry passes `version=1`. Real imports in a CPU venv (dependencies installed, so `kernels-data` is present for 0.14.x): | transformers | kernels | `import transformers.activations` | |---|---|---| | 5.5.0 | 0.12.3 | OK | | 5.5.0 | 0.14.1 | OK | | 5.5.0 | 0.18.2 | ValueError | | 5.12.1 | 0.14.1 | OK | | 5.12.1 | 0.15.1 | ValueError | | 5.13.0 | 0.15.1 | OK | | 5.13.0 | 0.18.2 | OK | | 5.17.0 | 0.14.1 | OK | | 5.17.0 | 0.18.2 | OK | ## GPU evidence (Colab L4, transformers 5.5.0, diffusers 0.42.1) Base is the merge base `d6841bbe96`. Head is this branch. Colab L4 (sm89), torch 2.14.1+cu130, Python 3.13, transformers 5.5.0, diffusers 0.42.1, huggingface_hub 1.33.0. Each arm starts with `kernels` uninstalled and runs the real MiniMax-H3-Image INT8 trigger, `install_checkpoint_attention(pipe, "cuda", scheme="int8")` from `diffusion_minimax_h3_image.py`, which routes the DiT blocks to `sage` and goes through the on-demand install. The full checkpoint is 204 GB, so the DiT is a tiny random `FluxTransformer2DModel` (bf16, CUDA) instead. Each arm then runs a forward pass and imports diffusers in a new process. | Step | Base | Head | |---|---|---| | kernels installed on demand | 0.18.2 (unpinned) | 0.12.3 (`kernels==0.12.3`) | | sage backend in the installing process | `sage_hub` engaged, probe passed (`INT8 attention (sage_hub) on 1 DiT blocks`) | falls back to the default backend: the 0.12.3 hub loader cannot install the current `kernels-community/sage-attention` build for this torch (`FileNotFoundError`), logged | | forward pass | finite | finite | | NEW process `from diffusers import DiffusionPipeline` | **fails**: `ValueError: Either a revision or a version must be specified.` | **imports** | Self-heal, starting from the broken state base left behind (kernels 0.18.2 with transformers 5.5.0): | Case | Result | |---|---| | Head, installs allowed: `close_dynamo_import_window` and then a diffusers import in the same process | imports. Logged `kernels 0.18.2 cannot be imported by transformers 5.5.0; reinstalled kernels==0.12.3 (now 0.12.3)`. The next process imports too. | | Head, `UNSLOTH_DIFFUSION_ATTENTION_INSTALL=0` | imports. kernels stays 0.18.2 and is hidden for that process, with a log line giving the pip command that repairs it. | Which kernels release can load the sage hub build here and still keep transformers 5.5.0 importable (same L4, each release installed with its dependencies): | kernels | Studio sage hub load | `import transformers.activations` on 5.5.0 | |---|---|---| | 0.12.3 | no (`FileNotFoundError` for the build) | OK | | 0.13.0, 0.14.0 | no (`Illegal header value` in the user agent) | OK | | 0.14.1 | no (publisher trust check) | OK | | 0.15.1, 0.16.2, 0.17.3 | no (publisher trust check) | ValueError | | 0.18.2 | yes, probe passed | ValueError | On this stack no kernels release does both. Next to transformers < 5.13, the hub sage backend therefore falls back to the default backend instead of breaking every later start. On transformers >= 5.13 the install is unchanged in practice (`kernels>=0.12.3` resolves to the newest release). ## Tests - New `tests/test_kernels_compat.py` (CPU, no network, 30 tests): spec selection per transformers version (including pre-releases, an unknown version, and an old hub), conflict prediction against the measured matrix, the on-demand install passing the pinned spec and then running the import check, rollback (uninstall, or reinstall of the previous version) plus hiding when the check fails, keeping the install when the check cannot run, and every self-heal branch: metadata only with no conflict, repair, hide with installs off, hide when `kernels` is already imported, and leaving a working pair alone. It also checks that the hook runs in both diffusers import windows. One test uses the real transformers: a stand-in `kernels` that raises this exact `ValueError` breaks `import transformers.activations`, and after `hide_kernels()` the import succeeds. It passes on transformers 5.5.0 and 5.17.0. - Updated the existing install tests that expected the bare `kernels` argument and a single subprocess call. - `tests/test_diffusion_attention.py`, `tests/test_diffusion_attention_install.py`, `tests/test_diffusion_attention_rocm_flash.py`, and the torch_warmup / diffusers prewarm tests pass. The one failure, `test_an_imported_old_kernels_is_not_papered_over` (it expects "after Studio restarts" but the message says "after Unsloth restarts"), also fails on `main`. ## Not covered - Other transformers import paths outside the diffusers import windows (for example a text model load in a process that never imports diffusers) are not repaired here. They get repaired the next time an image load runs in that environment. - A repair inside a process that has already imported `kernels` only applies after a restart. That process runs without hub kernels. - With Studio's transformers 5.5.0, the hub sage / FA3 / FA4 backends do not engage after this change on the stack tested above (torch 2.14.1, cu130). They fall back to the default backend. Getting them to engage on transformers < 5.13 needs a transformers bump to 5.13 or later, which this PR does not do. Older torch builds with kernels 0.12.3 were not tested. - Windows, macOS and ROCm were not run. The change is pip plus import logic with no platform branches.
Summary
Follow-up to #17453 (MiniMax-H3-Image, merged). Four speed levers for MiniMax-H3-Image, one commit each, each with its own switch. Where a mechanism is not specific to H3-Image it is added as a shared helper.
Studio H3-Image: conditioning cache for repeated prompts)encode_prompt, so the shared in-memory prompt cache (diffusion_prompt_cache) wraps it. The H3-Image backend load installs the cache like every other load does._LoadState) installs the cache.UNSLOTH_DIFFUSION_PROMPT_CACHE=0.... stream blocks through pinned memory with copy-stream prefetch).to(non_blocking=True)on the compute stream. A pageable copy is synchronous, so the compute waited for every copy.diffusion_offload_prefetch.stream_module_list. It gives each streamed member a diffusersModuleGroupwhose host copies are pinned and packed into slabs, on its own copy stream, and drives the groups with the existingGroupPrefetcher: the next member copies while the current one runs, fenced by events.UNSLOTH_H3_IMAGE_PINNED_STREAM=0for H3-Image,UNSLOTH_DIFFUSION_ASYNC_PREFETCH=0for every prefetcher.... engage the MiniMax-H3 video speed levers on the vendored DiT)to_out, and separate or fused QKV. The strided processor is built once per stock processor class, so the vendored H3-Image attention takes the levers unchanged. Video matches the same modules with the same class.UNSLOTH_H3_IMAGE_QK_ROPE=1/0forces it on or off on any tier.UNSLOTH_H3_IMAGE_COMPILE=1).UNSLOTH_H3_IMAGE_SPEED=0. Each lever also honours its video switch.... INT8 attention on the DiT blocks as the checkpoint declares)diffusion_attention(checkpoint_attention_backend) turns a declared attention kind into the Studio backend of the same arithmetic class; for INT8 attention that is the existing probe-gatedsagebackend.attentionin its metadata. The token refiner keeps its backend.UNSLOTH_H3_IMAGE_INT8_ATTENTION=0keeps native attention,=1turns INT8 attention on for any scheme.Results
2048x2048, 6 steps, fixed seeds, base (#17453 on main) and head arms on the same Colab VM per tier, a second base and head pair (A2 / H2) as the A/A check. Seconds per image after the first (warm) render, split into encode / denoise / decode. LPIPS (alex, 512 px) is against bf16 renders of the same prompt and seed.
A100 40GB, INT8 DiT resident (
dit_resident)LPIPS vs bf16 (lighthouse s7 / bookshop s1234 / island s2026): base 0.034 / 0.276 / 0.064, head 0.036 / 0.278 / 0.063.
L4 24GB, FP8 DiT streamed (
stream)With the fused q/k norm + RoPE off, the L4 head images are byte-identical to base. With it on, LPIPS vs bf16 was 0.491 / 0.147 against base 0.415 / 0.092 on bookshop s1234 / island s2026.
Per lever
UNSLOTH_H3_IMAGE_PINNED_STREAM=0on both cardsHost memory. Locked copies are made only when they fit two budgets: the host room the planner leaves after its own peak (
host_gb - host_need_gb, less what is already locked, DiT first), and the free host RAM less max(4 GiB, 15%). Anything that does not fit streams from pageable memory as before. On the 86 GB A100 VM the room is about 55 GB, so the encoder locks and the load peak rises from 22 to 46 GB. On the 54 GB L4 VM the room is about 14 GB, so only the DiT blocks lock (9.2 GB) and the peak rises from 24.9 to 30.3 GB. A 40 GB host locks nothing and loads as before.Tests
tests/test_diffusion_list_streamer.py: prefetching streamer bit-identity and no device memory left after the forward (CUDA), buffers restored to their host copies, refusal when a stream exceeds the pin budget, the plan room cap, and a 40 GB host that loads with every member pageable.tests/test_diffusion_minimax_h3_image.py: prompt cache hits and keys, every loader installs the cache, INT8 attention routing and restore.tests/test_diffusion_minimax_h3_image_speed.py: structural H3 attention match, strided processor bit-identical to stock, fused int8 QKV bit-identical, kill switches, the per-tier q/k norm + RoPE default.Not covered