Skip to content

Studio: Z-Image CFG split under static step skip and CFG-parallel - #14551

Merged
danielhanchen merged 4 commits into
mainfrom
studio-zimage-cfg-split-modes
Oct 21, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-zimage-cfg-split-modes

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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.

The split now engages under a static step skip when the skip keys a step's
two calls apart (Studio's step-end callback: cond is call #0, uncond #1,
both on the batched call's schedule), and under a CFG-parallel router, which
never pairs Z-Image calls (its branch key is the timestep, a fresh tensor
per call), so both branches stay on the primary card as before. A step
cache and a skip with no per-step call order still keep the batched call.
The router installed after the skip takes the forward slot, so read the
skip from its own instance slot too; a skip without a per-step call order
under a router keeps the batched call.
@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-21T20:58:15.956310Z a239f59 Manual request
🔒 Security Review ⚠️ Failed 2026-10-21T19:03:36.211039Z
We couldn’t complete this review. Comment @codex security review to try again.
ed3abbe 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

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 03780f4a94

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

Copy link
Copy Markdown
Member Author

@codex review

2 similar comments
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a239f59e7d

ℹ️ 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 6e63ceb into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the studio-zimage-cfg-split-modes branch October 21, 2026 21:02
danielhanchen added a commit that referenced this pull request Oct 22, 2026
… guidance branches on two cards (#14564)

## Summary

On two selected cards, Studio's CFG-parallel router (conditional branch
on the primary card, unconditional on a replica on the second card) had
two gaps:

1. On the default speed tier it stopped after the 2nd image. On the 3rd
image the deferred speed profile arms a whole-step CUDA graph in the
denoiser's `forward` slot. That replaced the router, and
`drop_displaced_cfg_router` then uninstalled it. Image families arm
whole-step graphs by default, so every guided image family fell back to
one card at that point.
2. It never ran Z-Image in parallel, on any tier. `ZImagePipeline`
batches a guided step into one call. Before #14551 the Z-Image CFG split
declined whenever a router was armed, so the router saw one call per
step; since #14551 the split runs under the router, but the router pairs
branches by the identity of the latent argument, and Z-Image's first
tensor argument is a timestep that is new on every call, so the two
halves still never paired and both ran on the primary card.

With this change, CFG-parallel stays on with the default tier (compile
plus CUDA graphs) and Z-Image runs its branches on two cards. On Kaggle
2xT4 that cuts seconds per step about in half.

## What it does

- `GraphedForward.install` installs the graph under a CFG-parallel
router (`router.inner`) when the router holds the slot. The primary
branch replays the graph. The replica runs the same compiled blocks
without a graph (same kernels). `uninstall` on either side gives the
slot back to the graph.
- `install_cfg_parallel` moves a resident whole-step graph that was
armed at load (non-deferred tier) under the new router. Before this, the
replica was declined as a "root forward override".
- Graph recordings use the global capture mode, which stops the replica
thread from allocating while one is in progress anywhere in the process.
So all CUDA work on the replica thread is held out of recordings:
binding the card at thread start, and each job from submit until it has
finished and dropped its inputs. A capture waits for those holds to
drain, with a 120 s timeout after which it records anyway (a failed
capture already falls back to eager).
- New `CfgParallelRouter.run_pair(primary_call, args, kwargs)`. A caller
that splits a batched guided call queues the second half on the replica
and runs the first half on the source through its normal call (hooks,
graph). The Z-Image split now uses it instead of declining under a
router. If the pair cannot run (router disabled, replica unavailable,
root hooks present, opaque inputs), both halves run on the source as
before. If the replica fails mid-step, that half is recomputed on the
source.
- Counters: `pairs_parallel` in the router stats, `parallel` in the
Z-Image split status.

The rest is unchanged: the guidance-distilled path, decline reasons
(offload, layer split, two experts, whole-module compile), automatic
placement (CFG-parallel still needs several selected cards or
`UNSLOTH_DIFFUSION_CFG_PARALLEL=force`), and video (video families do
not arm whole-step graphs by default).

## Results

Kaggle 2xT4, fp16, 768x768, 10 steps, guidance 4. Each arm is 3 timed
renders after a warm-up. s/step is the median of per-step deltas (step 0
excluded). The A/A row is the same single-card arm run again.

Z-Image (base, `Tongyi-MAI/Z-Image`), final code:

| tier | single card s/step | A/A repeat | CFG-parallel s/step | speedup
| peak VRAM card0 / card1 (GiB) single | parallel |
|---|---|---|---|---|---|---|
| eager | 2.922 (spread 0.127) | 3.046 | 1.561 (spread 0.017) | 1.87x |
12.02 / 0.00 | 12.02 / 11.84 |
| default (compile + graph) | 2.599 (spread 0.002) | 2.599 | 1.298
(spread 0.019) | 2.00x | 11.95 / 0.01 | 11.77 / 11.74 |

Z-Image-Turbo at guidance 4, same setup: eager 3.206 -> 1.623 s/step
(1.98x, A/A 3.208), default 2.595 -> 1.317 s/step (1.97x, A/A 2.597).

On the default tier, a follow-up prompt (same length bucket) added 0
dynamo graphs and 0 graph captures, and all 10 of its steps ran as
parallel pairs. The first default-tier render (compile, replica
recompile, capture) took 38 s. With the router, the primary graph
records only the conditional branch: 1 graph instead of 2.

Per family, tiny pipelines, one card (replica on the same device). `rc /
sp` = replica calls / parallel steps over 3 renders of 6 steps:

| family | eager tier, base | eager tier, head | default tier, base |
default tier, head |
|---|---|---|---|---|
| FLUX.1 (true CFG) | 15 / 15 | 15 / 15 | 0 / 0 (router dropped) | 15 /
15, graph 1 capture, 21 replays |
| FLUX.2-klein base | 15 / 15 | 15 / 15 | 0 / 0 (router dropped) | 15 /
15, graph 1 capture |
| Qwen-Image (true CFG) | 15 / 15 | 15 / 15 | 0 / 0 (router dropped) |
15 / 15, graph 2 captures |
| Z-Image | 0 / 0 (batched call) | 18 / 18 pairs | 0 / 0 (router
dropped) | 18 / 18 pairs, graph 1 capture |

All head rows match single-card output bit for bit.

## Compile on one card while the other runs

Up to torch 2.13 the FX tracing flag that AOTAutograd sets during a
compile is process-wide (torch 2.14 made it thread-local). A first call
on the replica's card, or a new prompt length on either card, compiles
while the other card's thread may be inside a compiled block, and dynamo
then raises "Detected that you are using FX to symbolically trace a
dynamo-optimized function". On Kaggle 2xT4 (torch 2.11) this once sent
the default tier's graph capture to its eager fallback.

- The router now remembers the input shapes, layouts and modes each card
has run. A call new to either card waits for the other card's in-flight
work instead of overlapping it, and a prediction is launched only when
both sides have seen their inputs. Steady-state steps are unchanged; the
cost is one serialized step per new shape.
- Capture warm-ups now also wait for held replica work, not just the
recording itself.
- 4 new tests force the interleaving with a process-wide flag and fail
without the fix. Kaggle 2xT4 rerun: the default-tier arm captures (1
capture, 50 replays, 0 fallbacks), 1.97x over one card, 0 new graphs or
captures on the follow-up prompt.

## Testing

- New `tests/test_diffusion_cfg_parallel_tier.py` (8 tests, CPU): graph
under the router, primary branch through the graph, a graph armed at
load moving under a later router, capture and replica-job exclusion in
both directions, queued jobs holding captures off until their inputs are
dropped, Z-Image pairs (exact) and replica-failure fallback. All 8 fail
on the merge base and pass here.
- `tests/test_diffusion_multigpu_cuda.py`: 2 new two-card tests (graph
under the router with real capture and replay, exact vs single-card
graph, no capture on a follow-up prompt; Z-Image pair on two cards,
exact). On Kaggle 2xT4: head 4 passed, base 2 failed (exactly the 2 new
tests).
- Related suites (multigpu, cuda_graph, zimage_cfg_split, cfg_batch,
block_graph, offload graphs, layer split, step skip, speed, wiring),
base vs head: the only failing test IDs on base are the 8 new ones.
Head: 685 passed, 65 skipped (CUDA-only).

## Not verified

- A family whose speed plan arms an automatic static step skip
(Qwen-Image's default plan does) still renders on one card: the skip
holds the source module, so the replica cannot carry it and the router
steps aside with the reason 'a static step skip wraps the denoiser'. The
graph now installs beneath such a nested router instead of replacing it,
but which of the two levers to keep for those families (step skip on one
card vs both branches on two cards) is left for a follow-up measurement.
The Qwen-Image row above is the tiny pipeline, which arms no skip.

- Bit identity on real Z-Image weights. In fp16 on T4, Z-Image and
Z-Image-Turbo produce NaN latents on a single card too (fp32-encoded
prompts, finite embeddings), so output equality was proven only on tiny
models (two real T4s, and one card).
- Not run here: Wan 2.1, Lumina 2, Chroma, CogView4, Qwen-Image edit /
layered, Krea 2, Ideogram 4, FLUX.3 modular, HunyuanImage. Their
pipelines make two calls on the same latent tensor, which is the path
FLUX and Qwen-Image exercise above. LTX, LTX-2 and HiDream batch both
branches into one call, and Wan 2.2 A14B is declined as two-expert, so
this PR does not change them.
- Studio's full load and generate path on two cards. The measurements
use the router, the Z-Image split, the compile recorder and
`install_cuda_graphs` directly on a diffusers pipeline.
- Cards other than T4, and NVLink hosts.

---------

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