Repository navigation
Studio diffusion: single-card CFG batching for a DiT streamed from host memory - #13787
Merged
Merged
Conversation
Text encoders and VAE move to a second card when that keeps the denoiser resident on the first, a two-expert denoiser can keep one expert per card, and guidance branches run on a denoiser replica on the second card (CFG-parallel). Placement happens at the component and denoiser-call boundaries, needs no NCCL, and falls back to one card. UNSLOTH_DIFFUSION_MULTIGPU=0 and UNSLOTH_DIFFUSION_CFG_PARALLEL=0 turn it off.
…tay with the denoiser
…weights or adapters change
… hooks on the source
…d holds its weights resident
… before the primary branch
…ps do not defeat the overlap
…ails A failed split fell back to whole-module offload unconditionally, which a torchao denoiser cannot take. The split plan now carries the plan one card would have used and applies it on the primary.
A hook function is shared by the source denoiser and its replica, so a captured list, dict, set, tensor or object is state both branches mutate concurrently. Only immutable captures are accepted now.
…lel replica A step cache installed on the source at generate time left the replica running uncached for the odd branches. The per-step staleness check now also declines when the source gained hooks a replica cannot share.
…d plan after load The post-load fit can use the tiled decode headroom, so clearing VAE tiling could let an untiled decode exceed what either card was budgeted for.
…ride of its source The router took the root forward slot, so the copy fell back to the class forward while the primary branch kept a bound override. The override is now rebound to the replica (offload wrappers are peeled off), and anything else declines.
…s offload wrappers off the root forward
…ting the result A tensor edited in place after the prediction was launched kept its identity, so the stale replica output was accepted. The launch-time copies are now compared with the sources at the real call (one sync); any difference recomputes the branch.
…ed profile mutates the denoiser
…a per call Root hooks run only on the source and can write per-call state onto its submodules (the HunyuanVideo-1.5 null-mask flag). That _unsloth_* scalar state is now copied to the replica before each replica call, and a predicted branch is accepted only when the source state for the real call matches what the replica saw.
A split reports offload policy none while its fit priced only the base pipeline, so a ControlNet added at generate time loaded whole onto the primary. It now streams as it would under the single-card offload plan.
… too With the VAE split onto another card the guard only read the primary's free memory, so a larger decode could be admitted there and run out of memory on the secondary. The guard now also checks the VAE's card, tiling or refusing on that card's figure.
… the primary out of the split The load dtype and device-specific patches are resolved for the primary card (bf16 from Ampere, FP8 kernels from Ada), so a pre-Ampere secondary could be handed a bf16 text encoder or VAE it cannot run. make_selection now drops any secondary whose compute capability is below the primary's; an unreadable capability keeps the old behaviour.
… primary The replica walker moves tensors inside plain tuples, lists and dicts only. A prefix-KV cache object (Qwen-Image-2.1, FLUX.2) reached the replica with its tensors still on the primary, and a mutable cache was written from both threads. Such a branch now runs on the primary in turn, without building a replica; plain arguments still route to it.
A split plan reports no offload policy, so the offload floor was None and the generate-time VRAM guard was skipped, where the offloading plan it replaced would have been checked. The load now records each card's resident weights and which card runs the VAE decode, and the guard checks every card: weights plus base headroom, and the decoded-clip share on the decode card.
…rd (diffusion_cfg_batch)
…estore what the router and boundaries replaced - the replica fingerprint covers registered buffers (packed NVFP4 weights and scales) and PEFT's _active_adapter - the replica shares the source's NVFP4 step controller, so both branches of a step run the same GEMM - a root hook from outside Studio declines the replica (its per-call state cannot be mirrored) - an unpredicted replica call copies its inputs after the primary branch instead of reusing the prefetch - the replica's compiled blocks get their own compile guard and the block-0 restride, like the source's - the router runs on the source during a forced-eager render and on the background compile thread - an uninstalled router left inside a wrapper is a passthrough; removal restores instance forward overrides - unload uninstalls the router; begin_load resolves several cards only when multi-GPU is on [skip ci]
…ule on the current multi-GPU base Replaces this branch's content with the rework: diffusion_cfg_batch.py with its own UNSLOTH_DIFFUSION_CFG_BATCH switch, no device or link probing, the Qwen-Image / Z-Image / device sync / timer / kill switch fixes, and the current studio-diffusion-multigpu head merged in. [skip ci]
…all, re-screen step caches per render, clear transient verdicts, drop a template on a shape change [skip ci]
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
danielhanchen
added a commit
that referenced
this pull request
Oct 21, 2026
… in the CFG routers, and test fixes (#14420) ## Summary Follow-up fixes for the recently merged Studio diffusion work: two runtime fixes (the VAE OOM ladder under a multi-GPU component split, and bitwise comparison of expanded timesteps in the CFG routers) and five test fixes. Each change is its own commit. ### 1. VAE OOM step (a) frees only what sits on the VAE's card (#13802 with #13725) **What was broken.** Under a component split the VAE decodes on a secondary card while the denoiser stays resident on the primary. When that decode ran out of memory, `DecodeSession.free_others` reset the denoiser's CUDA graphs on the primary card and counted that as "released". The ladder then retried the same untiled decode on the secondary card, which ran out of memory again before it reached the tiled rung, and the denoiser lost its captured graphs for nothing. `_release_groups` had the same problem with resident offload groups on the primary card. A failed re-pin was also deferred against the VAE's card instead of the groups' own card. **Fix.** Graph handles are filtered to the VAE's card, using the card the graph was recorded on (or its module's card when nothing has been recorded yet). Resident-group modules are filtered by `_unsloth_resident_device`. This is the same filtering `_hook_torchao_resident` and `_move_components` already do with `_placement(comp, self.device)`. `release_resident_groups` takes an optional `device` filter. It is only passed when the pipeline has resident groups on more than one card, so single-card calls are unchanged. Anything whose card cannot be read is still freed, as before. **Tests** (`test_diffusion_vae_oom.py`, all fail on main): - `test_split_vae_oom_leaves_the_other_cards_graphs_alone`: a decode on cuda:1 with graphs on cuda:0 goes straight from the untiled decode to the tiled one, and no graph is reset. - `test_split_vae_oom_still_drops_graphs_on_its_own_card`: only the cuda:1 handle is reset. - `test_split_vae_oom_releases_only_groups_on_its_own_card`: groups on cuda:0 are left alone and nothing is deferred against them. With groups on both cards, the release is limited to cuda:1. - `test_release_resident_groups_device_filter`: the new filter releases only the matching card's groups, and with no filter every card's groups are released. ### 2. Expanded scalars compare bitwise in the CFG routers (#13725, #13787) **What was broken.** `_bitwise_equal` in `diffusion_multigpu.py` flattens both tensors, calls `contiguous()` and views them as `uint8`. WanPipeline passes `timestep = t.expand(batch)`. For a one-element tensor `contiguous()` is a no-op whatever the stride, so the stride-0 timestep reached `view(torch.uint8)`, which raised, and the comparison returned False for two equal timesteps. #13787 CFG batching uses it through `_record_template`, `_matches` and the branch merge. On Wan it missed three times in a row and turned itself off. CFG-parallel's prediction check uses the same helper. **Fix.** A small `_as_bytes` helper takes a dense copy only when the flattened tensor still has a non-unit stride. `_bitwise_equal` and `_unchanged_since_launch` both use it. Bitwise semantics are unchanged: equal NaN bits match, and -0.0 and 0.0 do not. The CFG batcher's three call sites all go through `_bitwise_equal`, so they are covered by the same fix. **Tests** (both fail on main): - `test_bitwise_equal_on_an_expanded_scalar` (`test_diffusion_multigpu.py`): `torch.tensor(941).expand(1)` against a clone and a fresh expand, plus NaN, signed zero and `_unchanged_since_launch`. - `test_wan_expanded_timesteps_serve_the_second_branch` (`test_diffusion_cfg_batch.py`): a Wan-style loop that passes `t.expand(batch)` to each branch. It matches the two-call reference with 4 hits, 0 misses, and batching stays on. On main it gets 0 hits. ### 3. Seeded denoiser cancel test pins the text encoder (#13715) **What was broken.** On a CUDA host, an unset `text_encoder_quant` also plans the hosted FP8 Wan text encoder. The load then fetched two artifacts and `test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event` failed its exact single-fetch assertion. It passed only with the GPU hidden. **Fix.** The test passes `text_encoder_quant = "off"`, so it checks only what it is about: the denoiser fetch carries the load's cancel event. **Test.** Fails on main with a GPU visible and passes after. It passes both ways with the GPU hidden. ### 4. FLUX.2 FBCache test invalidates the child registry cache (#14401) **What was broken.** On diffusers 0.39 and 0.40, `enable_cache` does not drop the child-registry list that an earlier uncached render cached. `test_fbcache_on_flux2_skips_and_matches_the_full_pass` then failed with `ValueError: No context is set`. Production already calls `_invalidate_child_registry_cache` after `enable_cache` in `apply_step_cache`. Only the test helper skipped it. diffusers 0.41 invalidates the list itself. **Fix.** The test's `_render` helper calls `dc._invalidate_child_registry_cache(model)` after `enable_cache`. **Test.** With diffusers 0.39.0 the test failed before and the whole file passes after (7 passed). It also passes on the pinned diffusers. ### 5. Stream encode tests skip when diffusers cannot import the Wan VAE (#14405) **What was broken.** `pytest.importorskip("diffusers")` succeeds on the lazy top-level module. The next line, `from diffusers import AutoencoderKLWan`, can then raise `RuntimeError` (for example with a broken bitsandbytes), which aborted collection of the whole pytest run. **Fix.** Catch `ImportError` and `RuntimeError` on those imports and skip the module, as the other diffusion tests do. **Test.** In an environment with a broken bitsandbytes, collection errored before and the module is skipped after. In the Studio environment all 9 tests still run and pass. ### 6. Multi-GPU planner tests pin the host facts they read (#13725, #13793) **What was broken.** On a host with one GPU, 11 tests in `test_diffusion_multigpu.py` failed. `make_selection` drops ordinals at or above the real `torch.cuda.device_count()` and cards below the primary's capability, so `make_selection(0, [0, 1])` returned None on a one-card machine. An AMD Strix Halo CI runner (one integrated gfx1151) showed exactly these 11. `test_diffusion_fp8_unit_scale.py` gated on `get_device_capability() >= (8, 9)`, which passes on ROCm because ROCm reports the gfx version (gfx1151 gives (11, 5)), and torchao then refuses fp8 there. **Fix.** Tests only. The autouse fixture pins the card count and the capability check (tests that probe those filters still override them), and the fp8 GPU gate returns False on a HIP torch, matching Studio, which already declines torchao fp8 on ROCm. New test `test_two_discrete_rocm_cards_split_like_cuda`: with HIP set and two cards at capability (11, 0), the planner selects both and splits onto card 1, as on CUDA. **Tests.** Spoofed host (HIP + one integrated card, HIP + two discrete cards, one CUDA card without HIP): 11 failed before, 114 passed after on each. Normal CPU host: 133 passed, 1 skipped. ### 7. The ROCm APU pool discount applies only to HIP device snapshots (#14379) **What was broken.** `_rocm_linux_apu_os_room_outside_pool` (`diffusion_memory.py`) gave any unified-memory reading the smaller Linux ROCm APU reserve on a ROCm build, without checking the snapshot's device. On a ROCm host, a mocked Apple (`mps`) snapshot in `test_diffusion_unified_load_override.py` got that reserve, so two refusal tests failed. A real ROCm build never produces an `mps` reading, so the user impact is close to zero. **Fix.** The discount now requires a `cuda` device snapshot (`cuda` or `cuda:N`). `test_flux3_prompt_upsampler.py` also pins `torch.__version__` in the tests that stand in for a CUDA build (Studio reads `+rocm` there too) and pins the card count in its warm fixture, which read the real host. **Tests.** The new `mps` / `cpu` reserve test fails without the fix and passes with it. Prompt upsampler: 164 passed on a spoofed APU, two discrete ROCm cards, two CUDA cards and plain CPU. ## Tests Base is origin/main and head is this branch. Same host and same Studio venv (diffusers 0.41 dev, torch 2.13). Failing test IDs were compared, not counts. - CPU, GPU hidden: test_diffusion_vae_oom.py, test_diffusion_vae_oom_faults.py, test_diffusion_measured_placement.py, test_diffusion_offload_cuda_graph.py, test_diffusion_learned_peaks.py, test_diffusion_int8_gemm.py, test_video_stream_residency.py, test_diffusion_offload_prefetch.py, test_diffusion_small_host_prefetch.py, test_diffusion_fbcache_mixed_stream.py, test_video_stream_encode.py, test_diffusion_multigpu.py. Base: 3912 passed, 125 skipped, 0 failed. Head: 3916 passed (the 4 new tests), 125 skipped, 0 failed. No failing IDs on either side. - One GPU visible: test_video_prequant.py. Base: 1 failed (`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`), 85 passed. Head: 86 passed. - CPU, GPU hidden: test_diffusion_cfg_batch.py, test_diffusion_multigpu.py, test_diffusion_multigpu_wiring.py, test_video_multigpu_wiring.py. Base: 128 passed. Head: 130 passed (the 2 new tests). No failures on either side. - test_diffusion_fbcache_mixed_stream.py on diffusers 0.39.0: 1 failed before, 7 passed after. Wan2.1-T2V-1.3B end to end on a Kaggle T4 capped at 7.25 GiB (streamed offload, fp32, 480x320, 17 frames, 6 steps, guidance 5, seed 1234). Base and head ran on the two T4s of one kernel, each on its own CPU slice: | Run | s/step | CFG batch | |---|---|---| | base, CFG batching off | 5.96 | not armed | | base, auto | 8.55 | 0 hits, 3 misses (timestep 941 vs 941), then off | | head, CFG batching off | 5.58 | not armed | | head, auto | 5.55 | 2 hits, 0 misses, then off: measured no gain (batched pair 5.42 s vs plain pair 5.39 s) | - The 43% slowdown on base is gone. On this streamed T4 placement a batched pair is no faster than two plain calls, so the batcher's own timing gate turns it off, as designed. - The batching-off latents are identical on base and head (`829b889b587d13f6`), so the plain path is unchanged. The two batched steps are not bit-exact, as documented for CFG batching. ## Not verified - CFG-parallel on two real cards: test_diffusion_multigpu_cuda.py needs two CUDA cards in one process and was skipped. - No real two-GPU decode that runs out of memory. The split case is covered by CPU tests that use real `torch.device("cuda", N)` indices with fake graph handles and resident modules. - diffusers 0.40.0 was not run. Its source lacks the same invalidation as 0.39.0.
danielhanchen
added a commit
that referenced
this pull request
Oct 23, 2026
…cesses so a seed keeps one path (#14849) ## Problem Single-card CFG batching (#13787, defaults from #14566, #14652, #14734) decides per request shape whether both guidance branches run as one doubled call. Batched is a tolerance mode (about LPIPS 0.01-0.02 versus plain on some models, since the doubled batch can pick other kernels), so the same seed and prompt only give the same image if every render takes the same path. Three ways that choice could change: 1. **Between processes.** The verdict lived only on the router (`CfgBatchRouter.shapes`, keyed on the argument tensor shapes, per load). Every new process or reload re-ran the 2-sample trial (`min(batched) > 0.92 * min(plain)`, plus the single-sample `_RESIDENT_MAX_PAIR_S` gate). A shape near the 0.92 line landed on either side depending on timing noise. 2. **Between renders in one process.** A shape turned off by memory pressure (`_OFF_TRANSIENT`: no room before the trial, or an OOM on a doubled call) had `judged` reset in `end_render`, so the next render re-timed it and could latch "measured no gain" for the rest of the load. 3. **Within one render.** `_batched` returned plain for a single step when free memory read below 2x the activation peak and batched again on the next step, so a fluctuating free-memory reading mixed paths step by step. Probe with a controlled timer (per-call lognormal noise, 40 fresh loads per cell; P = plain pair, B = doubled call): | doubled / plain pair | noise sigma | main | this PR | |---|---|---|---| | 0.92 | 0 (A/A) | 40/40 batched | 40/40 batched | | 0.90 | 0.05 | 29 batched, 11 plain | 40/40 one path | | 0.92 | 0.02 | 22 batched, 18 plain | 40/40 one path | | 0.94 | 0.05 | 20 batched, 20 plain | 40/40 one path | One transient OOM on render 2, ratio 0.91, sigma 0.03: render 1 and render 4 took different paths in 2/40 loads on main, 0/40 here. Free memory moving around the line each step on main: `PPPBPBBB`, `PPBBPPBP`. ## Fix - The timing verdict is latched on the shape (`_Shape.verdict`). A transient memory off still makes that render plain, but the next render batches again from step 3 without a new trial. - Verdicts are stored in `diffusion_cfg_batch_verdicts.json` next to the learned peaks. The key covers the load (denoiser class, config, layer classes, weight dtypes, offload policy, speed tier), the card name, compiled or eager, the request shape, and the runtime stamp (torch, diffusers, kernel packages). First writer wins under the same file lock as the learned peaks, so a later process takes the stored path with no trial. Only measured timing verdicts are stored. Nothing is stored off CUDA or for a load that cannot be identified. `UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS=0` keeps the verdict per load, and `UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS_FILE` sets the path. - If a doubled call has no room mid-render, the shape stays plain for the rest of that render. It no longer skips single steps. - OOM safety is unchanged: no room or an OOM still falls back to plain for that render. A shape whose first doubled call comes from a stored verdict counts that render as its warm-up, so the compiled-graph rules match the trial path. Nothing changes under Dynamo tracing (the router still passes straight through) and there is no new per-step work. The store is read once per shape per load. ## Tests - New in `studio/backend/tests/test_diffusion_cfg_batch.py`: a borderline shape keeps one path across fresh loads (both verdicts), memory pressure never re-times a judged shape, no room mid-render keeps the rest of that render plain, and the store is keyed on the card and skipped off CUDA. All 5 fail on main and pass here. - `test_diffusion_cfg_batch.py`, `_cfg_batch_sync`, `_cfg_parallel_tier`, `_zimage_cfg_split`, `_speed`, `test_diffusion_backend.py`, `test_video_backend.py` with `-n 8`: 1465 passed here; on main 1460 passed and the 5 new tests failed. - Real CUDA (B200, tiny random FLUX.2-klein, resident bf16, CFG 4, 6 steps, 256x256): process 1 ran the trial and stored `batch`. Process 2 skipped the trial (`[1, 1, 1, 1, 2, 2, 2, 2]`) and gave the same image hash as process 1. ## Not covered - No real-model LPIPS run: the probe shows the path choice, and the image difference between paths is the tolerance already measured in #13787. - A stored verdict is not re-measured after a driver change, or after other changes that leave the key the same. Deleting the file or setting `UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS=0` resets it. - If memory really runs short partway through a render, that render still switches to plain from that step on. This is the intended OOM fallback. - `activation_mib` is only known when a plain call raises the process's peak counter, so whether the memory gate applies still depends on process history. Unchanged here. - `test_diffusion_backend.py::test_begin_load_rejects_concurrent` hit its 30 s thread timeout on a loaded host. It fails the same way on main and is unrelated. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
When the denoiser does not fit the card and streams from host memory, every guided step uploads the weights twice: once for the conditional branch and once for the unconditional one. This PR runs both branches as one doubled forward, so the weights upload once per step.
This replaces the earlier version of this PR. The CFG-parallel link pricing and device probing are withdrawn: multi-GPU placement is in #13725 (merged), and this PR is only the single-card batching, in its own module.
What it does
core/inference/diffusion_cfg_batch.py, installed next toinstall_cfg_paralleland released at the end of each render next toend_cfg_render(5 lines each indiffusion.pyandvideo.py).status()["cfg_batch"]reports whether it is armed, why it declined, and the batched / hit / miss counts.UNSLOTH_DIFFUSION_CFG_BATCH=0|auto|force.0keeps the exact two-call path.UNSLOTH_DIFFUSION_MULTIGPU=0no longer turns batching off.autoarms only for a denoiser Studio streams from host memory (group / streaming / model offload), for FLUX.1, FLUX.2, Qwen-Image and single-expert Wan.forcealso batches a resident denoiser and unlisted classes, as ComfyUI does.NVFP4Tensor), armed CUDA graphs, an installed step cache, a denoiser compiled whole, two experts. A displaced router passes calls through, and install never fails a load.Fixes over the earlier version
img_shapeslist was refused, and so were unequal positive / negative prompt lengths. The list is joined per sample (whichzero_cond_talso needs) and the shorter prompt is padded with masked zeros.Results
FLUX.2-klein-base-4B, 1024x1024, 12 steps, guidance 4, one B200 with memory capped so the DiT streams (
streamingoffload), multi-GPU off in every arm, exclusive card, 2 prompts x 2 repeats per arm:UNSLOTH_DIFFUSION_CFG_BATCH=01.88x per step and about 1.7x per image. All 54 batched steps hit, 0 misses. Torch peak memory rose by about 200 MiB (2647 to 2859 MiB).
The images were bit-identical in this run, but batching changes the batch size the kernels see, so other models or cards can pick different kernels: an earlier A100 run of the previous version measured LPIPS 0.0087. Treat
autoas a tolerance mode and0as the exact path.Testing
tests/test_diffusion_cfg_batch.py: 11 tests (Qwen-Image unequal prompt lengths andimg_shapes, per-sample list joins, declines, the switch being independent of multi-GPU, device sync on the latent's card, guidance ending mid-render).Not verified: video (Wan 2.1) on GPU, consumer PCIe cards, ROCm, macOS and Windows.