Skip to content

Studio: Z-Image guided steps run at the guidance-off batch so turning CFG on recompiles nothing - #14541

Merged
danielhanchen merged 1 commit into
mainfrom
studio-zimage-cfg-toggle-no-recompile
Oct 21, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
studio-zimage-cfg-toggle-no-recompile

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Turning guidance on for Z-Image (Z-Image-Turbo) partway through a session no longer recompiles the transformer or records a new CUDA graph.

ZImagePipeline (and its img2img and inpaint variants) runs a guided step as one transformer call with twice the samples: the latents repeated, then the prompt embeddings followed by the negative ones. Turbo's default is guidance 0, so the first render compiles the repeated block for one sample with no attention mask. The first guided render then hit three guard failures in ZImageTransformerBlock.forward (diffusion_arch_patches._zimage_forward):

  • tensor 'adaln_input' size mismatch at index 0. expected 1, actual 2 (dynamo specialises batch size 1)
  • attn_mask is None (the two captions pad to different 32-token buckets, so the batched call carries a mask)
  • the same mask change again in the main layers

That gave 3 new graphs and 1 new whole-step CUDA graph capture. After that, each guided prompt could still recompile, depending on whether its caption landed in the same bucket as the negative prompt (no mask) or a different one (mask).

Change

New diffusion_zimage_cfg_split.py. On a resident denoiser, a guided call with 2 * B samples now runs as the conditional B, then the unconditional B, both through the module's normal call path, and the two output lists are joined in the order the pipeline expects. Each half is an ordinary guidance-off call, so it reuses the graphs from the first render and the CUDA graph scope that is already sealed. The math is unchanged: the batched call masks the batch padding, and a single sample has no batch padding to mask.

  • Studio passes B (images per call) for each render, so a guidance-off batch of B is never split.
  • Declined for streamed offload (group / streaming / sequential), because two calls would upload the weights twice per step. Also declined per call under a step cache, static step skip or CFG-parallel, since those key on the one batched call.
  • Process-global class patch, gated per instance and restored on model unload. Reported in status()["zimage_cfg_split"].
  • Kill switch: UNSLOTH_DIFFUSION_ZIMAGE_CFG_SPLIT=0.

ComfyUI does something similar in calc_cond_batch / CONDCrossAttn.can_concat. It batches cond and uncond only when the text lengths are compatible and runs them as separate calls otherwise. Its Lumina / Z-Image model never passes a caption mask.

Results

Studio DiffusionBackend.load_pipeline + generate, default speed mode (compiled + CUDA graphs). Prompts 1-3 at guidance 0, prompts 4-5 at guidance 2.0. Each cell is new dynamo graphs / CUDA graph captures for that prompt.

Z-Image-Turbo, bf16, 1024x1024, 8 steps:

prompt guidance main this PR
1 0 3 / 1 3 / 1
2 0 0 / 0 0 / 0
3 0 0 / 0 0 / 0
4 2.0 3 / 1 0 / 0
5 2.0 1 / 0 0 / 0

A session that starts with guidance on (fresh process, prompts 4 and 5 only): main 3 / 1 then 2 / 0; this PR 3 / 2 then 0 / 0. The two captures on the first render are the conditional and unconditional lengths.

Tiny Z-Image pipeline, 256x256, 4 steps: main 2/1, 0/0, 0/0, 3/1, 1/0; this PR 2/1, 0/0, 0/0, 0/0, 0/0.

Speed

Setup: one exclusive B200, Z-Image-Turbo bf16, 1024x1024, 8 steps, default speed tier (compiled + CUDA graphs). Each process does two warm-up renders (prompt A, then prompt B) and then times A, B, A, B. That is 6 timed renders per prompt per arm, from 3 processes. Prompt A's caption shares a 32-token bucket with the negative prompt, so main's batched call has no mask. Prompt B's caption is in a different bucket, so main's batched call is masked. Times are wall s/step over the whole render, so text encode and VAE decode are included. The order was A/A (main x3) first, then main / split / bucket interleaved.

guidance arm prompt A s/step, median [min-max] prompt B s/step, median [min-max]
2.0 main (A/A run) 83.7 ms [82.9-84.9] 98.2 ms [96.9-104.6]
2.0 main 85.2 ms [83.4-86.5] 100.8 ms [97.9-102.6]
2.0 this PR (always split) 90.0 ms [84.6-130.6] 87.5 ms [87.0-130.2]
2.0 this PR, repeats 2-3 only 85.0 ms [84.6-94.7] 87.3 ms [87.0-87.7]
2.0 variant: batch when same bucket, split otherwise 86.7 ms [84.0-93.0] 88.5 ms [85.2-94.8]
0 main 43.8 ms [43.2-45.9] 46.8 ms [45.0-54.1]
0 this PR 43.6 ms [43.3-51.1] 45.5 ms [45.2-49.6]
  • Captions in different buckets (B): the split is about 13% faster than main's masked batched call (87.3 vs 100.8 ms/step), well outside the A/A spread.
  • Captions in the same bucket (A): the split matches main within noise in repeats 2 and 3 (85.0 vs 83.4-86.5 ms). In the first split repeat, all four timed renders were slow (130.6 / 130.2 / 95.5 / 116.6 ms). The bucket variant's first repeat was also slightly high, so this looks like a disturbance on the card or in the process, not a cost of splitting. It was not re-measured.
  • Guidance 0 is unchanged: the code path is identical and the times are within noise.
  • The bucket-aware variant is no faster than always splitting. It is also worse for the goal: the first guided prompt whose caption shares the negative's bucket still compiles the 2-sample, no-mask graphs and records new CUDA graphs. In a guided-first session it took 2 graphs + 2 captures on render 2; the always-split arm took 0 + 0. Always splitting is kept.

Image parity

  • Guidance off (prompts 1-3): bit-identical to main (same sha256), tiny and real.
  • Guided, both captions in the same 32-token bucket (prompt 5): bit-identical to main, compiled and eager.
  • Guided, captions in different buckets (prompt 4): not bit-identical, because the masked batched call and the single-sample call pick different kernels. Same composition. Against main the difference is mean abs 14.6 / 255 (PSNR 19.4 dB). For reference, main's own eager vs compiled render of the same prompt differs by mean abs 18.4 (PSNR 17.7 dB). Guidance 2.0 on the 8-step distilled Turbo amplifies kernel-level differences.

Tests

  • New tests/test_diffusion_zimage_cfg_split.py (9 tests, CPU). It runs a tiny ZImageTransformer2DModel with its blocks compiled the way Studio does (dynamic, one dynamo code object) and counts torch._dynamo unique_graphs. With the split off, the guided call adds graphs (this is the defect). With the split on, three guided calls at mixed caption lengths add 0. The split output equals each branch run alone bit for bit and matches the batched call within 1e-5. Streamed offload, step cache, step skip, guidance-off batches and unload restore are also covered.
  • Related suites (test_diffusion_backend, _batched, _cfg_batch, _cuda_graph, _offload_cuda_graph, _prompt_length_policy, _render_thread, _static_skip, _step_skip_defaults, _zimage_fused, _memory, _image_te_default): main 1506 passed, 31 skipped; this PR 1515 passed, 31 skipped (the 9 new tests), no failures on either side.

Not covered

  • Timing was measured on a B200 only. On smaller cards a doubled batch may use the GPU better than two single-sample calls; that was not measured.
  • Z-Image with a static step skip, step cache or CFG-parallel keeps the batched call, so it still recompiles when guidance turns on.
  • Streamed-offload Z-Image (low_vram group offload) keeps the batched call as well.
  • Guided renders with more than one image per call were not run end to end.

… CFG on recompiles nothing

ZImagePipeline batches a guided step into one transformer call of twice the
samples. After guidance-off renders the repeated block was compiled at one
sample with no attention mask, so the first guided render compiled three new
graphs and recorded a new CUDA graph, and later guided prompts kept
recompiling as the two captions moved between the same and different
32-token buckets (mask None vs tensor).

On a resident denoiser Studio now runs a guided call of 2B samples as the
conditional B then the unconditional B through the normal module call and
joins the outputs in the pipeline's order. Declined for streamed offload,
step cache, static step skip and CFG-parallel. Kill switch
UNSLOTH_DIFFUSION_ZIMAGE_CFG_SPLIT=0.
@danielhanchen danielhanchen self-assigned this Oct 21, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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 ✅ Completed 2026-10-21T17:11:12.434657Z — Manual request
🔒 Security Review ⚠️ Failed 2026-10-21T16:55:06.967372Z
We couldn’t complete this review. Comment @codex security review to try again.
2001021 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

Copy link
Copy Markdown

The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

ℹ️ 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 b6980ac into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the studio-zimage-cfg-toggle-no-recompile branch October 21, 2026 17:35
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…4551)

## Summary

#14541 runs a guided Z-Image step as two batch-1 calls, so turning CFG
on mid-session compiles nothing new and records no new CUDA graph. It
turned itself off under four modes. This PR turns it on under two of
them, static step skip and CFG-parallel. In both, the decline was never
actually needed. The other two keep the batched call, because there is a
real constraint.

| mode | before | after | why |
|---|---|---|---|
| static step skip (`transformer_cache="static"`) | batched | split |
With Studio's step-end callback, the skip keys calls by their order
within a step. Cond is `#0` and uncond is `#1`, so each branch is
skipped or computed on the same steps as the batched call. |
| CFG-parallel router | batched | split | The router pairs branches by
the identity of the first tensor argument. For Z-Image that is the
timestep, which is a fresh tensor on every call. So the router never
pairs Z-Image calls, batched or split, and every call runs on the
primary card either way. |
| step cache (FBCache) | batched | batched | FBCache keeps one residual
per `cache_context`, and two calls in one context would compare cond
against uncond. This case cannot happen today: no Z-Image pipeline
(`pipeline_z_image*.py`) opens a `cache_context`, so `apply_step_cache`
refuses Z-Image. |
| streamed / group / sequential offload | not armed | not armed | Two
calls would upload the streamed weights twice per step. That costs more
than a recompile, and `diffusion_cfg_batch` exists to avoid exactly
this. |

## What it does

- `_declined_now` declines under a static step skip only when the skip
has a plan and cannot key the two calls apart: no step signal, or a
`cache_context` name shared by both calls.
- The skip is found through its own `_unsloth_static_skip` slot as well
as the forward slot. A CFG-parallel router installed after the skip
takes over the forward slot and wraps the skip.
- The CFG-parallel decline is removed.
- The docstring now says which modes split and why.

## Results

Studio `DiffusionBackend`, same host, base = `origin/main`. Prompts 1-3
at guidance 0, then prompts 4-5 at guidance 2.0. Each cell is new dynamo
graphs / recompile log lines / Studio CUDA graph captures for that
render.

| setup | prompt 4 main | prompt 4 this PR | prompt 5 main | prompt 5
this PR |
|---|---|---|---|---|
| Z-Image-Turbo bf16, 1024x1024, 12 steps, static skip, default tier | 3
/ 6 / 1 | 0 / 0 / 0 | 1 / 2 / 0 | 0 / 0 / 0 |
| tiny Z-Image, 256x256, 12 steps, static skip | 3 / 6 / 1 | 0 / 0 / 0 |
1 / 2 / 0 | 0 / 0 / 0 |
| tiny Z-Image, 4 steps, CFG-parallel armed, CUDA graphs off | 3 / 6 / 0
| 0 / 0 / 0 | 1 / 2 / 0 | 0 / 0 / 0 |

- Static skip schedule: both arms skip 4 of 12 steps on each branch.
Main skips 4 of 12 batched calls; this PR skips 8 of 24 split calls.
Prompts 1-3 are bit-identical to main (same sha256).
- Real model, first guided render: 15.6 s on main (recompile plus
capture) vs 0.90 s on this PR. Second guided render: 5.7 s vs 0.77 s.
Each is a single render on a shared card, so these are latency
observations and not a throughput benchmark. Prompt 5 is bit-identical
to main (same sha256). Peak VRAM was 19.3 GB on main and 19.0 GB on this
PR.
- CFG-parallel: main and this PR both show `replica_calls 0` and
`steps_parallel 0`, which confirms the router never pairs Z-Image calls.
The guided images under the router are bit-identical to the split
without a router.

## Testing

- `tests/test_diffusion_zimage_cfg_split.py` has 4 new tests:
- Under the real `StaticStepSkip`, a guided render after guidance-off
renders adds 0 graphs.
- Split vs batched under the skip: the same steps are skipped (2x the
calls) and the predictions match within 1e-4.
- A skip with no step signal keeps the batched call, including when a
router is installed over the skip.
- Under the real `CfgParallelRouter`, the split adds 0 graphs, builds no
replica, and its output is bit-identical to the split without a router.
- The new tests fail on main (4 failed) and pass here.
- Related suites: `test_diffusion_cache`, `cfg_batch`, `multigpu`,
`multigpu_wiring`, `static_skip`, `step_skip_defaults`,
`zimage_cfg_split`, `zimage_fused`, `video_static_skip`, `cuda_graph`.
Main: 4 failed (the new tests only), 488 passed, 8 skipped. This PR: 492
passed, 8 skipped.

## Not verified

- CFG-parallel across two physical cards. The host queue leases one card
per job, so the router was armed with the primary card as its own
secondary. Since the router never pairs Z-Image calls, no replica is
built in either arm. Making CFG-parallel actually parallelise Z-Image is
a separate change and is not done here.
- On the default tier, CFG-parallel does not arm on Z-Image in either
arm: the CUDA graph wrapper owns the forward slot. The router case was
measured with CUDA graphs off, and with the eager tier (no compile, so
nothing to recompile).
- Steady-state s/step under the static skip on an exclusive card.
- A step cache on Z-Image, since no Z-Image pipeline can run one today.
- Streamed offload. It is unchanged and still not armed.
danielhanchen added a commit that referenced this pull request Oct 23, 2026
…d or replaying graphs (#14868)

## Problem

The Z-Image CFG split (#14541) runs a guided step as two calls at the
guidance-off batch so that turning guidance on compiles and records
nothing new. Studio armed it on every resident load, including the
`eager` and `off` speed tiers, where the denoiser is neither compiled
nor replaying CUDA graphs. There the split saves nothing and only adds a
second serial pass through the weights.

Eager denoiser timing on B200 (random weights, full 3840 width, 4 main +
2 refiner layers, bf16, 8 interleaved groups after an A/A check, shared
GPU so treat as a coarse ratio):

| Latent (image) | Captions | Batched ms | Split ms | Split / batched
(range) | A/A |
|---|---|---:|---:|---:|---:|
| 32x32 (256px) | 9 / 12 | 14.36 | 29.87 | 2.08 (1.64 to 2.39) | 1.05 |
| 32x32 (256px) | 9 / 45 | 13.65 | 26.15 | 1.92 (1.66 to 2.15) | 1.01 |
| 64x64 (512px) | 9 / 12 | 20.02 | 26.18 | 1.31 (1.21 to 1.69) | 1.01 |
| 64x64 (512px) | 9 / 45 | 21.26 | 32.78 | 1.54 (0.80 to 1.90) | 0.98 |
| 128x128 (1024px) | 9 / 12 | 67.49 | 64.68 | 0.96 (0.92 to 1.09) | 0.97
|
| 128x128 (1024px) | 9 / 45 | 67.79 | 68.13 | 1.01 (0.88 to 1.11) | 1.00
|

## Fix

- `install_zimage_cfg_split` takes `compiled_only`. When set, `render()`
splits only while the denoiser runs compiled code (the same detection
the CFG batch router uses, plus a torch.compile'd instance forward) or
the pipeline replays CUDA graphs. The check runs per render, so a
compile engaged after the load still splits from its next render.
- Studio's load path passes `compiled_only = True`. Direct callers keep
the old behaviour.

On the default tier nothing changes. Tiny Z-Image pipeline through
Studio `load_pipeline` + `generate`, new Dynamo graphs and CUDA graph
captures per render:

| Sequence | Before | After |
|---|---|---|
| default tier, single image: off, cfg, cfg, cfg | (2,1) (0,0) (0,0)
(0,0) | (2,1) (0,0) (0,0) (0,0) |
| default tier, 2-prompt lists, mixed caption buckets, 8 renders | (3,1)
(1,0) then 0 | (3,1) (1,0) then 0 |
| eager tier, single image | split 12 calls | split 0 calls (batched, as
before #14541) |

## Tests

- New in `tests/test_diffusion_zimage_cfg_split.py`: an eager denoiser
keeps the batched guided call (bitwise equal to the plain call) and
splits once compiled; every engaged form (regional compile mark,
compiled block, CUDA graphs) splits; Studio's load call passes
`compiled_only = True`. All 5 fail on the current main and pass here.
- `tests/test_diffusion_zimage_cfg_split.py` and
`tests/test_diffusion_cfg_parallel_tier.py`: 47 passed.
- Diffusion suites touching Z-Image or CFG batching: failures are
identical on the base and on this branch.

## Not covered

- Timing used random weights, the denoiser only, on a shared B200; no
pretrained end-to-end render was timed.
- With 2-image prompt lists in different caption buckets, the first
guided render on the default tier compiles one graph (the unconditional
half has no mask). The batched path compiles the same graph on the first
same-bucket render instead, and later prompts compile nothing either
way, so this is left as is.
- Only torch 2.12.1 (eager timing) and 2.14.1 (Studio runs) were
exercised; no non-NVIDIA hardware.
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