Skip to content

Studio: split one diffusion denoiser across GPUs by block ranges - #14412

Merged
danielhanchen merged 28 commits into
mainfrom
studio-diffusion-layer-split-v2
Oct 21, 2026
Merged

danielhanchen merged 28 commits into
mainfrom
studio-diffusion-layer-split-v2

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Studio can now split one diffusion denoiser across several GPUs by block ranges when it does not fit on any single selected card. Until now a denoiser that was too big for one card fell back to host RAM offload, even with a second card sitting idle. With this PR the blocks are cut into contiguous ranges, one range per card, and the activations hop across the card boundaries. The output is bit-identical to one card in eager mode, and the split keeps the speed paths: regional compile, per-card CUDA graphs, the step cache and the int8 kernels.

This builds on the multi-GPU placement from #13725 (component placement and CFG-parallel), which is already in main.

What it does

  • diffusion_layer_split_plan.py is the planner. It prices every selected card from its free memory, the block working set and the per-card reserve, keeps at least one block on the primary, cuts two denoisers (Wan 2.x A14B) jointly when only some pair of cuts fits, and picks where the text encoders go (a card that has room, else streamed from host RAM, since they run once per prompt and the denoiser runs every step). When nothing fits it records why, and the status shows that reason.
  • diffusion_layer_split.py is the engine. It moves each block to its card, swaps the block class for a same-named subclass whose __call__ moves the inputs to the block's card, and routes the outputs. Families whose forward passes one block's output straight to the next block route lazily (one copy per card boundary): FLUX.1/2/3, Qwen-Image / 2.1, Z-Image, HunyuanImage, HiDream, Wan, LTX-2, HunyuanVideo-1.5, Krea2, Lumina2, MiniMax-H3 and Ideogram4. Others, and any call with a residual input such as ControlNet or VACE hints, run eager (outputs come back to the primary after every block). Unload undoes the split.
  • Speed paths on a split:
    • The speed layer, the compile cache key and the int8 kernels are set up for the split placement, not for the one-card offload plan the split replaces. Before, a split denoiser compiled without fullgraph and kept the int8 GEMM in its streaming mode.
    • Regional compile follows main's PROMPT_LENGTH_POLICY. Qwen-Image also arms its prompt-length sources on the default tier, so a new prompt length does not recompile.
    • Per-card CUDA block graphs, and per-card segment graphs (a run of blocks on one card recorded as one graph, only on a lazily routed forward, breaking if a handed-on tensor was rewritten in place). Block and segment graphs key on the root's branch flag (_unsloth_graph_key_extra), as the whole-step graph does. For a family whose text length follows the prompt, they record only the first render's prompt lengths per image scope (main's sealing for the whole-step graph, applied per card). A later new length runs compiled without graphs.
    • The First-Block-Cache goes back on after placement. Its residuals are copied between the head and tail cards, around main's FLUX.2 mixed-stream tail.
    • The int8 GEMM, the fused int8 / QKV records and the Qwen-Image / Qwen-Image-2.1 / Z-Image fused RoPE paths run per card. Each block uses its own card's kernels and probes (diffusion_int8_gemm.after_layer_split).
  • A quantized DiT on a split is compiled. When the one-card plan offloads, Studio picks the torchao-free int8 scheme (W8A8 torch._int_mm), and the rule that forces compile for a quantized DiT skipped that scheme, so a split that kept it resident ran eager. Both backends now compile it once the DiT stays resident: on one card, on a layer split, or on a companion split that keeps it whole on the primary. ROCm and Apple keep their own native path.
  • Video gets the same treatment: the same split-aware speed setup, the step cache back after placement, and the per-card int8 binding. When a split it expected falls back to the one-card offload plan at placement, the compile moves below the offload hooks, as on the image backend (a full-graph block compile over group offload hooks fails to trace and drops the whole DiT to eager).
  • The generate-time check on a card that holds only blocks scales that card's working set with the request size and charges its fixed reserve once, so a large render is not refused on a card where it fits.

How the auto planner picks a placement

For each load, in this order:

  1. One card. The denoiser and its companions fit the primary card: nothing changes from today.
  2. Companion split (Studio diffusion: multi-GPU component placement and CFG-parallel #13725). The denoiser fits the primary once the text encoders and/or the VAE move to a second card: they move, and the denoiser stays whole on the primary.
  3. Layer split (this PR). Nothing fits on one card, but the denoiser blocks fit across the selected cards. Fewest cards first: the primary, then the secondaries from largest to smallest.
  4. Offload. Nothing fits: the one-card offload plan stays as it is today, and the status says why the split declined.

A layer split is CUDA only (ROCm declines with a reason), needs a denoiser with a sequential block list the engine can cut, and is skipped for explicit offload memory modes and unified memory. CFG-parallel does not arm on a split denoiser.

Kill switches

Variable Effect
UNSLOTH_DIFFUSION_MULTIGPU=0 every multi-GPU placement off (companion split, layer split, CFG-parallel)
UNSLOTH_DIFFUSION_LAYER_SPLIT=0 layer split off; force splits even a denoiser that fits one card
UNSLOTH_DIFFUSION_SEGMENT_GRAPHS=0 per-card segment graphs off (per-block graphs stay)
UNSLOTH_DIFFUSION_BLOCK_GRAPHS=0 per-block CUDA graphs off
UNSLOTH_DIFFUSION_CFG_PARALLEL=0 CFG-parallel off

Results

All numbers are on a B200 pair. Image runs use 1024x1024, 8 steps and guidance 4. LTX-2 uses 768x512, 33 frames and 8 steps. "One card" means UNSLOTH_DIFFUSION_MULTIGPU=0. "Split" means UNSLOTH_DIFFUSION_LAYER_SPLIT=force across two cards, except the last table, where the planner chose the split itself. Image timings ran on exclusive cards. The LTX-2 timings ran on shared cards, so treat those as rough.

Eager (speed off): the split is bit-identical to one card

Model One card s/step Split s/step Image hashes, 2 prompts x 2 repeats
FLUX.2-dev bf16 0.313 0.304 identical (1e7585a4, 6976052b)
Qwen-Image bf16 0.219 0.219 identical (2cfafe27, 325b36eb)
LTX-2 (shared cards) 0.86 to 0.90 0.64 to 0.69 identical (ea1c175a, 1c355af5)

Compiled (speed default)

Model One card s/step Split s/step Graphs on the split
FLUX.2-dev bf16 0.221 0.203 3 per-card segment graphs per step
Qwen-Image bf16 0.145 0.132 2 per-card segment graphs per forward
LTX-2 (shared cards) 0.36 to 0.59 0.29 to 0.30 none (video families do not record graphs)

On LTX-2 the compiled split is also bit-identical to the compiled single-card run (399f4a65, 7e445ae0, ed4e8d71).

Prompts of different lengths, new seed each, no separate warm-up

Model Split: setup on generations 2 and 3 One card: setup on generations 2 and 3
FLUX.2-dev 0 recompiles, 0 graph captures 0 recompiles, 0 graph captures
LTX-2 0 recompiles, 0 graph captures 0 recompiles, 0 graph captures
Qwen-Image 0 recompiles, 0 graph captures (new lengths run ungraphed: 0.134 vs 0.131 s/step) 0 recompiles, 0 graph captures (main's sealing)

FLUX.2 pads the prompt to 512 tokens. Qwen-Image does not pad it, so its graphs record only the first render's lengths. A length recorded there replays later (generation 4 above), and a new one runs compiled without graphs, on one card and on the split alike.

Quantized DiT on a planner-chosen split (LTX-2, int8, both cards capped to 44 GiB free, shared cards, speed left at off)

Build Speed engaged s/step
main + split, before the compile fix off (eager) 0.89 / 1.23
this PR default (forced, like torchao int8) 0.33 / 0.33
this PR, speed default, prompts of 5 / 26 / 69 words default 0.32 / 0.31 / 0.35, 0 compiles and 0 captures on generations 2 and 3
one card, torchao int8, speed default (reference) default 0.26 / 0.26 / 0.25

Compiled runs are reproducible across processes, and the compiled split matches compiled one card

Exclusive B200 pair, speed default (compiled), every row a fresh process with no compile cache, 2 prompts:

Model One card, process 1 / 2 Split, process 1 / 2 s/step one card / split
Qwen-Image 0408ab61, aa0de448 / same 0408ab61, aa0de448 / same 0.143 / 0.130
FLUX.2-dev 1c50b74e, 0d8f3a55 / same 1c50b74e, 0d8f3a55 / same 0.224 / 0.202

Two sources of per-process variation had to go, and neither came from the split. A split compiles its blocks once per card, so it made them easy to see:

  • Qwen-Image: inductor benchmarks near-tied norm-reduction configs in each process, and they sum in different orders. Before this PR, four fresh one-card processes rendered four different images, 42 / 26 dB apart (the same gap seen between two split processes). Studio already pins these reductions for Qwen-Image on A100 / L4 / RTX PRO 6000; this PR adds B200 for Qwen-Image and its edit / layered siblings.
  • FLUX.2-dev: cudnn.benchmark picks the VAE conv algorithm per process. Seven fresh processes on shared cards rendered five variants of one seed, on one card and on the split alike, 58 to 59 dB apart. FLUX.2-dev now keeps cudnn.benchmark off, like FLUX.1, Qwen-Image, Z-Image and SDXL already do. That costs about 0.01 s per 1024x1024 image (1.83 vs 1.82 s).

Planner-chosen split

FLUX.2-dev bf16 at speed default, with both cards capped to about 70 GiB free so that one card would need group offload. The planner picked the split ("transformer cut over 2 cards ... single card would use 'group'"). The run compiled and recorded per-card graphs, ran at 0.205 s/step, and showed no recompile or capture on generations 2 to 4. It also loaded the same compile cache bundle as the single-card resident compile. Before this PR, the planner-chosen split compiled under the one-card offload plan's settings and used a different bundle.

Tests

  • CPU unit suites (layer split, split speed paths, load order, prompt-length policy, dynamic text, multi-GPU, memory, measured placement, CUDA / block graphs, step cache, compile config / cache / regional compile, int8 GEMM / fused, native quant, Qwen-Image / Qwen-Image-2.1 / Z-Image fused paths, image and video backends): 2830 passed. The one failure (test_unpinned_torchao_host_copy_is_a_distinct_wrapper_over_the_same_data) fails the same way on main.
  • Every diffusion / video / offload / multi-GPU test file on CPU, main vs this branch: no new failing test IDs. The failures on main (LM Studio diffusion chat, training offload layers, three VAE tiling files that time out under load) fail the same way here.
  • On two real CUDA cards: test_diffusion_layer_split_cuda.py and test_diffusion_multigpu_cuda.py, 3 passed.

Not covered

  • PCIe consumer cards. Every run here was on B200s, where the boundary copies are cheap.
  • ROCm, which declines the split with a reason, and Windows / macOS / MLX, which have no split.
  • More than two cards, on real models.
  • Wan 2.x A14B (two experts), HunyuanImage, HiDream, Z-Image, FLUX.1 and FLUX.3 were not re-run on this branch at full size. The HunyuanImage lazy routing was measured on an earlier build of the split: identical images, 0.163 vs 0.18 to 0.19 s/step eager. HiDream routing lazily is checked on a tiny random HiDream split over two real cards with several blocks per stream per card: bitwise equal to one card, one hop per card boundary, and one segment graph per card per stream (tests/test_diffusion_layer_split_cuda.py).
  • Families that keep cudnn.benchmark on (FLUX.1-Kontext, FLUX.2-klein, FLUX.3, HiDream, HunyuanImage-2.1, Ideogram-4, Krea-2, Lumina-2, MiniMax-H3, Qwen-Image-2.1, Qwen-Image-Edit / Layered) were not checked for per-process VAE variants. Neither were FLUX.1 and Z-Image for the B200 reduction race.
  • The torchao int8 split paths (per-card int8 GEMM, fused records, the Qwen-Image-2.1 / Z-Image fused paths) and the First-Block-Cache across cards are covered by CPU tests only here, with no real-model run on this branch. The int8 run above uses the torchao-free scheme, which needs no per-card swap. The auto-int8 load time on a split was not re-measured.
  • On the image backend the text encoders are quantized after the speed layer, so a companion split that fits only once they are quantized is not previewed, and a torchao-free int8 DiT placed that way still runs eager unless speed is on.
  • The torchao-free int8 split (0.33 s/step) is still slower than a resident torchao int8 build on one card (0.26 s/step).

A denoiser too big for any one card is cut into contiguous block ranges, one range per card, instead of falling
back to host RAM offload. The planner (diffusion_layer_split_plan) prices each card from its free memory and the
block working set, keeps a block on the primary, and records why it declines. The engine
(diffusion_layer_split) moves the blocks, routes activations across the range boundaries, and undoes the split
on unload.

On a split: regional compile with prompt-length dynamic shapes (one policy per denoiser family), per-card CUDA
block and segment graphs, the First-Block-Cache across cards, and per-card int8 GEMM and fused records
(diffusion_int8_gemm.after_layer_split). UNSLOTH_DIFFUSION_LAYER_SPLIT=0 turns the split off;
UNSLOTH_DIFFUSION_SEGMENT_GRAPHS=0 and UNSLOTH_DIFFUSION_BLOCK_GRAPHS=0 turn the graphs off.
…card

resident_cuda_device answers None once the blocks span cards, which kept the Qwen-Image real-arithmetic RoPE,
the Qwen-Image-2.1 and Z-Image fused paths off on a split. resident_cuda_cards lists every card of a split; each
patch probes every card and each block reads its own card's probe. after_layer_split probes the Qwen-Image-2.1
RoPE on the cards the install did not see.

HunyuanImage routes lazily on a split (bit-identical images, faster); HiDream stays eager because it
concatenates root-level state with a block output between blocks.
…lacement

The speed layer runs before placement and saw the one-card offload plan a split replaces, so a split denoiser
compiled without fullgraph and kept the int8 GEMM in its streaming mode. Both backends now ask the multi-GPU
refinement first and set up the speed layer and the compile key for a resident split. After placement the
First-Block-Cache goes back on (it copies its residuals across the head and tail cards) instead of staying off,
and the per-card int8 / fused records and block graphs bind on the video backend too.
… torchao one

The NVIDIA int8 offload scheme (W8A8 torch._int_mm) is chosen while the one-card plan offloads, and the force
compile rule skipped every torchao-free scheme, so a layer split that kept that DiT resident ran it eager (LTX-2:
0.90-0.97 vs 0.26 s/step compiled). Both backends now force the regional profile for it once the DiT stays
resident, on one card or split across cards. ROCm and Apple keep their own native path.
HiDream moves each block's llama states and concatenates them on hidden_states.device, so its outputs can go
straight to the next block's card. A two-card split of a tiny random HiDream is bitwise equal to one card in both
routings (lazy: one copy per card change instead of every block's inputs); tests/test_diffusion_layer_split_cuda.py
pins it on two real cards.
Two fresh one-card processes rendered one Qwen-Image seed 42 / 26 dB apart on B200: inductor benchmarks
near-tied norm-reduction configs per process. A layer split compiles its blocks once per card, so it picked
per card as well and looked irreproducible. With the reduction filter on B200, three fresh one-card and three
fresh split processes match bitwise at the same s/step. FLUX.1 and Z-Image keep their measured arch list.
cudnn.benchmark picks the VAE conv algorithm per process, and the picks sum differently: seven fresh B200
processes rendered five variants of one FLUX.2-dev seed, on one card and on a layer split alike. Held off, two
one-card and two split processes render the same image. Same rule as FLUX.1, Qwen-Image, Z-Image and SDXL.
Main now carries the prompt-length policy table and prompt_length_varies (#14387) and the FLUX.2 First-Block-Cache
mixed-stream tail (#14401); the branch keeps main's of both and drops its own copies: one table, main's compile
arming (FLUX.1 and Z-Image classified, not armed), and no FLUX.2 FBCache refusal. On top: Qwen-Image still arms
its sources on the default tier, the layer split's FBCache guard wraps the mixed-stream tail (the residual is taken
on the tail's card), and a split's per-card graphs seal new prompt lengths per image scope, as main's whole-step
graph does, instead of being refused for a prompt-length family.
@danielhanchen danielhanchen self-assigned this Oct 20, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-21T02:50:00.109876Z 131e01a New commits
🔒 Security Review ⚠️ Failed 2026-10-20T21:50:12.777094Z
We couldn’t complete this review. Comment @codex security review to try again.
53e7e6e PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 53e7e6e66e

ℹ️ 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".

Comment on lines +9070 to +9072
# A layer split keeps every block resident on some card: the speed layer and the compile key are set
# up for that placement, not for the one-card offload plan it replaces.
split_expected = _layer_split_expected(pipe, plan)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recompute placement after text-encoder quantization

When text-encoder truncation or quantization is what makes a resident multi-GPU placement fit, this preview still sees the larger pre-quantized components because quantize_text_encoders runs later, while the final refinement at placement sees the reduced sizes. Consequently split_expected can be false even though the final plan is a resident component or layer split; for a native int8 DiT with speed disabled, quant_forces_compile then remains false and the newly resident denoiser takes the much slower eager path this change is intended to avoid. Recompute the preview after encoder quantization or reconcile the speed setup with the final plan.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in part in 9b3a042. For a layer split this cannot happen: the planner can always stream the text encoders from host RAM, so whether the blocks fit never depends on encoder size. The component split half was real: the early preview only recognised a layer split, so a torchao-free int8 DiT kept whole on the primary stayed eager. _companion_split_expected now feeds the int8 compile rule in both backends (test_a_companion_split_preview_counts_as_a_resident_denoiser). The remaining case, an image component split that fits only after encoder quantization, is listed under Not covered: moving quantization ahead of the speed layer also moves it ahead of the backend-flag snapshot unload restores, which is too invasive here. Video already quantizes its encoders first.

Comment on lines +234 to +237
left = sum(sum(denoisers[n].block_mib) for n in names[idx:])
share = sum(layout.block_mib) / left if left else 1.0
caps_d = [int(r * share) if idx < len(names) - 1 else r for r in remaining]
cuts = _partition(layout.block_mib, caps_d) or _partition(layout.block_mib, remaining)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Backtrack block cuts across multiple denoisers

For dual-denoiser pipelines, each denoiser is partitioned irrevocably before the next one's block sizes are considered, so a feasible joint placement can be rejected. For example, with card capacities 3/3 and block sizes A=(1,1), B=(1,2,1), placing all of A plus B's first block on the primary and B's remaining blocks on the secondary fits; this code instead proportionally splits A 1/1, leaves capacities 2/2, and then cannot partition B. The planner therefore falls back to host offload (or may unnecessarily add another card) despite a valid two-card split, so it needs to try alternate earlier cut points when a later denoiser fails.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in 593e3c1. When cutting the denoisers one at a time finds no placement, _search_cuts runs a bounded joint search over all denoisers' cut points (200k nodes). Your 3/3 example with A=(1,1), B=(1,2,1) now splits. Test: test_two_denoisers_that_fit_only_jointly_are_cut_jointly.

Comment on lines +2243 to +2244
checked += 1
need = int(reserved * scale)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scale only the secondary activation working set

For a larger-than-default image, reserved is not purely activation memory: card_required_mib - card_weights_mib contains both the block working set and the fixed per-card safety reserve (at least 1.2 GiB on Linux). Multiplying the whole value by the request-size ratio therefore scales that fixed reserve as if it were an activation, causing otherwise viable large renders to be refused; the analogous video calculation scales the same combined field. Preserve the fixed reserve and scale only the working-set portion.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in fb76587. LayerSplit records card_reserve_mib, and both the image guard and video_split_shortfall_message scale only the working set and add the reserve once. Tests: test_block_card_guard_scales_only_the_working_set_not_the_fixed_reserve and test_video_guard_scales_only_the_working_set_not_the_fixed_reserve.

Comment on lines 9309 to +9310
speed_optims: tuple = ()
speed_offload = plan.offload_policy != "none" and not split_expected

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reconfigure video compilation after split fallback

When a predicted video layer split fails during placement and apply_memory_plan installs its group/streaming fallback, the speed layer has already been configured with offload_active=False here, including a fullgraph=True regional compile. After applied_plan switches to the offloaded fallback, the video path never calls compile_pipe_below_offload_hooks or otherwise rebuilds that compile, even though the speed layer documents that compiler-disabled onload hooks inside a full graph crash on the first step. Reconcile the compile with the applied fallback as the image backend does before allowing generation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in 8b689cf. After placement, a video load whose speed layer was built without offload but whose denoiser ended up hooked (a predicted split that fell back to group offload) moves the compile below the hooks, as the image backend does. Before, the full-graph compile hit the compiler-disabled onload hook and the whole DiT fell back to eager. Test: test_a_layer_split_fallback_moves_the_compile_below_the_offload_hooks, plus a GPU repro on a tiny FLUX transformer (fails before, runs after).

pre-commit-ci Bot and others added 6 commits October 20, 2026 22:02
… cutting in turn finds none

Cut one after the other by proportion, an earlier expert could take the room a later one needed (cards 3/3,
blocks (1, 1) and (1, 2, 1)), and a two-card split that fits fell back to offload. When that happens the planner
now backtracks over the cut points of every denoiser together, each still keeping a block off the primary.
The block card guards (image and video) scaled everything the plan
reserved past the weights, including the fixed per-card reserve. Record
that reserve on the split and charge it unscaled.
The speed layer compiles for the layer split it previewed (full graph,
no offload). When placement lands the one-card offload fallback instead,
the onload hooks sit under that full graph. Move the compile below the
hooks after placement, as the image backend does.
The torchao-free int8 DiT is compiled once it stays resident, but the
early placement preview only recognised a layer split. A component split
also keeps the denoiser resident (other components move to the second
card), so the int8 DiT stayed eager there.

[skip ci]
[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e07682fa85

ℹ️ 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".

inside = None
base = getattr(type(module), "_unsloth_layer_split_base", type(module))
if base.__name__ in wanted:
out.append((qual, qual.rpartition(".")[0], module))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Group wrapped blocks by their containing list

For HiDream, the repeated modules are nested as double_stream_blocks.N.block and single_stream_blocks.N.block, so using the immediate parent gives every block a different group. _install_boundary only routes lazily when adjacent groups match, and _segments uses the same grouping, so a multi-block HiDream split returns every off-primary block output to the primary and cannot build per-card segment graphs—adding cross-card transfers after every block instead of only at card boundaries. Normalize these wrapped blocks to their containing ModuleList group.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in eec9dc2. A wrapped list entry (double_stream_blocks.N.block) is now grouped with its containing list, so a HiDream split hops once per card boundary and builds per-card segments. On a tiny HiDream (4 double + 6 single blocks, 2+2 / 3+3 over two cards): cross-card block inputs 17 -> 10, root tensor copies 9 -> 2, segments 2/2/3/3, bitwise equal to one card. Tests: test_a_wrapped_list_entry_groups_with_its_list and test_a_hidream_split_hops_once_per_card_boundary_and_records_per_card_segments.

HiDream's list entries wrap the repeated block (double_stream_blocks.N.block),
so grouping by the immediate parent made every block its own group: each
off-primary block sent its output back to the primary and no per-card
segment graph formed. Group by the path before the last list index.
The formatter split the pinned-denoiser condition across lines, which
broke the substring match.
…ly on lazy chains

Block and segment graph keys now include the root's graph key extra, as
the whole-step graph does, so a recording made on one branch (the
HunyuanVideo-1.5 null-mask flag) never replays for the other.

A segment matched later blocks' inputs by tensor identity only, so an op
between blocks that rewrote an output in place still got the recorded
next output. Segments now start only on a lazily routed forward (a
class verified to pass each block's outputs straight on, no residual
input), and break when a handed-on tensor's version changed.
An auto First-Block-Cache that turns on at generate time put its hooks
under block graphs recorded without them, and the video backend never
bypassed its graphs per generation. Block and segment graphs now check
the denoiser's step cache marker, as the whole-step graph does, and the
video generate bypasses its graphs while the cache breaks them, as the
image backend does.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 3f61a455f4

ℹ️ 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".

pre-commit-ci Bot and others added 3 commits October 21, 2026 01:05
The plan and order tests build their fake two-card selection through
make_selection, which reads torch's device count and the primary's
capability, and the planner declines on a HIP torch. On a ROCm host
(the one-GPU Strix Halo APU in AMD CI) every split came back None.
Pin the count, the capability and _is_rocm in the autouse fixtures;
the ROCm decline keeps its own test.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f99e78f98c

ℹ️ 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".

Comment on lines +316 to +317
if cuts is not None and n > 1 and cuts[1] == n:
# the cut rounded every block onto the primary, which the engine refuses: move its last block to the furthest card with room

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allow a denoiser to remain wholly on the primary

In a dual-denoiser pipeline, forcing every denoiser to contribute a block to a secondary can reject a feasible resident placement. For example, with post-reserve capacities 4/6 MiB and block layouts A=(2,2) and B=(3,3), keeping A wholly on the primary and B wholly on the secondary fits exactly, but this rewrite splits A 2/2, after which B cannot fit; _search_cuts also excludes the all-primary cut. The placement path already handles whole_on_primary, so preserve that cut as long as at least one denoiser makes the overall plan multi-GPU.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7481da4. The joint cut search now lets a denoiser stay wholly on the primary as long as another denoiser puts a block on a secondary (placement already handled whole_on_primary). Your 4/6 MiB example with A=(2,2), B=(3,3) used to decline; now A stays on cuda:0 and B lands on cuda:1, and a plan where nothing leaves the primary still returns None. Test: test_dual_denoisers_may_keep_one_wholly_on_the_primary.

Comment on lines +702 to +705
with contextlib.suppress(Exception):
pipe.to("cpu")
import torch
torch.cuda.empty_cache()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Release off-tree fused weights when split placement fails

When placement fails after moving any fused block, this cleanup moves only registered pipeline modules back to CPU. The fused QKV and SwiGLU modules are stored directly in parent __dict__ records rather than registered as children, and their weights own the original shared CUDA allocation after the registered projection views are moved; consequently pipe.to("cpu") leaves that allocation referenced and empty_cache() cannot reclaim it. The one-card fallback can then OOM on VRAM that should have been released, so drop or relocate these fused records before applying the fallback.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eb74813. New drop_stranded_fused_records (diffusion_int8_fused.py) drops any off-tree fused record whose weight sits on a different device from its parts; apply_layer_split_plan calls it after pipe.to("cpu") and before empty_cache(), so the one-card fallback gets that VRAM back. Readers already handle a missing record. Reachable when a prequantized denoiser is seeded onto the primary before placement. Test: test_failed_placement_drops_fused_records_left_on_another_card.

Comment on lines +902 to +904
try:
from .diffusion_qwenimage21_rope import probe_split_cards
out["rope_cards"] = probe_split_cards(cards)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Probe Z-Image RoPE on every post-split card

When the Z-Image speed patch is installed while the denoiser is resident on the primary and placement later refines it to a layer split, Z-Image's private _FUSION map contains only the primary card. This post-placement path probes only diffusion_qwenimage21_rope's separate map, so blocks moved to another card take Z-Image's complex _stock_rope path inside regional compilation—the operation this patch documents as unsupported by Inductor—causing those blocks to fail compilation or fall back. Re-probe Z-Image's fusion map for all cards here as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1863795. diffusion_int8_gemm.after_layer_split now also calls the new diffusion_zimage_fused.probe_split_cards, which probes Z-Image's own _FUSION map on every split card (no-op when no install probed a card). Test: test_zimage_real_rope_probes_every_card_of_a_split (_FUSION goes from {0} to {0, 1, 2}).

Comment on lines +258 to +260
secondaries = sorted(
(o for o in card_limits if o != primary), key = lambda o: (-card_limits[o], o)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate the attention backend on every block card

With heterogeneous selected GPUs, this planner admits secondary cards solely by memory capacity even though the attention backend was selected and architecture-gated against the primary before placement. For example, auto cuDNN selected on an Ampere-or-newer primary, or an explicitly selected FlashAttention variant, can then execute blocks on a secondary architecture that the backend rejects, failing on the first denoise. Filter secondary cards by the engaged backend's capability or fall back to a backend supported on every card used by the split.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 45cd7ed. make_selection already drops lower-capability secondaries, but a higher one (for example an H100 primary with a B200) got through while FlashAttention 3 is Hopper-only. refine_plan_for_layer_split now reads the backend tag apply_attention_backend set at load; for arch-pinned backends (flash 3 / 4 hub, sage, sage hub, flash) it keeps only secondaries with the primary's capability and declines with a reason naming the backend if none remain. cuDNN and native SDPA are unchanged. Test: test_an_arch_pinned_attention_backend_keeps_blocks_off_other_architectures.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 45cd7edf9c

ℹ️ 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".

@danielhanchen
danielhanchen merged commit bd63cc3 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-layer-split-v2 branch October 21, 2026 04:39
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…rds (#14479)

## Summary

Enables the diffusion multi-GPU layer split (#14412) on ROCm. Until now
the planner declined every ROCm host with `ROCm (layer split is CUDA
only)`. With this change a denoiser that does not fit one card is cut
across discrete ROCm GPUs, on Linux and on Windows, the same way it
already is on CUDA. Integrated GPUs and APUs (unified memory) decline
with a clear reason, and every ROCm-specific gate is scoped to ROCm
only, so nothing changes on CUDA. `UNSLOTH_DIFFUSION_LAYER_SPLIT=0`
still turns the split off (as does `UNSLOTH_DIFFUSION_MULTIGPU=0`).

## What changed

`studio/backend/core/inference/diffusion_layer_split_plan.py`
- The blanket ROCm decline is gone. On ROCm,
`_rocm_discrete_secondaries` runs Studio's existing APU classifier on
each card (`utils.hardware._rocm_props_unified_status`: the driver's
integrated flag, then the gfx target). A unified primary declines with
`unified memory: cuda:N is an integrated GPU (APU) sharing system
memory, so cutting the denoiser across cards frees no memory`. A unified
secondary is dropped, and if that leaves no secondary the split declines
with the same reason.
- New `note_unified_primary`: when `refine_plan_for_multigpu` stops on a
unified-memory plan, ROCm now records the unified reason in
`status()["multi_gpu"]["layer_split"]`, so a two-APU selection is no
longer silent. On CUDA this stays a silent no-op, same as before.
- Attention backends: on ROCm, native SDPA keeps every card. ROCm
`flash` (flash_attn, #13792) and `aiter` only keep secondaries with the
primary's exact gfx target. `flash` must also pass its own probe on each
secondary (`_rocm_flash_attn_runs` for that card and the denoiser's
dtype), the same probe the primary passes at load. The CUDA branch
(`_PRIMARY_ARCH_BACKENDS` compared by compute capability) is unchanged.
- `_is_rocm` now also detects AMD SDK / Radeon wheels, which leave
`torch.version.hip` unset.

`studio/backend/core/inference/diffusion_multigpu.py`
- `make_selection` on ROCm no longer orders gfx targets as if they were
CUDA capabilities. Before, a 7900 XTX `(11, 0)` primary dropped an MI300
`(9, 4)` secondary. Now a secondary is kept when it can run the
primary's load dtype: if the primary has native bf16, a card that only
emulates bf16 (RDNA1/2, GCN, Vega per `rocm_bf16`) is dropped. The CUDA
path is untouched.
- `refine_plan_for_multigpu` calls `note_unified_primary` on its
existing unified-memory early return. It still returns the plan
unchanged.

### Review follow-ups

- `utils/hardware`: the APU arch set now names every target LLVM's
AMDGPUUsage table types as APU (gfx1153 Krackan Point 2, gfx1033,
gfx1035, gfx1036, gfx1013, gfx90c, gfx902, gfx909, gfx801, gfx810), so
an APU whose runtime leaves `is_integrated` unset no longer reads as
discrete. The device-name fallback (no arch attributes, no flag) also
matches 820M, 8040S, 780M / 760M / 740M, 680M / 660M and 610M as whole
tokens, so discrete mobile names such as RX 7600M stay discrete.
- Native SDPA on ROCm: each secondary runs the existing per-device SDPA
probe at the model dtype. A math-only card beside a fused primary gets
no blocks (math SDPA builds the full score matrix the plan never priced
on that card).
- Component split: a second denoiser (for example Wan's `transformer_2`)
moves to a ROCm secondary only if that card passes the same per-card
backend gate; otherwise both denoisers stay on the primary and only the
text encoder / VAE move.

Already ROCm-safe on main, audited and left alone:
- Per-card CUDA graphs and block graphs: `backend != "cuda"` is off on
ROCm.
- int8 GEMM and fused int8 / QKV records: `_split_cards` and
`resident_cuda_cards` return nothing on HIP.
- Cross-card copies: the boundary does plain `tensor.to(device)`. There
are no custom streams or events in the split path.
- Memory probes: `trusted_mem_get_info(ordinal)` already caps the free
figure on Windows ROCm, per card.
- Compile: per-block regional compile on each card. The ROCm compile
probe is keyed per device.

## Tests

- `tests/test_diffusion_layer_split_plan.py`: 8 new tests. They run
Studio's real classifiers (`_rocm_props_unified_status`, `rocm_bf16`)
over faked device properties:
  - two discrete ROCm cards plan exactly the split CUDA plans;
  - two APUs decline with the unified reason;
- a unified-memory plan records the reason on ROCm and stays silent on
CUDA;
  - a discrete primary skips an APU secondary;
  - the kill switch on ROCm;
- mixed arch selection (7900 XTX + MI300 both kept, RDNA2 dropped under
a bf16 primary);
- mixed arch native SDPA splits, while flash / aiter stay on the
primary's gfx target and flash probes the secondary;
  - the Windows ROCm WDDM free cap on secondary budgets.
- The ROCm decline test is now
`test_rocm_discrete_splits_and_explicit_modes_and_legacy_cpu_offload_keep_the_plan`.
- The fixtures in the plan, order and multigpu suites pin `_rocm_torch`,
so the CUDA-shaped tests behave the same on a ROCm host.
- CPU sweep over every diffusion / video / multigpu / layer split / rocm
test file, base vs head: 18780 vs 18788 passed. The 340 failing /
erroring test IDs are the same on both sides (local environment issues,
present on base).

## AMD CI evidence (gfx1151, Linux, device multiplier)

One batched GPU job on the Strix Halo runner, torch ROCm (HIP 7.13),
`--spoof-devices 2` (3 HIP devices, 2 of them phantom), base = main
`a74da3f321`, head = main + this change, same runner and seeds.

| cell | base (main) | head |
|---|---|---|
| tiny FLUX.1 pipeline, forced split, discrete spoof | declines `ROCm
(layer split is CUDA only)` | split on cuda:0 + cuda:1, 2 calls / 10
hand-offs, bit-identical to one card |
| tiny Qwen-Image pipeline | declines | split, 2 / 6, bit-identical |
| tiny Wan transformer | declines | split, 1 / 8, bit-identical |
| tiny Wan, three cards selected | declines | split on [0, 1],
bit-identical |
| same models, this host as it is (gfx1151 APU) | declines (CUDA only) |
declines `unified memory: cuda:0 is an integrated GPU (APU) ...` |
| FLUX.2-klein-4B, 512 px, 4 steps, forced split vs one card | declines
| blocks 0-11 on cuda:0, 12-24 on cuda:1, 4 calls / 156 hand-offs,
bit-identical; 0.585-0.590 vs 0.580-0.585 s/step (phantom card, wiring
only) |
| compiled split (`compile_repeated_blocks(fullgraph=True)`), tiny
FLUX.1 / Qwen-Image / Wan, prompts 2-4 | n/a | bit-identical to one
card, 0 new graphs, 0 graph breaks |
| compiled split, FLUX.2-klein-4B | n/a | not proven: Triton's HIP
launcher raised `invalid device ordinal` (101) for the phantom ordinal
while precompiling. The multiplier only wraps the HIP calls torch makes,
so this is the spoof, not the split; it needs a real second card |
| kill switch `UNSLOTH_DIFFUSION_LAYER_SPLIT=0` | no split | no split,
nothing recorded |
| head's layer split / multi-GPU test files | 38 passed, 176 errors (the
head's tests need the head's API) | 212 passed, 1 skipped, 1 failed |

The one head failure,
`test_execution_device_reports_the_primary_of_a_split_pipeline`, is the
runner's diffusers failing to import in the test process (`Failed to
import diffusers.pipelines.pipeline_utils`), and the skip is the same
import. Both pass on the CPU sweep above.

## What the spoof cannot prove

The device multiplier shows extra HIP ordinals that are the same
physical gfx1151. So this run proves wiring: selection, planning,
placement, the boundary hand-offs, bit identity, and compile with zero
recompiles. It does not prove:
- real multi-GPU memory relief (the "cards" share one pool);
- cross-card copy bandwidth or stream behaviour over a real PCIe / xGMI
link;
- any s/step figure (recorded, but phantom);
- the compiled split of a real model (blocked by the spoof above);
- mixed gfx targets on one host;
- ROCm flash_attn or AITER on a secondary;
- the Windows ROCm path on real hardware.

gfx1151 is an APU, so reaching the discrete branch at all required a
Studio-layer spoof in the harness: the memory kind reported as discrete,
and the per-card unified classifier answering discrete. The unmodified
host takes the unified decline, which is the intended behaviour on this
hardware.

## For a tester with two or more discrete AMD GPUs

```bash
# 1. CPU and two-card unit tests from the PR checkout
cd studio/backend
python -m pytest -q tests/test_diffusion_layer_split_plan.py tests/test_diffusion_layer_split_order.py \
  tests/test_diffusion_multigpu.py tests/test_diffusion_layer_split_cuda.py tests/test_diffusion_multigpu_cuda.py
# 2. Forced split on a model one card holds: Studio, select both GPUs, load FLUX.2-klein-4B with
UNSLOTH_DIFFUSION_LAYER_SPLIT=force unsloth studio
#    then check the log for "diffusion.layer_split: ... split cuda:0: N blocks ..., cuda:1: M blocks ..." and the
#    model status multi_gpu.layer_split (cards [0, 1], live.calls > 0), and that the image matches a run with
#    UNSLOTH_DIFFUSION_LAYER_SPLIT=0 (same seed)
# 3. Real need: a model larger than one card (FLUX.2-dev bf16 on 2x 24 GB), default settings:
#    status shows layer_split engaged instead of an offload policy, and s/step beats the one-card offload run
# 4. Mixed cards (for example 7900 XTX + MI300 or RDNA3 + RDNA4): the status shows which cards were used, and
#    with flash_attn installed the split stays on cards of the primary's gfx target
rocm-smi --showproductname; python -c "import torch; print([torch.cuda.get_device_properties(i).gcnArchName for i in range(torch.cuda.device_count())])"
```

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…eir learned peak (#13860)

Stacked on #13847 (learned peaks keyed on the unsloth mirror). Without
it a fresh install keys every build as `unknown`, so nothing here
engages. Merge #13847 first. Both branches now carry current main
(`c08dfbbe64`), merged cleanly.

## Problem

#13724 records a learned activation peak at every completed image
render, and `refine_plan_from_loaded_weights` reads it on the next load
to keep more of the model resident. For a dense denoiser that function
still returns before the learned lookup on main when:

- the compute dtype is bf16 (`_denoiser_compute_bytes` is None), or
- the weights are GGUF or int8 packed (`_pipe_denoisers_hold_packed`).

The early return exists because the static dense eager table was
measured on fp16 / fp32 unpacked weights only. That is a reason to skip
the table, not the learned peak, which is a real measurement of the
exact build (model revision, quant label, VAE savers, attention backend,
graphs, GPU name). These loads recorded a peak on every render that no
later load ever read: every dense load on a bf16 card (Ampere and newer)
and every GGUF image load kept the flat 8 GiB/MP estimate and streamed
the whole denoiser.

## Change

- `measured_image_runtime_mib(..., static_seed=True)`: with
`static_seed=False`, every static table is skipped and the answer comes
from the learned peak alone (None when nothing was recorded).
- `refine_plan_from_loaded_weights`: a bf16 or packed dense denoiser
sets `static_seed=False` instead of returning. With no learned peak the
lookup answers None and the flat plan stands, which is today's
behaviour. Dense loads keep the conservative branch: the whole-DiT and
wide-window pins stay torchao-only.
- The reserve the request guard reads carries the flag
(`_unsloth_measured_reserve[8]`), so a learned-only load never sizes
requests from the fp16 table. Older 8-field reserves read as before. A
layer split still drops the reserve (#14412), unchanged.
- A family that can run classifier-free guidance used to skip recording
every render without it, so Z-Image-Turbo at its default guidance 0
never learned a peak. Such a render now records under `<label>|cfg:off`.
A load reads that key only when no CFG peak exists, and marks the
reserve. The request guard then sizes any request that runs CFG, or
whose guidance mode is unknown, from the flat estimate, because the
doubled denoiser batch was never measured. Kill switch:
`UNSLOTH_DIFFUSION_LEARNED_PEAKS_CFG_OFF=0`.
- Unchanged: fp16 / fp32 dense and torchao loads, "a learned value only
raises a seed", non-CUDA and unified-memory devices (the refine is a
no-op there), and every kill switch
(`UNSLOTH_DIFFUSION_LEARNED_PEAKS=0`,
`UNSLOTH_DIFFUSION_MEASURED_ACTIVATION=0`,
`UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_DENSE=0`,
`UNSLOTH_DIFFUSION_PARTIAL_RESIDENT=0`).

## Results

Colab A100 40 GB, allocator capped, fresh VM (models downloaded from the
`unsloth/` mirrors). Base is main + #13847, head is this branch, both at
current main. Order base, head, head, base. Each arm loads twice in a
fresh Studio home: load 1 has no learned peak and records one, load 2
reads it. Median s/step of 3 renders at 1024x1024, speed tier off.

| Case | base load 1 / load 2 (arms 1, 4) | head load 1 / load 2 (arms
2, 3) | head placement on load 2 | Peak alloc base / head | Output |
|---|---|---|---|---|---|
| FLUX.2-klein-4B bf16, 10 GiB | 0.643 / 0.643, 0.641 / 0.641 | 0.643 /
**0.491**, 0.641 / **0.489** | 1943 of 7393 MiB DiT resident (learned
peak 2816 MiB reserved) | 2620 / 4397 MiB | bit-identical |
| FLUX.2-klein-4B GGUF Q8_0, 8.75 GiB | 0.687 / 0.687, 0.689 / 0.688 |
0.686 / **0.311**, 0.689 / **0.310** | 663 of 4102 MiB DiT resident |
2620 / 3245 MiB | bit-identical |
| Z-Image-Turbo GGUF Q8_0, guidance 0, 10 GiB | 0.621 / 0.623, 0.621 /
0.622 | 0.622 / **0.484**, 0.621 / **0.484** | 1946 of 6888 MiB DiT
resident, from its `cfg:off` peak | 2611 / 4562 MiB | bit-identical |
| FLUX.2-klein-4B GGUF Q8_0, 10 GiB | 0.239 to 0.241 throughout | 0.239
to 0.241 throughout | unchanged: the plan is whole-module offload, out
of scope | 4842 / 4842 MiB | bit-identical |

- Speedups on learned loads: klein bf16 1.31x, klein GGUF 2.21x, Z-Image
GGUF 1.28x. Every load without a learned peak matches base within 0.5%,
which is also the base-vs-base spread.
- No OOM in any arm. The stored keys name the mirror
(`model:unsloth/FLUX.2-klein-4B@04e0a8a...`), and the Z-Image peak is
stored with a trailing `cfg:off` part. Base records no Z-Image peak at
guidance 0.
- A local B200 run (host heavily loaded, so timings are noisy) with an
offline HF cache holding only the mirrors showed the same placements and
bit-identical images: klein GGUF 0.80 to 1.01 s/step down to 0.13, while
klein bf16 (0.148 vs 0.154) and Z-Image (0.16 to 0.19 vs 0.17) moved
within that host's noise. On a card this fast the streamed bf16 copy
hides behind compute, so the gain depends on the card's compute to PCIe
ratio.

## Tests

- `test_diffusion_learned_peaks.py`: the CFG test now asserts the
`cfg:off` key (it pinned the old skip), plus 2 new tests for the load
fallback / guard and the wiring (the wiring check is whitespace-free so
the formatter cannot break it).
- `test_diffusion_measured_placement_dense.py`: 5 new tests, all failing
without this change:
- bf16 and GGUF denoisers place from a recorded learned peak, and each
kill switch restores the flat plan.
- An fp16 load keeps its 3072 MiB table seed over a lower learned peak.
- The request guard of a learned-only load scales the learned peak and
ignores the fp16 table.
  - The load stores the flag in the reserve.
- CPU, base (main + #13847) vs this branch, over
`test_diffusion_learned_peaks.py`,
`test_diffusion_measured_placement.py`,
`test_diffusion_measured_placement_dense.py`,
`test_diffusion_small_host_planner.py`, `test_offload_planner.py`,
`test_diffusion_gguf_offload_route.py`,
`test_diffusion_stream_residency.py`, `test_video_stream_residency.py`,
`test_diffusion_offload_seed_balanced.py`,
`test_group_offload_background_pin.py`: 6 fixed, 2 new, 573 unchanged, 6
skipped (CUDA only), 0 new failures. 4 tests fail identically on main
and are not touched here (`test_background_pinner_pins_gguf_host_copies`
and three video peak persistence tests).

## Not covered

- Video: this PR changes no video path.
- LoRA loads still skip learned peaks. Runtime adapters attach after
placement, so this needs a measured per-adapter overhead term, not just
a key.
- On the default speed tier a streamed load is labelled `graphs:on` but
can render graph-free and record under `graphs:off`, so that peak is not
read back. Follow-up: re-refine after the graph decision.
- CFG requests on a load placed from a `cfg:off`-only peak are sized
from the flat estimate (resident groups stream again for that request)
until a CFG render records its own peak. Covered by CPU tests, not by a
GPU run.
- No real 8 / 10 / 12 GB consumer card, no AMD card and no Windows run:
a larger card with a capped allocator. macOS / MPS and CPU are untouched
(the refine returns before any of this on non-CUDA and unified memory).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
jasonjack-jay pushed a commit to jasonjack-jay/unsloth that referenced this pull request Oct 25, 2026
…d function (bit-identical, 1.33x streamed) (unslothai#15183)

## Summary

A streamed or offloaded denoiser on the torchao-free native int8 W8A8
path runs eager. Examples:
- FLUX.2-klein-4B int8 under a small budget;
- Wan2.2 offloaded with `speed_mode=off`.

Each linear then runs the ConvRot rotation, the activation quantise,
`torch._int_mm` and the rescale as separate kernels, with Python between
them. The render thread spends almost all its time there: py-spy puts it
in `_int_mm_rows` / `_rotate`. Under host CPU load, GPU utilisation
drops from 99% to 77%.

Why it was eager:
- unslothai#11712 left this path uncompiled on purpose: eager W8A8 already beat
compiled bf16, and the first image cost 41 s compiled against 8 s eager.
- unslothai#14412 forces compile only when the denoiser stays resident.

Compiling the whole block (the existing regional compile) is fast, but
it is not bit-identical to eager. Triton's approximate fp32 reciprocal
moves the per-row scale by one ulp and flips about 1 in 10^4 int8 codes.
LPIPS against eager is 0.0175, against a bf16 eager-vs-compiled floor of
0.0097.

## Changes

- Each eager native int8 linear on CUDA runs as one `torch.compile`'d
function of plain tensors (`_w8a8_rows`, dynamic shapes): rotation,
scale, quantise, `torch._int_mm` and rescale together.
- The function takes tensors, not the module, so the offload hooks
moving weights never invalidate the graph.
- **Bit-identical to eager:** the reciprocal is taken in fp64, which
gives exactly the eager CUDA value, so the int8 codes match bit for bit.
- **No guard churn:** inputs are detached, so guards on view bases and
Parameter shapes do not pile up. That gives 2 graphs (with and without
bias), and 8 input shapes x 4 layers still give 2.
- **Regional compile unchanged:** compiled blocks still trace the eager
code.
- **When it stays off:**
  - on ROCm and on hosts without Triton;
  - during CUDA graph capture;
  - for too few rows.
- **Fallback:** a failed compile falls back to eager once and stays
there.
- **Kill switch:** `UNSLOTH_NATIVE_INT8_FUSED=0`.

## Results

Exclusive B200, Studio pinned to 8 cores, base and head interleaved, 7
processes per arm. FLUX.2-klein-4B int8 streamed, 1024x1024, 8 steps.
The host's load average stayed at 160-385 on 192 cores, so the quiet
figure is the best phase per process.

| | base | head |
|---|---|---|
| ms / step (median of per-process best) | 103.0 | **77.6 (1.33x)** |
| A/A spread, calm processes | 102.8-103.1 (5 of 7) | 74.9-77.6 (5 of 7)
|
| wall per image, calm processes | 0.93-0.94 s | 0.71-0.76 s |
| first step, cold compile cache | 0.55-0.73 s | 2.4-2.8 s (about +2 s
compile) |
| first step, warm compile cache | - | 1.86 s |

Wan2.2-TI2V-5B, `low_vram` int8, `speed_mode=off` (one process per arm,
no A/A): 9.71 / 8.77 -> 6.72 / 6.81 s per clip (about 1.35x); first
render 55.6 -> 50.9 s.

- **Images:** bit-identical to eager, 12 of 12 (2 prompts x 6 seeds) for
klein and 3 of 3 clips for Wan 5B.
- **Compile behaviour:** 0 graph breaks, 2 graphs (one recompile at the
first no-bias layer), and 0 recompiles on follow-up seeds and prompts.
- **Under CPU contention:** 251 ms (range 170-315) on base against 229
ms (137-349) on head. The host load makes this inconclusive, so no claim
is made for it.

## Tests

- New `tests/test_diffusion_native_quant_fused.py`, CPU parts:
- the kill switch, and staying eager without an inductor runtime, on
ROCm, for CPU input and for too few rows;
- fallback after a failed compile, while an out-of-memory error
propagates;
  - detached, non-Parameter inputs to the compiled function;
  - chunking on the accumulator;
  - the fused maths tracking the eager kernels.
- The CUDA test (bit-identical to eager, with and without rotation) was
run on a GPU.
- Native quant, speed, cold start and video suites: 3089 passed, 115
skipped.

## Limits

- No contended speed claim: the shared host was too loaded.
- Not run: Wan2.2-A14B, other GPU generations, and the torch 2.6 floor
(only torch 2.14.1 was tested).
- The path only runs on bf16 CUDA targets, so a T4 (fp16) never takes
it.
- On main, the regional int8 compile drifts from eager for the same
reciprocal reason. That is not changed here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant