Skip to content

Studio: keep CFG-parallel on the default speed tier and run Z-Image's guidance branches on two cards - #14564

Merged
danielhanchen merged 18 commits into
mainfrom
studio-cfg-parallel-default-tier
Oct 22, 2026
Merged

danielhanchen merged 18 commits into
mainfrom
studio-cfg-parallel-default-tier

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

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 Studio: Z-Image CFG split under static step skip and CFG-parallel #14551 the Z-Image CFG split declined whenever a router was armed, so the router saw one call per step; since Studio: Z-Image CFG split under static step skip and CFG-parallel #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.

…Image branches

The whole-step CUDA graph the deferred speed profile arms used to replace the
CFG-parallel router in the denoiser's forward slot, so from the 3rd image on
every family ran both guidance branches on one card. The graph now installs
under the router (the primary branch replays it, the replica runs the same
compiled blocks ungraphed), a graph armed at load moves under a later router,
and replica forwards never overlap a graph recording (global capture mode).

Z-Image's split guided call hands its two halves to the router as one
explicit pair: their tensors are fresh every step, so pairing by latent
identity never matched them and Z-Image never ran in parallel.
A replica job is counted in from the moment it is queued until it has
finished and dropped its inputs, and the worker thread's start (binding its
card) is held the same way, so a recording on the source card never begins
while the replica thread can still allocate, free or set up its context. A
hold that never drains times out after 120 s and the capture records anyway.
# Conflicts:
#	studio/backend/core/inference/diffusion_zimage_cfg_split.py
@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 ⚠️ Failed 2026-10-22T00:21:05.970326Z
We couldn’t complete this review. Comment @codex review to try again.
ae4b1b2 New commits
🔒 Security Review ⚠️ Failed 2026-10-21T21:10:07.595609Z
We couldn’t complete this review. Comment @codex security review to try again.
a0b4773 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…usion instead of running anyway

A refused capture never raises the depth or begins recording: the step runs eager, nothing is retired,
the wrapper is not poisoned and a later call records. Refused replica work never makes its CUDA calls:
the worker reports the error and the branch falls back to the source card.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…g, and flush other failures with captures held off
… capture still waits for another worker's held work

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 90bbdce90f

ℹ️ 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 and others added 3 commits October 21, 2026 15:42
Up to torch 2.13 the FX tracing flag is a module global, so while one thread
traces a first compile any compiled call on another thread raises. A call
signature new to either side now runs with the other side idle, and a whole
step capture waits for held replica work before its warm-ups, not only before
the recording.

[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. 👍

Reviewed commit: eedc3cc84f

ℹ️ 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 5433863 into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the studio-cfg-parallel-default-tier branch October 22, 2026 01:27
danielhanchen added a commit that referenced this pull request Oct 22, 2026
…ch in-place edits of inference weights (#14626)

## Summary

Two CFG-parallel defects found after #14564 landed.

**1. The replica never builds on quantised weights, so CFG-parallel
never engages on the default tier.** The router builds the second-card
replica lazily on the first guided step, which runs inside the render's
`torch.inference_mode()`. There, `param.detach().to(device)` on a
torchao weight subclass created outside inference mode raises `Cannot
set version_counter for inference tensor`, and the router disables
itself. On a B200 the default tier picks an int8 transformer, so a
two-card Qwen-Image render ran entirely on one card (`steps_parallel` 0,
second card 0 GiB).

Repro matrix on two B200s (int8, fp8, NVFP4, MXFP8, bf16 x weights
loaded inside / outside inference mode x build inside / outside):
- Weights loaded outside inference mode, built inside it (the Studio
path): every quantised scheme raised; bf16 built.
- Weights loaded inside inference mode: no error, but the quantised
replica weights silently stayed on cuda:0 (replica devices `{cuda:0,
cuda:1}`), so the "replica" shared the primary's weights across cards.

**2. A stale replica after an in-place weight edit.**
`weights_fingerprint` reads each tensor's version counter, which
inference tensors do not have, so an in-place edit left the fingerprint
unchanged and the replica kept the old weights (probe: primary 3.0,
replica 1.0, 0 rebuilds).

## Change

- `build_replica` copies under `torch.inference_mode(False)` +
`torch.no_grad()`, and raises (CFG-parallel declines) if any replica
weight lands on a CUDA card other than the target.
- `weights_probe()` samples 64 evenly spaced bytes of each
inference-tensor weight (torchao inner tensors included) with one host
sync, at replica build and once per render, never per step, outside any
CUDA graph capture. When every weight has a version counter it reads
nothing, so the normal path costs nothing.
- LoRA load / unload / `set_adapters` paths in `_apply_loras` /
`_adjust_baked_loras` now drop the replica explicitly, next to where
they already reset the graphs.

## Testing

| Suite | this PR | main |
|---|---|---|
| CPU: multigpu, cfg_parallel_tier, zimage_cfg_split, static_skip | 221
passed | 218 passed, 3 failed (the new tests) |
| CUDA `test_diffusion_multigpu_cuda.py` on two cards | 7 passed | 4
passed, 3 failed (version_counter error; replica split across cards) |
| `test_a_lora_change_drops_the_cfg_parallel_replica` | pass | fail |

Real two-card run, Qwen/Qwen-Image through `DiffusionBackend` at the
default tier (int8, compiled, CUDA graphs): replica built on cuda:1,
`steps_parallel` 133 over 7 renders (19 guided steps each),
`predicted_hits` 126, not disabled. On main the same run disabled
CFG-parallel with the version_counter error.

Small int8 model, 8 steps: main disables (or, with weights loaded under
inference mode, runs on a replica split across both cards); this PR runs
7 parallel steps with the replica entirely on cuda:1 and output equal to
the single-card render. All 20 matrix cells build on cuda:1 with replica
output bitwise equal to the primary.

Not covered: no timing (shared, oversubscribed host); an in-place edit
that misses every sampled byte of a tensor is not caught (whole-tensor
edits are); GGUF on CUDA and NVFP4 in a full pipeline were not run
(GGUFParameter builds on CPU on both sides).

---------

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