Skip to content

Studio diffusion: record a prompt length's CUDA graph on the first render only - #14387

Merged
danielhanchen merged 6 commits into
mainfrom
studio-diffusion-graph-text-length
Oct 20, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
studio-diffusion-graph-text-length

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

On one card, Qwen-Image's whole-step CUDA graph recorded a new graph on every new prompt length. The graph is keyed on input shapes, and Qwen-Image's text length follows the prompt, so generations 2 and 3 with new prompts each logged captured QwenImageTransformer2DModel graph 3/4 and then graph 4/4.

This PR keeps the graph but records prompt lengths only on the first render of each image scope (output resolution, batch and reference images, including FLUX.3's separate reference tensors). After that:

  • a prompt length the graph already recorded replays, as before
  • a prompt length it never recorded runs the compiled step without a graph (same kernels, same image), with no warm-up, no capture and no eviction
  • reset() (LoRA load, unload, adapter switch) reopens the window, as today
  • a graph key that also follows the step (the NVFP4 per-step precision branch, a pre-hook's branch flag) closes its scope when the first render ends rather than on its first replay, so every branch records during that render
  • a new resolution or reference layout opens its own window

With true CFG the negative prompt keeps its graph, so a new prompt still replays half of every step.

Which families

The classification is PROMPT_LENGTH_POLICY in diffusion_dynamic_text.py, the same table as the dynamic-text compile work, with one entry per denoiser class Studio loads. A test checks that every family in diffusion_families and video_families is covered.

Text length follows the prompt Padded to one length (unchanged)
Qwen-Image (incl. Edit, Layered), Qwen-Image-2.1, Z-Image (32-token buckets), FLUX.1 (256 or 512 T5 tokens), FLUX.3 (80-token buckets), MiniMax-H3 FLUX.2, Krea 2, Lumina 2, HunyuanImage 2.1, HiDream, Ideogram 4, SDXL, LTX-2, Wan, HunyuanVideo 1.5

This PR only adds the table to diffusion_dynamic_text. _FAMILY_SOURCES (what the compile arms) is unchanged, so FLUX.1 and Z-Image compile the same way they do today.

Per-block graphs (offloaded or pinned denoisers, and the per-block fallback under a step graph) decline these denoisers. A block's inputs carry the text stream, so they would record every block again for each new prompt length. Fixed-length families are untouched.

UNSLOTH_DIFFUSION_CUDA_GRAPH_EVERY_LENGTH=1 restores recording every new length, for both whole-step and per-block graphs. UNSLOTH_DIFFUSION_CUDA_GRAPH_FAMILIES still forces per-block graphs on a family.

Why not drop the graph for these families

I measured graph replay against the same compiled step run without a graph, in one process on one B200 (Qwen-Image bf16, 1024x1024, 20 steps, true CFG 4, Studio default speed mode, same prompt and seed):

Arm s/step median per round
A/A, graph every round (6 gens) 0.1413 to 0.1427
graph 0.1417, 0.1456, 0.1465
compiled, no graph 0.1710, 0.1731, 0.1837

All eight images in the A/B run have the same sha256, so replay and the ungraphed compiled step agree bit for bit. Without the graph the step was 17 to 25% slower on this host. That is not small enough to give up, so the graph stays for every prompt length it has already seen.

Padding text to buckets with masked tokens is not used, since I could not show it is bit-identical.

3-generation check

Real Qwen-Image bf16 through Studio's DiffusionBackend, one B200, default speed mode, 8 steps, prompts of 3, 15 and 63 words, then generation 1's prompt and seed again. Both trees load the same compile bundle, so the hashes are comparable across processes.

Gen Words main: captures / new dynamo graphs this PR: captures / new dynamo graphs sha256 (both)
1 3 2 / 1 2 / 1 1c5e4e76...
2 15 1 / 0 0 / 0 377e8b8f...
3 63 1 / 0 0 / 0 003a8289...
4 3 (repeat) 0 / 0 0 / 0 1c5e4e76...

There are no Recompiling lines under TORCH_LOGS=recompiles on either side. A second main run on the same bundle reproduced main's hashes.

Tests

  • test_diffusion_prompt_length_policy.py (new): every family class is classified, the variable and fixed sets, prompt_length_varies, and the compile sources are unchanged.
  • test_diffusion_cuda_graph.py: a new length after the first render records nothing (no capture begun, no warm-up, no eviction) and returns the step's own output, the negative prompt's graph keeps replaying, a repeated length replays, fixed-length families record as before, reset() reopens, the env switch, seal_lengths, and describe().
  • test_diffusion_block_graph.py: a variable-length denoiser records no per-block graphs.

23 of the new tests fail on main with only the classification table copied in. The fixed-family test passes on both. The existing graph, block graph, offload graph, speed and dynamic-text suites pass (388 passed, 42 skipped), and so does test_diffusion_qwenimage21_graph.py (9 passed, 12 skipped).

Not covered

  • s/image for generations 2 and 3 is too noisy on this shared host to quote. The host's load average was about 950 on 192 threads, and the ungraphed path is the CPU-bound one. The capture and recompile counts and the hashes are the result.
  • Qwen-Image-2.1, Z-Image, FLUX.1 and FLUX.3 were checked with unit tests only, not with real weights.
  • Offloaded placements were not run on a real model.
  • On main, FLUX.1 and Z-Image do not mark their text dims dynamic in the compile, so a new length there can still recompile. That is the dynamic-text compile change, not this PR.

…nder only

A denoiser whose text length follows the prompt (Qwen-Image, Qwen-Image-2.1,
Z-Image, FLUX.1 past 256 T5 tokens, FLUX.3, MiniMax-H3) keys its whole-step
graph on the input shapes, so every new prompt length recorded a new graph
on that render: Qwen-Image captured on generations 2 and 3.

The whole-step graph now records the lengths of the load's first render only.
After that a length it never recorded runs the compiled step ungraphed (the
same kernels, the same image) and a recorded length replays. reset() reopens
the window. Per-block graphs decline these denoisers, since a block's inputs
carry the text stream too. Fixed-length families are unchanged.

The classification is PROMPT_LENGTH_POLICY in diffusion_dynamic_text, the same
table as the dynamic-text compile work. UNSLOTH_DIFFUSION_CUDA_GRAPH_EVERY_LENGTH=1
restores recording every new length.
@danielhanchen danielhanchen self-assigned this Oct 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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 ⚠️ Failed 2026-10-20T19:36:54.024368Z
We couldn’t complete this review. Comment @codex review to try again.
e24cce2 New commits
🔒 Security Review ⚠️ Failed 2026-10-20T18:36:34.288130Z
We couldn’t complete this review. Comment @codex security review to try again.
c1fca01 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.

@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: c1fca01ba0

ℹ️ 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 +1127 to +1129
if getattr(self, "length_sealed", False) and (
self.placement is None or key not in self._recorded
):

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 Preserve captures for non-text shape changes

When a variable-length family is rendered later at a different resolution or batch size, graph_key changes even if the prompt length is unchanged, but this condition treats every unseen key as a new prompt length and permanently runs it ungraphed. Thus a normal resolution or batch-size change loses the CUDA-graph speedup for that shape; sealing must distinguish the text-length component from other graph-key dimensions.

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 0424c79184. The seal treated every unseen graph key as a new prompt length, so a render at a new resolution, batch size or reference image ran ungraphed for the rest of the load. The seal is now kept per image scope, the shape key of the denoiser call's first argument, which is the latents for every variable-length family. A first-seen scope records its first render within the slot budget as before this PR, and only a new prompt length at an already sealed scope runs the compiled step ungraphed. test_a_new_resolution_still_records_after_the_seal covers it.

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.

The fix landed on the branch as 801fa3b (rebased over the pre-commit.ci commit).

"HiDreamImageTransformer2DModel": FIXED_LENGTH, # T5 / Llama padded to max_sequence_length 128
"Ideogram4Transformer2DModel": FIXED_LENGTH, # token ids left-padded into max_sequence_length 2048
"UNet2DConditionModel": FIXED_LENGTH, # CLIP padded to 77
"MiniMaxH3Transformer3DModel": _MINIMAX_H3_SOURCES,

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 Seal forced H3 graphs after a video render

When MiniMax-H3 CUDA graphs are force-enabled and the first video uses the API-supported steps=1, the only denoiser call captures a graph but never reaches the cache-hit branch that sets length_sealed. The successful video path in video.py never calls seal_lengths (only the image backend does), so each subsequent one-step video with a new prompt length performs another expensive capture instead of limiting capture to the first render.

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.

MiniMax-H3 does not use CUDA graphs on the video path: video families default to supports_cuda_graph=False and H3 does not opt in, so the default path never builds a graph for it. The video families that do graph pad text to a fixed length and are not sealed at all. The case needs UNSLOTH_DIFFUSION_CUDA_GRAPH_FAMILIES (a measurement override) plus 1-step videos, since any render of two or more steps seals on its first replay, and in that setup a new length captured every render before this PR too. If H3 ever graphs by default, the video backend should call seal_lengths at the end of a render as the image backend does.

Comment on lines +2062 to +2063
if getattr(handle, "length_varies", False) and int(handle.stats.get("captures", 0)) > 0:
handle.length_sealed = True

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 Require a post-reset capture before resealing

After reset() clears the graph cache, this check still reads the lifetime captures counter. For a planned graph such as Qwen-Image-2.1, a short first render with a new key may perform only the shape-warmup path and end before recapturing; seal_lengths then sees an old capture, seals the empty cache, and every later call for that key runs eager forever. Track captures since the reset, or require a currently cached graph, so reset actually reopens the recording window.

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.

Agreed, fixed in 0424c79184. seal_lengths read the lifetime capture counter, so a first render after reset() that recorded nothing sealed an empty cache and that key ran ungraphed until the next reset. reset() now clears per-scope capture counts, and seal_lengths only seals a scope this render used that recorded since the last reset. test_a_render_with_no_capture_after_reset_does_not_seal covers it.

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.

The fix landed on the branch as 801fa3b (rebased over the pre-commit.ci commit).

… since reset

The first-render seal treated every unseen graph key as a new prompt length,
so a later render at a new resolution or batch size ran ungraphed for the rest
of the load. The seal is now kept per image scope (the key of the call's first
argument, the latents), so a new resolution, batch or reference image records
its first render as before, and only a new prompt length at a sealed scope
runs the compiled step ungraphed.

seal_lengths also read the lifetime capture counter, so a first render after
reset() that recorded nothing (a bypassed render, or a planned step that only
warmed up) sealed an empty cache. It now seals only scopes that recorded since
the last reset.
@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: 801fa3b98b

ℹ️ 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 +1149 to +1150
if scope in getattr(self, "_sealed_scopes", ()) and (
self.placement is None or key not in self._recorded

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 evicted resident graphs to be recaptured

When a resident planned denoiser such as Qwen-Image-2.1 has used more than max_graphs keys, the planned-path LRU eviction removes an older cache entry but leaves its scope sealed and its key in _recorded. Returning to that earlier resolution and prompt then reaches this condition, where self.placement is None forces the key to run eager forever instead of allowing the planned graph to be recaptured. Previously recorded keys should bypass the length seal regardless of placement, or their scope should be reopened when they are evicted.

Useful? React with 👍 / 👎.

Comment on lines +1243 to +1246
if scope is not None:
# Every text length of this scope's render was seen on its first step (cond and uncond alike).
self._render_scopes.add(scope)
self._sealed_scopes.add(scope)

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 Seal scopes only after step-dependent branches are captured

When NVFP4 protection is enabled with a normal multi-step schedule such as 0,1,2,3,-1, the first protected call captures a graph and the next protected step hits it here, sealing the scope before the unprotected branch is encountered. Once the controller changes branches, protect_graph_key produces a new key, but the sealed miss is forced eager, so most denoising steps never receive the second graph even though the cap was doubled specifically for both branches. Defer sealing until the render completes, or otherwise ensure all step-dependent key variants can capture during that first render.

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 acdaa97. A key that also follows the step (NVFP4 protect branch, or a pre-hook's branch flag) no longer seals its scope on replay; the scope seals when the render ends via seal_lengths, so every branch records during the first render. Test: test_a_step_dependent_key_seals_only_when_the_render_ends.

Comment on lines +73 to +74
first = args[0] if args else next(iter(kwargs.values()), None)
return graph_key(first)

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 Include separate reference tensors in the image scope

For FLUX.3 image-conditioned renders, the output latents remain the first argument while image_cond_hidden_states and image_cond_ids are passed separately, so changing the number or resolution of reference images does not change this scope. After a text-only or differently conditioned render seals the same output-resolution scope, the new reference layout has a different full graph key but is forced eager forever. Fresh evidence in the pinned FLUX.3 denoise path shows these reference tensors are forwarded separately rather than concatenated into hidden_states; build the scope from all non-text shape inputs instead of only the first tensor.

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 acdaa97. The image scope now includes image_cond_hidden_states / image_cond_ids when passed, so a new reference layout at the same output size records its first render. Test: test_separate_reference_images_are_part_of_the_image_scope.

Comment on lines +1960 to +1961
if _family_forced(family):
return None

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 Apply the every-length override to block graphs

When UNSLOTH_DIFFUSION_CUDA_GRAPH_EVERY_LENGTH=1 is set, _length_varies restores the old whole-forward behavior, but this predicate still classifies the same denoiser as variable-length and causes arm_block_graphs to reject its per-block graphs. Consequently, an offloaded or otherwise block-only FLUX.1, FLUX.3, Qwen-Image, or Z-Image load remains ungraphed despite the new switch promising to record every prompt length as before. Treat this override like the family-force override here so it applies consistently to both graph modes.

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 acdaa97. prompt_length_reason now returns None under UNSLOTH_DIFFUSION_CUDA_GRAPH_EVERY_LENGTH=1, the same as the family force, so block graphs arm again. Test: test_the_every_length_switch_keeps_block_graphs.

…reference images, honour the every-length switch for block graphs

[skip ci]
[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. Nice work!

Reviewed commit: 21dc909d8f

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

[skip ci]
@danielhanchen
danielhanchen merged commit c6d77f2 into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-graph-text-length branch October 20, 2026 20:13
danielhanchen added a commit that referenced this pull request Oct 22, 2026
…ss renders and pin torchao int8 host weights (#14666)

## Summary

Under `memory_mode=low_vram` (whole-module CPU offload) on a compiled
speed tier, the denoiser step now runs as a CUDA graph on every render,
recorded once on render 1, and the int8 weights the compiled tier stores
stop being copied back and forth through pageable host memory on every
render.

Four commits:

1. **Stable device range for a model-offloaded denoiser**
(`diffusion_stable_arena.py`). The denoiser's onloads land in one CUDA
virtual address range reserved for the load (driver VMM:
`cuMemAddressReserve` once, then `cuMemCreate` + `cuMemMap` on every
onload and `cuMemUnmap` + `cuMemRelease` on every offload). The weights
get the same addresses on every render, so render 1's step graph replays
on renders 2+ with no new capture. The physical memory is still released
at every offload, so the text encoder and VAE phases get the VRAM back
as they do today. This is the same idea as ComfyUI's `comfy_aimdo`
`model_vbar`. #14497 kept this placement eager because the stock onload
moved the weights on every render. `offload_placement()` now arms the
graph only when the range attaches;
`UNSLOTH_DIFFUSION_MODEL_OFFLOAD_ARENA=0` brings back #14497's eager
step.
2. **Keep and pin torchao int8 / fp8 host weights under model offload**
(`diffusion_memory.py`). The keep-host-weights offload skipped torchao
wrapper weights (`Int8Tensor`). Every render then copied them
device-to-host into fresh pageable memory and uploaded them again from
there. On FLUX.2-klein 4B only 0.5 of 4 GiB of the denoiser was pinned.
Wrapper weights whose inner tensors are plain are now kept: the offload
swaps the parameter back onto its kept host tensors (no copy), and their
inner tensors are pinned on the first onload.
3. **Int8 / fp8 weights in the stable range.** Each inner tensor is
placed in the range, and the weight is rebuilt over the placed tensors
and swapped in, the same way `Module.to` moves it.
4. **Survive diffusers re-hooking.** accelerate's
`remove_hook_from_module` pops instance `to` overrides
(`_accelerate_added_attributes`), and diffusers re-hooks model offload
before every render. Without this commit the range served only render 1.
A forward pre-hook now puts the override back before the hook's
pre-forward onloads the module.

The existing offload speed check still judges each recorded key. A
replay has to be at least 1% faster than the eager step, or the graph is
dropped for the load. That covers the devices where a replay does not
pay.

## Numbers

Studio `begin_load` + `generate`, `memory_mode=low_vram`,
`speed_mode=default` (auto int8), 1024^2, 4 prompts (new text length and
seed each time, guidance change on 4), B200. Base = main `465e0c8d27`,
head = this branch. The host was heavily loaded during these runs (load
average 1100-2000), so wall times are not comparable across processes.
The counters are exact, and the same-process eager vs replay timings are
fair.

| | klein 4B base | klein 4B head | Z-Image base | Z-Image head |
|---|---|---|---|---|
| step graph armed | no (#14497 reason) | yes, over the stable range |
no | yes |
| captures, render 1 / renders 2-4 | 0 / 0 | 1 / 0, 0, 0 | 0 / 0 | 1 /
0, 0, 0 |
| replays per render, renders 2-4 | 0 | 4 of 4 each | 0 | 0 (new text
lengths: #14387 records lengths on render 1 only) |
| graph invalidations | - | 0 | - | 0 |
| denoiser host weights pinned | 0.5 of 4 GiB | 4.0 GiB | 0.2 of 6 GiB |
6.0 GiB |
| same process: eager step vs replay | - | 26.5 vs 20.3 ms | - | 158.5
vs 94.7 ms |
| peak allocated / reserved MiB | 6073 / 6088 | 6115 / 6936 | 7704 /
7716 | 7800 / 8442 |
| output | | | | same sha256 as base on all 4 renders |

Same-process A/B on head Z-Image at 512^2, 8 steps, same prompt and
seed. The replay ran at 31.7 ms per denoiser call. The same compiled
step with the graph bypassed ran at 86.8 ms (min 56.0). Wall per render
was 35.6 s against 57.6 s, and the image sha was identical in both
modes. Wan 2.2 5B low_vram (480x832, 17 frames): armed over a 4848 MiB
range, speed check 54.1 ms eager vs 21.1 ms replay.

The first denoiser call of a render includes the onload. On base it took
26-58 s on every klein render: the int8 weights were uploaded from
pageable memory after a device-to-host copy. Head klein render 3 took
0.195 s. Renders 2 and 4 took 109 s and 149 s while the host was
stalling, so treat the onload time as unmeasured here.

Quiet-host check, Colab A100 40 GB. Studio was installed by `install.sh`
at `465e0c8d27`; "new" adds the four commits.
FLUX.2-klein-4B, `low_vram`, speed default (auto int8), 1024^2, 4 steps.
Renders 2-4 (render 1 compiles):

| arm | wall per render | first denoiser call (incl. onload) | ms per
denoiser call | captures 2-4 | replays per render | sha vs base |
|---|---|---|---|---|---|---|
| base (main) | 4.71-4.79 s | 1.27-1.32 s | 114.0 | 0 | 0 | - |
| head with `UNSLOTH_DIFFUSION_MODEL_OFFLOAD_ARENA=0` (commit 2 only:
int8 kept + pinned) | 1.91-1.92 s | 0.66 s | 114.2-114.6 | 0 | 0 |
identical on all 4 |
| head (all four commits) | 1.87 s | 0.62 s | 113.1-113.9 | 0 | 4 of 4 |
differs (66 dB PSNR vs base on the B200 images; in-process graph vs no
graph is identical) |
| base, speed off | 2.45-2.74 s | 1.00-1.06 s | 174 | 0 | 0 | - |

On main the compiled low_vram tier was slower per render than speed off
(4.7 s vs 2.5 s) because of the int8 re-copy.
The head is 2.5x faster than main and 1.3x faster than speed off. On a
quiet A100 the graph itself adds about 1-2%:
in-process, 512^2 is 33.0 vs 33.5 ms per call and 1024^2 is 114.1 vs
114.4 ms, bit-identical. Most of the per-render
win comes from commit 2. The graph's large gains on the loaded B200
(Z-Image 512^2: 31.7 vs 86.8 ms) come from CPU launch
overhead, which graphs remove. That is real for a CPU-starved machine,
but it is not the quiet-host number.

The graph pool lives across renders. That costs about 0.85 GiB reserved
on klein and 0.6 GiB on Z-Image, held during the text encoder and VAE
phases. The range itself is released at every offload.

## Tests

- New:
`test_model_offload_replays_over_the_stable_range_and_frees_it_between_renders`,
`test_model_offload_stable_range_holds_torchao_int8_weights`,
`test_torchao_int8_weights_keep_their_host_storage_and_are_pinned[0|1]`.
Updated:
`test_model_offload_records_nothing_after_the_first_render[False]` (main
arms nothing there; it now arms the graph and records 0 captures on
renders 2+), and
`test_model_offload_keeps_the_step_eager_without_the_stable_range`
(#14497's eager test, now with the range turned off).
- Base (main) with the head tests: both
`test_torchao_int8_weights_keep_their_host_storage_and_are_pinned` cases
fail (the host tensors change on every render). The stable-range tests
cannot import on main, because the module does not exist there.
- Head, GPU: `test_diffusion_offload_keep_cpu.py` 39 passed.
`test_diffusion_offload_cuda_graph.py -k "model_offload or
stable_range"`: all passed, including re-hooking between renders the way
diffusers does, and torchao int8.
- CPU sweep over `test_diffusion_memory`, `test_diffusion_block_graph`,
`test_diffusion_offload_step_graphs`, `test_diffusion_multigpu`,
`test_diffusion_offload_precision` and
`test_diffusion_offload_keep_cpu`: base 499 passed / 1 failed / 63
skipped, head 499 passed / 1 failed / 65 skipped. The one failure has
the same ID on both
(`test_execution_device_reports_the_primary_of_a_split_pipeline`, a
diffusers / huggingface_hub import mismatch in that environment). The
two extra skips on head are the new CUDA tests.
danielhanchen added a commit that referenced this pull request Oct 22, 2026
…s not recompile on a long prompt or new size (#14689)

## Summary

On the default speed tier FLUX.1 (schnell / dev / Krea-dev, and Kontext,
which uses the same `FluxTransformer2DModel`) recompiles both repeated
blocks on follow-up prompts:

- the first prompt longer than 256 T5 tokens (Studio pads T5 to 256, or
512 for a longer prompt), and
- the first render at a new resolution.

The default load picks int8 for FLUX.1, and a torchao denoiser compiles
with automatic dynamic (`compile_dynamic` returns `None`), so the first
compile is static and the first new text length and the first new image
size each pay a generalising recompile. #14387 classified FLUX.1's
prompt-length inputs in `PROMPT_LENGTH_POLICY` but left them out of
`_FAMILY_SOURCES` ("a new length there can still recompile. That is the
dynamic-text compile change, not this PR"). This is that change for
FLUX.1: its block inputs are armed from the first forward, as FLUX.3 and
Qwen-Image already are.

## Measured (real weights, unsloth/FLUX.1-schnell, default settings, one
process, B200, torch 2.13)

Follow-up sequence on the Images defaults (speed unset, memory auto,
which resolves to int8 + regional compile + CUDA graphs):

| render | main | this PR |
|---|---|---|
| first render (compile + capture) | 2 graphs, 1 capture | 2 graphs, 1
capture |
| repeat, seed change, guidance change | 0 / 0 | 0 / 0 |
| prompt past 256 T5 tokens | **2 recompiles, 31.6 s** | 0 recompiles,
3.0 s, same image bytes as main |
| new resolution 768x1280 | **2 recompiles + 1 capture, 60.3 s** | 0
recompiles + 1 capture (new size, by design), 23.4 s, same image bytes
as main |
| batch 2 | 2 recompiles + 1 capture (batch 1 is specialised) |
unchanged (batch size is not a prompt-length input) |

Recompile reasons on main: `tensor 'image_rotary_emb[0]' size mismatch
at index 0. expected 4352, actual 4608` (text 256 to 512) and `tensor
'hidden_states' size mismatch at index 1. expected 4096, actual 3840`
(new resolution).

Images: the long-prompt, new-resolution and batch-2 renders are
byte-identical to main's (main ran the same generalised graph after
recompiling). The first render now runs that dynamic graph from the
start instead of main's static first graph: against the speed-off bf16
render of the same seed, LPIPS-alex 0.054 here vs 0.035 on main (one
image; main's own long-prompt render is 0.119 and its new-resolution
render 0.082 against bf16, so this is inside the int8 default's spread).
Renders whose prompt length matches the first one differ from main's by
LPIPS 0.01-0.03 on simple scenes and up to 0.22 on a dense night-market
scene, same composition (kernel numerics of the static vs dynamic
graph).

The host was heavily loaded (load average above 1000), so the wall times
above are what one user saw on that host, not a clean benchmark; the
recompile and capture counts are the result.

## Changes

- `diffusion_dynamic_text._FAMILY_SOURCES`: add `FluxTransformer2DModel:
_FLUX1_SOURCES` (the sources #14387 already defined). Only
automatic-dynamic compiles arm them (`install` with `dynamic=None`), so
a bf16 FLUX.1 (`dynamic=True`) and a static compile are unchanged.
- Tests:
`test_flux1_new_prompt_length_and_resolution_reuse_the_first_graphs` (a
two-block FLUX.1 stand-in compiled with automatic dynamic: unarmed it
compiles again on a new text length and on a new image length; armed,
the first compile covers both). Fails on main (`install` arms nothing),
passes here. The policy test now lists FLUX.1 among the armed classes.

## Testing

- `pytest tests/test_diffusion_dynamic_text.py
tests/test_diffusion_prompt_length_policy.py`: 33 passed (the new test
fails on main).
- Real-weights follow-up sequence above, main vs this branch, same host,
same seeds.

## Not covered

- Z-Image is still classified but not armed: its bf16 default compiles
with `dynamic=True` and did not recompile in the same sequence; an int8
Z-Image (bf16 does not fit) was not run here.
- FLUX.1-dev and Krea-dev were not run with real weights (same
transformer class and block code as schnell).
danielhanchen added a commit that referenced this pull request Oct 22, 2026
…8 compile (#14715)

## Summary

An int8 Z-Image-Turbo, which is what the default load picks when bf16
would not fit (a 12 GB card here: int8 + group offload), compiles with
automatic dynamic (`compile_dynamic` returns `None` for torchao
weights). Its one block class runs the caption refiner (caption tokens),
the noise refiner (image tokens) and the main layers (caption + image),
so on main:

- the first render recompiled the block for each of those lengths: 17
graphs, 12 recompiles (`tensor 'x' size mismatch at index 1. expected
4096, actual 32`), and
- the first longer prompt recompiled again (`tensor 'x' size mismatch at
index 1. expected 32, actual 256`: the caption is padded to 32-token
buckets).

#14387 classified Z-Image's prompt-length inputs in
`PROMPT_LENGTH_POLICY` but left them out of `_FAMILY_SOURCES`. This arms
them, as FLUX.3 and Qwen-Image already are, so a longer prompt reuses
the first compile instead of recompiling.

A bf16 Z-Image (resident, `dynamic=True`) is unchanged: `install` arms
sources only for an automatic-dynamic compile, and that path already
showed 0 recompiles on the same follow-up sequence.

## Measured (real weights, Tongyi-MAI/Z-Image-Turbo, defaults on a 12
GiB card, one process, B200, torch 2.13)

Follow-up sequence, main vs this branch, same process layout (speed
unset, memory auto, which resolves to int8 + group offload + regional
compile + CUDA graphs on this card):

| render | main | this branch |
|---|---|---|
| first render | 17 graphs, **12 recompiles**, 1 capture | 13 graphs, 7
recompiles, 1 capture |
| repeats, guidance, seed change | 0 / 0 | 0 / 0 |
| ~190-word prompt | **1 recompile** (`x` 32 to 256) | **0** |
| new resolution, back to 1024 | 0 recompiles, 1 capture | 0 recompiles,
1 capture |

Every image is bit-identical between main and this branch (same sha256
prefixes for the first render, the long prompt, the seed change, the new
resolution and the return to 1024).

The 7 first-render recompiles left on this branch are one-time and come
from inputs this change does not arm: the refiners pass
`adaln_input=None` where the main layers pass a tensor (a different
graph by construction), and `freqs_cis` reaches the attention processor
through `cross_attention_kwargs`. No later render recompiles.

The host was heavily loaded (load average above 1000), so wall times are
what one user saw on that host; the recompile and capture counts are the
result.

## Changes

- `diffusion_dynamic_text._FAMILY_SOURCES`: add
`ZImageTransformer2DModel: _ZIMAGE_SOURCES` (the sources #14387 already
defined).
- Tests: `test_zimage_new_caption_bucket_reuses_the_first_graphs` (a
Z-Image block stand-in compiled with automatic dynamic, called with
caption, image and unified lengths: unarmed it compiles more than once
in the first render, armed it compiles once and never again across
caption buckets and image sizes). Fails on main (`install` arms
nothing), passes here. The policy test now lists Z-Image among the armed
classes.

## Testing

- `pytest tests/test_diffusion_dynamic_text.py
tests/test_diffusion_prompt_length_policy.py`: 33 passed (the new test
fails on main).
- Real-weights sequence on main and on this branch above (B200 under a
12 GiB cap, one process per tree).

## Not covered

- Turning CFG on (guidance 0 to 3.5) on the offloaded int8 load still
compiles the batch-2 shape once (Z-Image's CFG split is off when the
denoiser streams, by design: two calls would upload it twice per step).
- FLUX.1 is the same gap and is handled separately.
danielhanchen added a commit that referenced this pull request Oct 23, 2026
…le-diffusion.cpp) (#14552)

## Summary

Adds MOSS-Image (`OpenMOSS-Team/MOSS-Image-SFT` and
`OpenMOSS-Team/MOSS-Image-Base`) to Unsloth Studio as an image family.

The official repos ship the transformer and scheduler as remote code
(`model_index.json` points both at the repo's `pipeline_moss_image.py`),
and diffusers has no MOSS-Image pipeline. Studio never runs repo code,
so this PR ports the model in tree
(`core/inference/diffusion_moss_image.py`, from the Apache-2.0
reference) and assembles the pipeline per component from safetensors and
JSON only. No `trust_remote_code`, no `custom_pipeline`.

## What is supported

- Text to image on both repos, through the normal Images load path
(`begin_load` / `generate`), from a repo id or a local diffusers folder
(detected from `model_index.json` `_class_name`).
- Components: the in-tree `MOSSImageTransformer` (state-dict keys
identical to the repo's), the Qwen3.5-9B text encoder
(`transformers.Qwen3_5Model`, vision tower dropped at load), the FLUX.2
small-decoder VAE (`diffusers.AutoencoderKLFlux2`) and the tokenizer.
SFT and Base share every file except the transformer shards (checked by
sha256 on the Hub), so one family row serves both.
- Every component is fetched from `unsloth/*`, as for FLUX.3: the
upstream diffusers files (`model_index.json`, `pipeline_moss_image.py`,
`scheduler/`, `text_encoder/`, `tokenizer/`, `transformer/`, `vae/`) sit
byte for byte in `unsloth/MOSS-Image-SFT-FP8` and
`unsloth/MOSS-Image-Base-FP8` beside the quantised files
(`_UNGATED_MIRROR_PAIRS`, `_ARTIFACT_MIRRORS`). The `OpenMOSS-Team` ids
stay the family's base ids and provenance; a user's complete cached
upstream snapshot keeps being used, as for every ungated mirror.
- Needs transformers >= 5.3 for the text encoder. Older transformers
hides the family from the picker and a load is refused with a clear
message (`in_tree_pipeline_refusal`).
- Memory modes: resident, model offload and group offload (block-level
denoiser, leaf-level encoder streaming). Qwen3.5's gated-delta layers
read `conv1d.weight` straight into the causal-conv kernel without
calling the module, so leaf-level group offload never onloaded it
(device mismatch on the first prompt). A pre/post hook on each
gated-delta layer now onloads and offloads that conv; leaf-level offload
output is bit-identical to resident with and without CUDA streams.
- Quantised builds: INT8-ConvRot, INT8 and FP8 denoisers for SFT and
Base and an int8 ConvRot text encoder shared by both, seeded into the
per-component assembly (section below). When the hosted repos cannot be
reached, a load quantises at runtime with the same spec.
- GGUF on the native stable-diffusion.cpp engine (section below). A MOSS
GGUF loads only there, on every backend, from a build that has MOSS
(upstream master-975 or newer).
- Not in this PR: single-file safetensors transformer picks and GGUF
through diffusers (see the GGUF section), LoRA, image conditioning (the
released pipeline is text to image only).

## Defaults vs ComfyUI

| knob | ComfyUI (MOSS workflow / native support) | Studio | reference
pipeline |
|---|---|---|---|
| size | 1024x1024 | 1024x1024 | 1024x1024 |
| steps / CFG | 50 / 3.0 | 50 / 3.0 | 50 / 3.0 |
| sampler | euler | Euler (flow matching) | Euler |
| sigmas | `sgm_uniform`, shift 5 | `sgm_uniform`, shift 5 (default) |
shift 5 snapped to the 1000-point training grid
(`UNSLOTH_MOSS_SIGMAS=training_grid`) |
| guidance trick | SkipLayerGuidanceDiTSimple, block 22, uncond only,
0..1 | uncond skips block 22 | uncond skips block 22 |
| negative prompt | empty | empty | empty |
| seed noise | CPU fp32 `randn` from the seed | CPU fp32 `randn` from
the seed | fp32 `randn_tensor` with the caller's generator |
| DiT / text encoder dtype | bf16 (fp16 not supported) | bf16, fp16
promoted (`fp16_incompatible`) | bf16 |
| VAE decode | fp32 | fp32 | fp32 |

## Numerics

| check | result |
|---|---|
| port vs the repo's `pipeline_moss_image.py`, tiny random model (CPU):
sigmas, timesteps, prompt encoding, forward with skip layers, masked
batch of 2, full pipeline with CFG + skip 22, no CFG, plain CFG, extra
SLG, 2 images per prompt | bit-identical in every case |
| port vs the official pipeline, real SFT weights, 1024x1024, 50 steps,
4 prompts, same noise (B200) | bit-identical, 4 of 4 |
| Studio speed off vs the plain eager port, real weights, 12 prompts |
bit-identical, 12 of 12 |
| eager port A/A (same prompt twice in one process) | bit-identical |

## Speed and memory

Exclusive B200, 1024x1024, 30 steps, CFG 3, bf16, transformer quant off,
resident placement. Three rounds per arm, each a fresh process, arms
interleaved; s/step is the median of warm steps (scheduler-step deltas,
synced). Prompt 1 is the first render, prompt 2 a new prompt length,
prompt 3 prompt 1 again.

| arm | s/step, prompt 1 (3 rounds) | s/step, new length | s/step,
repeat | peak allocated |
|---|---|---|---|---|
| speed off (the eager port) | 0.1966 / 0.1974 / 0.1973 | 0.1981 /
0.1973 / 0.2039 | 0.1966 / 0.1974 / 0.1968 | 28.09 GiB |
| speed default (regional compile + CUDA graphs + cuDNN attention) |
0.0874 / 0.0874 / 0.0871 | 0.0875 / 0.0872 / 0.0873 | 0.0875 / 0.0870 /
0.0874 | 27.26 GiB |

2.26x faster per step at the default tier, 0.83 GiB lower peak. The
first render in a fresh process takes 17 to 43 s at the default tier
(compile, partly served from the compile cache) against 9 to 17 s eager;
later renders take about 2.9 s for 30 steps against 6.2 s.

Compile, graphs and prompt lengths (real weights, 1024x1024, 50 steps,
14 prompts of 8 to 18 words with seeds 1001 to 3002 and CFG 2.5 / 3 /
4.5, then prompt 1 again):

| | prompt 1 | prompts 2 to 14 | prompt 1 again |
|---|---|---|---|
| dynamo graphs compiled | 2 (`_Block`, `_TextBlock`) | 0 | 0 |
| graph breaks | 0 | 0 | 0 |
| recompiles | 0 | 0 | 0 |
| CUDA graph captures | 2 (cond and uncond lengths) | 0 | 0 |

The text length is armed dynamic from the first compile
(`PROMPT_LENGTH_POLICY` / `_FAMILY_SOURCES`), so a new prompt length
never recompiles, and under the existing first-render-only graph policy
(#14387) a new length runs compiled without a graph. The two cost the
same here (0.0872 to 0.0875 s/step either way), so the policy gives
nothing up on MOSS. Same counts under group offload (the denoiser
streamed per block, the encoder per leaf).

Accuracy against the eager bf16 port (12 prompts: 8 calibration + 4 held
out, 1024x1024, 50 steps, same seeds, LPIPS alex):

| arm | LPIPS mean | LPIPS max |
|---|---|---|
| speed off | 0 (12 of 12 pixel-identical) | 0 |
| speed default (compile + graphs + cuDNN attention) | 0.020 | 0.052 |
| speed default with native SDPA, group offload | 0.026 | 0.098 |
| speed eager (cuDNN attention, no compile), for scale | 0.032 | 0.157 |

Swapping only the attention kernel moves a 50-step CFG render further
than the compiled blocks do, so the compiled default sits inside the
kernel-noise floor of this model.

What each lever is and what it gave:

| lever | status |
|---|---|
| regional compile | `_repeated_blocks = ["_Block", "_TextBlock"]`;
2.26x per step, 0 breaks, 0 recompiles |
| dynamic text length | on from day one; 0 recompiles across 14 prompt
lengths |
| CUDA graphs | whole step, cond and uncond; skip layers passed as a
tuple so the uncond call is capturable; the forward takes no host sync
without a mask |
| attention backend | attention goes through diffusers' dispatcher, so
Studio's backend pick (cuDNN on NVIDIA) reaches it |
| text refiner cache | the 2-block text refiner runs once per prompt per
render, not per step and branch; bit-identical (tiny model), kill switch
`UNSLOTH_MOSS_TEXT_CACHE=0`; off under offload hooks |
| RoPE | tables built once per (size, prompt length) instead of per
forward; bit-identical. Inside the compiled block inductor fuses the q/k
RMSNorm and the split-half rotation |
| prompt-embedding cache | Studio's prompt cache wraps `encode_prompt`
(the empty negative is cached too) |
| cudnn.benchmark | off for this family: on the fp32 VAE decode its plan
search took 254 s and a 73 GiB transient workspace on the first
1024x1024 decode, then picked a 4x slower plan (0.34 vs 0.08 s warm) |
| offload | resident, group and model offload render pixel-identical to
resident in eager mode (tiny model) |
| CFG batching | not done: cond and uncond run at different text lengths
with different RoPE positions (the image sits after the text on the f
axis), so batching needs padding plus masks in both the refiner and the
joint blocks and cannot be bit-identical; ComfyUI also runs the branches
separately. A hand-written fused RoPE kernel was not added either, since
the compiled path already fuses it |

## Quantised builds

Keep-list for every scheme (`_MOSS_IMAGE_QUANT_KEEP`): the whole
`text_embedder` (projection and its 2 refiner blocks), `time_embedding`
and the AdaLN modulations (`shared_block_modulation`,
`video_head_modulation`) stay bf16; the 252 block Linears
(`proj.q/k/v/o/ffn_up_gate/ffn_down`) quantise. `video_embedder` and
`final_linear_video` sit under the 512-feature floor and stay bf16 too.
int8 rotates those 252 Linears with ConvRot at group 256
(`int8_convrot`, on by default). These are the settings the hosted files
were built with, so a runtime quantise and a hosted file build the same
module layout (renders compared below).

| repo | files |
|---|---|
| `unsloth/MOSS-Image-SFT-FP8` |
`MOSS-Image-SFT-INT8-ConvRot.safetensors`,
`MOSS-Image-SFT-INT8.safetensors`, `MOSS-Image-SFT-FP8.safetensors`,
`MOSS-Image-SFT-text_encoder-INT8-ConvRot.safetensors` |
| `unsloth/MOSS-Image-Base-FP8` |
`MOSS-Image-Base-INT8-ConvRot.safetensors`,
`MOSS-Image-Base-INT8.safetensors`, `MOSS-Image-Base-FP8.safetensors` |

- Default denoiser (GPU, `transformer_quant` unset): the bf16 DiT while
it fits (`auto_bf16_when_resident`, the small-DiT rule FLUX.2-klein,
Z-Image and FLUX.3-klein follow). When bf16 would offload, auto falls
back to INT8-ConvRot, then plain INT8 from the same repo. An explicit
precision is honoured.
- fp8 and mxfp8 are removed from the family's automatic order (new
`FamilyProfile.auto_scheme_skip`) and stay explicit picks. The quant
track measured fp8 at LPIPS 0.163 against 0.058 for INT8-ConvRot.
- Default text encoder (`text_encoder_quant` unset): the int8 ConvRot
encoder. ComfyUI's official MOSS-Image templates (SFT and Base) load
`qwen3.5_9b_w4a8_gptq` (4-bit weights) with an `int8_convrot` DiT. Their
encoder is not bf16 or fp8, and int8 weights are the nearest class at
higher precision. `text_encoder_quant=none` keeps the dense bf16
encoder.
- Base: its own denoiser builds (variant repo rows; any other scheme on
Base quantises Base's weights, never SFT's file). The Base files record
family `moss-image-base`, which the quant tables now answer to
(`quant_names`). SFT and Base ship identical `text_encoder/` shards, so
Base reuses the SFT encoder file through a `_TE_EQUIVALENT_BASES` group.
- Text encoder: Qwen3.5-9B (`Qwen3_5Model`) with the MLP and
full-attention projections int8 (128 Linears), 11.49 GB against 16.79 GB
dense; budgeted at 0.69 of dense. The vision tower in the file is
dropped at load and the gated-delta offload guard is installed on a
handed-in encoder as on a dense one.
- Hosted repos absent or unreachable: the seed finds nothing, the
released denoiser is loaded and quantised at runtime (INT8-ConvRot, same
spec), and the automatic text-encoder pick keeps the dense bf16 encoder;
an explicit request is reported as falling back. Covered by tests with
an empty offline cache.

Real weights, hosted files served through
`UNSLOTH_DIFFUSION_PREQUANT_MIRROR` (measured before the upload),
1024x1024, 50 steps, speed default, 14 prompts (seeds 1001 to 3002, CFG
2.5 to 4.5), B200 shared card:

| arm | what loaded | LPIPS vs eager bf16 port, mean / max | peak
allocated |
|---|---|---|---|
| bf16 (transformer quant off) | dense | 0.025 / 0.156 | 27.26 GiB |
| SFT default (new): bf16 DiT kept by auto, hosted int8 encoder | dense
DiT (269 bf16 Linears, `transformer_quant=off(auto)`, resident) + int8
encoder (128 int8 Linears) | 0.036 / 0.164 | 22.33 GiB |
| SFT INT8-ConvRot (previous default; now the offload fallback), hosted
files | INT8-ConvRot DiT (252 `Int8Tensor` Linears, fingerprint 252 of
252, ConvRot on 252) + int8 encoder (128 int8 Linears, vision tower
dropped) | 0.049 / 0.136 | 17.90 GiB |
| SFT, hosted DiT, encoder pinned bf16 | INT8-ConvRot DiT | 0.049 /
0.137 | 22.83 GiB |
| SFT, no hosted files, encoder pinned bf16 | runtime INT8-ConvRot
("ConvRot group 256 on 252 int8 linears") | 0.049 / 0.137 | 22.83 GiB |
| Base INT8-ConvRot (the previous default), hosted files (2 prompts) |
`MOSS-Image-Base-INT8-ConvRot.safetensors` + the SFT encoder file | not
scored (no Base eager reference) | 17.90 GiB |
| SFT default on a simulated 24 GiB card (`--vram-cap-gib 24`, 2
prompts) | bf16 would offload, so auto picks INT8-ConvRot
(`transformer_quant=int8(auto)`, 252 `Int8Tensor`), int8 encoder
streamed by group offload | not scored (load-and-render check) | 17.90
GiB |
| SFT, explicit `transformer_quant=fp8`, hosted file (2 prompts) |
`MOSS-Image-SFT-FP8.safetensors` (252 `Float8Tensor` Linears) + int8
encoder | not scored (load-and-render check) | 17.90 GiB |

Runtime against hosted (same tree, encoder bf16 in both): 11 of 14
renders pixel-identical, the other 3 at LPIPS 0.003 mean / 0.028 max. An
A/A repeat of the hosted arm is bit-identical (14 of 14), so that small
gap is real, not run-to-run noise: the runtime quantise and the builder
agree on the spec but not on every rounded code. Both sit at the same
distance from the eager bf16 port.

Every quantised arm: 2 dynamo graphs and 2 CUDA graph captures on the
first render, then 0 new graphs, 0 graph breaks, 0 recompiles and 0
captures on every later prompt. Before this PR's refiner fix the first
render compiled a third graph: the pipeline refines the text once per
render outside `forward`, where Studio's per-forward prompt-length
arming does not reach, so the text block specialised on the cond length
and recompiled at the uncond one. The refiner inputs now carry a
dynamic-length hint. It moves the compiled kernels for the refiner a
little: 8 of 14 renders pixel-identical before and after, the rest LPIPS
0.006 mean / 0.040 max, and the distance to the eager port is unchanged
(0.049 both). bf16 keeps its 2 graphs and 0 recompiles.

## GGUF through stable-diffusion.cpp

MOSS GGUFs go to the native engine. The family row carries the sd.cpp
assets:
- VAE: the MOSS repo's own `vae/diffusion_pytorch_model.safetensors`,
read from its byte-identical copy in `unsloth/MOSS-Image-SFT-FP8`. It is
the FLUX.2 small decoder, not FLUX.2-dev's VAE, and sd.cpp detects its
layout itself.
- Text encoder: `unsloth/Qwen3.5-9B-GGUF` `Qwen3.5-9B-Q8_0.gguf` on
`--llm`.
- Arch marker: `MOSS-Image`.
- No flow-shift override: sd.cpp's MOSS default of 5 is the reference
recipe.

Tokenizer plumbing:
- sd.cpp's MOSS conditioner refuses to run without the official Qwen3.5
`tokenizer.json` on `--tokenizer` (taken from
`unsloth/MOSS-Image-SFT-FP8`, byte-identical to the upstream file).
- `SdCppModelFiles` gains an optional `tokenizer` field, and the cli,
server and video command builders pass it when it is set.
- The family's new `sd_cpp_tokenizer` (repo, file) adds it to the
fetched assets and to the delete guard's companion files. Every other
family leaves it `None`, so their commands are unchanged.

Routing (new `native_transformer_files_only` flag in place of
`pipeline_only`):
- Diffusers has no single-file loader for the in-tree port, so the
router sends a MOSS GGUF native on GPU hosts too.
- The architecture marker gates the native route. A build older than
master-975 is refused with a reason before anything unloads, rather than
handed to diffusers.
- `family_buildable_here` gives the picker the same answer.
- An explicit diffusers pick, `UNSLOTH_DIFFUSION_ENGINE=diffusers` or
`UNSLOTH_DIFFUSION_SD_CPP=0` is refused by `validate_load_request`
before eviction.
- Loose MOSS `.safetensors` files are not offered as single-file picks.

A manual diffusers `GGUFLinear` load was not added: the native route
covers GGUF more simply.

End to end:
- Setup: Studio's own `SdCppDiffusionBackend` (B200, local `UD-Q4_K_XL`
SFT GGUF, master-982 build via `SD_CLI_PATH` / `SD_SERVER_PATH`,
512x512, 20 steps, CFG 3).
- Routing: predicted `sd_cpp` on a CUDA host.
- Load: in server mode.
- Render: a coherent image with the prompted sign text (peak 12 GB).
- Base arm (same run, tokenizer asset stripped): sd-server fails, and
the sd-cli fallback exits 1 with `MOSS-Image requires the official
Qwen3.5 tokenizer.json; pass --tokenizer FILE`.

## ComfyUI and comfy-kitchen levers

Checked against ComfyUI master (fetched read-only; no MOSS changes after
b1a247c9: `comfy/ldm/moss_image`, `model_management`, `ops`,
`model_prefetch`, `quant_ops` unchanged) and comfy-kitchen 0.2.39 (the
latest release). The MOSS defaults Studio uses (shift 5 / multiplier 1,
bf16 or fp32 only, FLUX.2 latents, cond and uncond as separate forwards
at their own text lengths, uncond skip of block 22, empty negative) are
unchanged upstream.

All timings: exclusive B200, 1024x1024, 30 steps, CFG 3, speed default
(regional compile + CUDA graphs), fresh process per arm, s/step = median
warm step over a first prompt, a new prompt length and the first prompt
again. Every arm: 0 recompiles, 0 graph breaks and 0 CUDA graph captures
on prompts 2 and 3.

| lever (ComfyUI / kitchen) | Studio | s/step before -> after | peak |
accuracy (LPIPS vs eager port, 14 prompts, 50 steps) |
|---|---|---|---|---|
| fused QKV (repacked `proj.qkv`, one GEMM + one act quant) | on for
int8: codes and per-row scales concatenate, ConvRot parts share one
rotation; parts become views (no extra memory) | INT8-ConvRot
0.0769-0.0778 -> 0.0721-0.0727; plain INT8 0.0700 -> 0.0673-0.0678 |
unchanged | int8: 0.049 before and after (base vs fused A/A is
bit-identical run to run) |
| same, bf16 | off: one fused GEMM measured 0.0876-0.0880 vs
0.0881-0.0886 (inside the A/A spread) | - | - | 13 of 14 pixel-identical
to three GEMMs |
| int8 act quant (kitchen int8 kernels) | on: every int8 block Linear
runs Studio's probed Triton act quant and `_int_mm` (torchao's eager
math) | included above (runner alone: 0.0752) | unchanged | as above |
| `rms_rope_split_half` (q/k RMSNorm + split-half RoPE) | new one-pass
Triton kernel (q, k, v read once, written in the attention layout),
every eager bf16 rounding kept, probed per device; opt-in
`UNSLOTH_DIFFUSION_MOSS_QK_ROPE=1` | bf16 0.0879-0.0883 -> 0.0871-0.0876
(0.7%); INT8-ConvRot 0.0723-0.0726 -> 0.0722 | unchanged | bf16 0.025 ->
0.026, int8 0.049 -> 0.056: inside the kernel floor, no better, so off |
| `rms_adaln` (norm weight folded into the scale) + in-place `addcmul_`
gated residual | not added: the compiled block already emits one fused
reduction kernel per norm + modulation site (both sites together ~1.4 ms
of a ~40 ms forward in the profile), and Studio measured in-place
addcmul neutral before; the fold also changes the reference's rounding |
- | - | - |
| SiTU folded into the int8 `ffn_down` act quant (`linear_input_act(...,
"situ")`) | not added: plain INT8 already compiles SiTU + act quant into
one kernel; INT8-ConvRot (the quantised default) must rotate the SiTU
output before quantising, so nothing can fold. A cheaper SiTU
formulation (sigmoid form) was 16% faster on the kernel alone, about 1%
of a step, and changes bits, so not taken | - | - | - |
| `rotq_i8` (Studio's own fused rotation + quant,
`UNSLOTH_DIFFUSION_INT8_ROTQUANT=1` on B200) | stays off on sm100 (its
existing arch gate) | 0.0721-0.0727 -> 0.0818-0.0830 (slower) | - | - |
| offload prefetch / partial load (`comfy.model_prefetch`, lowvram) |
Studio's group offload already prefetches blocks on a side stream and
keeps whole groups resident within the room; what was missing was MOSS's
measured activation peak, so the flat 8 GiB estimate streamed the 5 GB
int8 denoiser on a 16 GB card. Seeded (2905 MiB worst phase) | card
capped to 16 GiB (planner + allocator), INT8-ConvRot + int8 encoder:
0.241 -> 0.0786; 13 GiB 0.0766; 12 GiB 0.0766 (resident 0.0722) | 2.9 ->
11.2 GiB (16 GiB cap), no OOM | placement only |
| attention backend | already the same choice: SDPA routed to cuDNN on
B200 (`optimized_attention` picks PyTorch SDPA there too) | - | - | - |
| fp64 RoPE omegas | not adopted: ComfyUI builds the omegas in fp64;
Studio keeps the reference's CPU fp32 bands (the training construction),
which is what the parity tests pin | - | - | - |
| SLG under compile | already: the uncond skip of block 22 is a tuple
kwarg, the compiled blocks are simply not called, 0 recompiles | - | - |
- |
| control adapters (`concat_cond` widening `video_embedder`) | later
item: no control checkpoint is released | - | - | - |

Low-VRAM bf16 is unchanged: the dense default tier has no measured-peak
table for any family, so bf16 on a 16 GiB card still streams everything
(0.410 s/step, peak 2.9 GiB; on 24 GiB the denoiser stays resident with
the encoder streamed, 0.0864 s/step, peak 12.5 GiB).

## Multi-GPU (Kaggle T4x2, tiny model)

Run on a Kaggle T4x2 kernel (two 15 GB T4s), tiny random MOSS-Image
pipeline, 256x256, 4 steps, 4 prompts with different lengths, seeds and
CFG; each arm a fresh process through `DiffusionBackend.begin_load` /
`generate`. torch 2.11, transformers 5.20.2, diffusers 0.41.0.

| arm | placement | images vs one card |
|---|---|---|
| two cards selected, automatic | CFG-parallel armed: uncond branch on a
replica on cuda:1, 12 of 12 multi-branch steps in parallel, replica
built in 0.07 s | pixel-identical, 4 of 4 |
| `UNSLOTH_DIFFUSION_MULTIGPU=force` (component split) | text encoder
and VAE on cuda:1, DiT on cuda:0 | pixel-identical, 4 of 4 |
| component split + `UNSLOTH_DIFFUSION_CFG_PARALLEL=force` | split as
above; CFG-parallel declined (cuda:1 holds the split's components) |
pixel-identical, 4 of 4 |
| component split, speed default (compile + CUDA graphs) | split as
above; CFG-parallel declined (the graphed forward is an instance
override) | pixel-identical to one-card speed default, 5 of 5; 0
recompiles, 0 graph breaks, 0 captures on prompts 2 to 4 |

Diffusion has no layer split (that lever is llama.cpp only), so it was
not run. A real-weight 2xT4 render did not run either: the INT8 / FP8
builds exist but are not uploaded, so a Kaggle kernel cannot fetch them,
and bf16 (10.2 GB DiT + 15.9 GB encoder) does not fit two 15 GB T4s
without offload.

## Tests

- `tests/test_diffusion_moss_image.py` (35 tests, CPU): bitwise parity
against the reference file kept as test data
(`tests/data/moss_image/pipeline_moss_image_reference.py.txt`,
unmodified Apache-2.0 copy), scheduler parity and ComfyUI `sgm_uniform`
sigmas, seed noise, step callback / interrupt, skip-layer kwargs
reaching the transformer as a tuple, the forward taking no host sync
without a mask, family detection for both repos and an opaque local
folder, defaults, trusted repos, the transformers >= 5.3 gate,
prompt-length policy, in-tree class resolution. Skips without diffusers
/ transformers.
- `tests/test_diffusion_moss_fused.py` (8 tests; the kernel test needs
CUDA): fused QKV equals the three projections and drops back when a
projection is replaced, the int8 runner reaches all six block Linears,
bf16 keeps three GEMMs, the RoPE kernel is opt-in and matches the eager
ops, kill switch and offload leave the blocks alone, registry entry.
- `tests/test_sd_cpp_moss_image.py` (17 tests, CPU):
- the family row's sd.cpp assets, and that only MOSS sets a tokenizer or
native-only files;
  - asset specs and the companion delete guard include the tokenizer;
  - `--tokenizer` in all three builders, and absent when unset;
  - the marker gate against fake binaries;
  - native routing on CUDA and CPU;
  - refusal (not a diffusers fallback) for a pre-975 build;
  - refusal of an explicit diffusers pick and of the two env disables;
- route validation passing a GGUF native can take and refusing one it
cannot;
  - single-file refusal and the loose-file listing.
- `tests/test_diffusion_moss_image_quant.py` (18 tests, CPU): keep-list
and ConvRot spec, exclude tables for both recorded family names, hosted
file names for SFT and Base (rotated first, plain int8 behind, never the
other base's file), fp8 / mxfp8 out of the automatic order on every tier
while an explicit fp8 is not denied, the text-encoder file, equivalence
and budget, the absent-repo fallback (offline, empty cache: no seed,
dense encoder), the in-tree class reaching the denoiser seed, the
handed-in encoder's vision drop and offload guard, the tokenizer class
lookup, the compute-dtype cast, the measured-peak seed.
- Mirror guards: `test_image_fetch_ids_unsloth.py` (new
`test_moss_image_components_come_from_its_fp8_repos`; the MOSS pairs
join the in-repo mirror round trip, and the fetch-id guard that failed
on MOSS now passes), `test_artifact_mirrors.py` (both -FP8 repos are
artifact mirrors, so a pipeline pick of either id is refused naming its
base), the mirror-table counts in `test_diffusion_backend.py` and
`test_video_unsloth_mirrors.py`, and the sd.cpp VAE / tokenizer ids in
`test_sd_cpp_moss_image.py`.
- Updated: `test_diffusion_prompt_length_policy.py`,
`test_diffusion_autoopt_parity.py` (+ fixture rows for the new family
only), the family data freeze fixture,
`image-generation-defaults.test.ts`.
- Ran: the new file plus prompt-length policy, autoopt parity, family
freeze, more families, flow shift, auto policy, dynamic text, hub
metadata, backend and diffusers repair suites. The only failure
(`test_mirrored_base_still_trips_the_flux2_shape_guard`, no `gguf`
module in that environment) fails the same way on main.

## Not verified

- ComfyUI itself was not run (no Comfy-Org files); the defaults come
from the MOSS ComfyUI workflow and ComfyUI's native MOSS support code,
and the seed noise matches ComfyUI's draw by construction (CPU fp32
`randn`), not by a side-by-side render.
- Base ran only with its hosted INT8-ConvRot file and the SFT encoder
file (2 prompts, load-and-render, not scored); Base in bf16 was not
rendered. It differs from SFT only in the transformer shards (sha256 on
the Hub).
- Timing is B200 only. Consumer cards, ROCm, Apple and CPU did not run.
The eager speed tier measured 0.49 s/step on a shared card (not
exclusive), slower than speed off there; it was not timed on an
exclusive card.
- Low-VRAM streaming of the encoder was checked on the tiny model with
diffusers' leaf-level group offload directly (bit-identical with and
without CUDA streams) and on real weights through Studio's group
offload; Studio's `low_vram` tier did not choose streaming on this
host's free memory, so that exact path is unproven end to end.
- Under model offload (tiny model) the second prompt recorded one new
CUDA graph, which is the existing offloaded-key behaviour of the graph
layer, not specific to this family.
- Measured activation rows (`_MEASURED_IMAGE_ACTIVATION_MIB`) were not
added; the planner uses its flat estimate. Measured here: 3.5 GiB above
the resident weights at 1024x1024, the fp32 VAE decode being the worst
phase.
- The hosted-file arms above read the built files through
`UNSLOTH_DIFFUSION_PREQUANT_MIRROR`. Against the hosted repos (checked
with a token while they were private; all four now answer a token-less
request), the PR's own resolvers, download plan and fetch paths were
checked: every quant and mirrored upstream file (42 mirrored files, size
and sha256 against the pinned upstream commits), the bf16 download plan
of both bases (20 folder files, 27.22 GB, no root quant files), the
tokenizer, configs and VAE loaded from the mirrors, and the sd.cpp VAE
and tokenizer fetch. A full bf16 load from a fresh cache through the
mirrors was not run. If the mirrors are unreachable, the redirect has no
fallback to the upstream ids.
- Quantised speed is not a timing claim: the s/step numbers in those
arms come from a shared card. The GGUF route was rendered with a locally
built master-982 sd-cli / sd-server; the Studio prebuilt pin moves on a
separate branch, so a managed install from this branch alone was not
exercised (a build without MOSS is refused by the marker gate, covered
by tests). No LoRA, no single-file transformer pick.
- Under the seeded 16 / 13 GiB placements the denoiser runs resident
behind group-offload hooks, where the fused levers do not install
(0.0786 against 0.0722 fully resident); at 12 GiB the second prompt
re-captured its CUDA graphs once (the graph layer's existing behaviour
for offloaded keys).
- No side-by-side ComfyUI render or timing: running ComfyUI needs
Comfy-Org's MOSS files, which this work does not download.
- The int8 encoder keeps the gated-delta projections, embeddings and
vision tower dense (as built); a text-only, fully int8 encoder needs a
builder and loader change and was not done.
- CFG-parallel together with CUDA graphs (speed default) was not armed
on the T4x2 run (the graphed forward is an instance override the router
declines); whether that pair should combine is a question for the
CFG-parallel layer, not this family.
- The frontend tests could not run here (no `node_modules`); the catalog
check script passed.
- The MOSS bf16-while-it-fits rule uses the existing
`FamilyProfile.auto_bf16_when_resident` field under its own reason
string. The small-DiT defaults change (FLUX.2-klein, Z-Image,
FLUX.3-klein) edits the same
`test_the_bf16_rule_names_only_the_measured_families` parametrize list
and the family freeze fixture, so whichever lands second needs a trivial
merge there.
- The int8 encoder adds LPIPS 0.011 mean over the bf16 encoder with the
bf16 DiT (0.036 vs 0.025) and saves about 5 GiB of peak. ComfyUI's W4A8
encoder was not scored (no Comfy-Org files).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
…nals, planned negative length records on the first render) (unslothai#14682)

## Summary

True CFG on Qwen-Image-2.1 with a negative prompt of another text length
now records the negative branch's CUDA graph on the first render. Found
while re-checking unslothai#14387.

### The problem

The planned whole-step graph keys on the prompt length. After the first
capture, each new length spends one real step as its warm-up and records
on the next step. With true CFG and a negative prompt of a different
length, each step makes two calls:

- The positive key records on the first decode step.
- The negative key warms up on that same step.
- On the next step the positive key replays, and that replay seals the
image scope for new prompt lengths.
- The negative key then hit the sealed check (`length_eager`) and ran
ungraphed for the rest of that render and every render after.

The default guidance of 1 runs no negative branch, so it never hits
this. Any guidance above 1 always does, because the default negative
prompt is empty and so has a different text length from the positive
one.

### The fix

A planned key that was already warmed before the seal can still record.
Only warm-ups from the current render count: the set is cleared at the
end of each render (`seal_lengths`) and on `reset()`. A length first
seen after the first render, or one that warmed only on an earlier
render or before a reset, still runs ungraphed, as before.

## Results

Qwen-Image-2.1, true CFG with guidance above 1 and an empty negative,
two renders on an L4:

| | graphs recorded | `length_eager` | new graphs on render 2 |
|---|---|---|---|
| base | 1 | 5 | 0 |
| this PR | 2 | 0 | 0 |

Frames are bit-identical between base and this PR.

## Tests

-
`test_a_planned_negative_of_another_length_records_on_the_first_render`
(CPU stub): two planned keys of different lengths over two renders give
2 captures, 1 shape warm-up and 0 `length_eager`, and a later new length
still runs ungraphed. On main it gives 1 capture and fails.
- `test_a_warmup_from_before_a_reset_does_not_reopen_the_sealed_scope`
and
`test_a_warmup_from_an_earlier_render_does_not_reopen_the_sealed_scope`
(CPU stub): a length that warmed before a `reset()`, or only on an
earlier render, still runs ungraphed once the scope is sealed. They
guard the fix from reopening more than the current render's warm-ups.
- `test_true_cfg_negative_of_another_length_records_on_the_first_render`
(CUDA, tiny random Qwen-Image-2.1 transformer, real planned graphs): two
true-CFG renders, positive text length 9 and negative 13, bit-identical
to the stock forward. With the fix there are 2 captures and 0
`length_eager`. On main there is 1 capture and the test fails. The
`UNSLOTH_DIFFUSION_CUDA_GRAPH_EVERY_LENGTH=1` control passes on both.

## Known failures on main (not fixed here)

On a CUDA host, three existing tests in
`tests/test_diffusion_qwenimage21_graph.py` fail on main and with this
PR alike:

- `test_evicting_the_only_graph_does_not_reuse_its_dead_pool`
- `test_a_new_prompt_length_recaptures_and_the_oldest_graph_is_evicted`
- `test_a_new_prompt_length_warms_on_tensors_laid_out_like_the_capture`

Each one renders a new prompt length after the first render and expects
it to record. Since unslothai#14387, that length runs ungraphed by design unless
`UNSLOTH_DIFFUSION_CUDA_GRAPH_EVERY_LENGTH=1` is set.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant