Skip to content

Studio: run the Qwen-Image-2.1 CFG branch on the replica with its own prefix KV cache - #14954

Merged
danielhanchen merged 5 commits into
mainfrom
studio-q21-cfg-parallel-kv-cache
Oct 23, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-q21-cfg-parallel-kv-cache

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

On two cards, every guided Qwen-Image-2.1 render arms CFG-parallel, then the first replica call fails with

RuntimeError: Expected all tensors to be on the same device ... (when checking argument in method wrapper_CUDA_cat)

and the router falls back to one card for the rest of the session. Guided Q21 renders never get the 2-card speedup.

Traced on a tiny Qwen-Image-2.1 pipeline on two B200s: the failing torch.cat is torch.cat([cached_k, key]) in diffusers' _qwenimage21_prepare_qkv. The pipeline passes its prefix KV cache as kv_cache=QwenImage21KVCache, which holds a list of QwenImage21KVLayerCache objects that store K/V on the primary card. _holds_opaque_tensors is meant to keep such a branch on the primary. It does not see tensors that sit inside objects in a list (cache.layer_caches[i].k), so the cached negative branch went to the replica with cuda:0 K/V. _to_replica cannot move tensors held inside objects, so the replica's cat mixed the two cards.

The fallback was also only half visible. cfg_parallel.disabled_reason was set, but the placement decision still showed no CFG-parallel rejection.

Fix

studio/backend/core/inference/diffusion_multigpu.py:

  • The replica gets its own copy of the prefix KV cache on its card. When a cached-mode call (kv_cache_mode="cached") carries a cache made of plain value holders, lists and tensors, _to_replica swaps in a structural copy with every tensor on the replica card. The copy is made once per cache object, so once per prompt and render, not per step. Later steps reuse it as long as the source still holds the same K/V tensors. The copies are dropped at end_render.
  • The prefill (kv_cache_mode="extract") always runs on the primary. It fills the pipeline's own cache object, which the pipeline reads back, and it is never predicted onto the replica.
  • _holds_opaque_tensors now sees tensors inside value holders in a list. A cache that cannot be copied (slotted objects, modules) stays on the primary instead of failing at run time. The first such branch logs one info line.
  • _call_signature includes the cached K/V shapes. A new prompt length counts as a new signature that may compile, so it never overlaps the other card.
  • Status: cfg_parallel gains armed, replica_failures, kv_cache_copies and kv_prefill_primary_calls. A router that falls back at run time is now listed in decision.rejected as disabled at run time: <reason>.

Tests

  • New CPU tests in tests/test_diffusion_multigpu.py. All three fail on main.
    • test_prefix_kv_cache_branch_runs_on_the_replica_against_its_own_copy: two guided renders with a Q21-shaped cache. Output must equal the one-card output. The prefill runs on the main thread, the replica never sees the pipeline's cache object, and there is one copy per render.
    • test_opaque_detection_sees_tensors_in_a_list_of_value_holders
    • test_replica_failure_is_reported_in_the_status
  • New 2-card test in tests/test_diffusion_multigpu_cuda.py: test_prefix_kv_cache_branch_runs_on_the_second_card_and_stays_exact. On main the router disables itself with the same cross-device torch.cat error. With the fix it runs the branch on cuda:1, stays bit-identical to one card and makes one copy per render.
  • Multigpu, cfg-parallel and Qwen-Image-2.1 test files (test_diffusion_multigpu*.py, test_diffusion_cfg_parallel_tier.py, test_diffusion_cfg_batch*.py, test_diffusion_zimage_cfg_split.py, test_video_multigpu_wiring.py, test_diffusion_prefix_kv.py, test_diffusion_qwenimage21*.py) were run on two cards, main vs this branch, comparing failing test IDs:
    • Main: 7 failed, 406 passed. This branch: the router-facing files pass in full (232 passed); the test_diffusion_qwenimage21*.py files, which do not import the router, fail only the 3 tests below.
    • The 4 new tests are the only IDs that fail on main and pass here. No test fails here that passes on main.
    • Three test_diffusion_qwenimage21_graph.py tests (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, test_evicting_the_only_graph_does_not_reuse_its_dead_pool) fail on both and are unrelated.
  • End to end, through DiffusionBackend, on a tiny Qwen-Image-2.1 pipeline on two B200s (6 steps, guided renders at guidance 4 with 7 and 17 word prompts, plus guidance 1 renders in between). Each arm was run twice on main and twice on this branch, same cards and seeds:
    • Main: the first guided render disables CFG-parallel with the cross-device cat error and every later render runs on one card.
    • This branch: no fallback. Every guided render runs steps 1 to 5 on the replica (steps_parallel 5 per render, 4 of them predicted, 0 misses). There is one cache copy per render and the prefill stays on the primary.
    • Eager (speed off): every image, guided or not, is bit-identical to one card.
    • Compiled: every image is bit-identical to one card except the first guided render, which is at 52.7 dB. That is above the compiled cross-card floor (48.5 dB on a long prompt) and the same in both repeats.
    • Compiled: the first guided render pays the replica's own compile on the second card (2 recompiles; main pays 1 before it falls back). Follow-up guided renders, including a new prompt length, have 0 recompiles and 0 graph breaks.

Not covered

  • No real-weight timing. The Qwen-Image-2.1 text encoder weights are not in the local cache, so one card vs pair speed was measured only on the tiny pipeline, where the timing is overhead and means nothing. The speedup on real weights is not measured here.
  • Step 0 (the prefill) still runs both branches on the primary, so a guided render parallelises steps 1 to N-1.
  • Only same-type cards (B200 pair) were tested. No ROCm, no mixed-card pairs.

… prefix KV cache

The CFG-parallel replica received the pipeline's QwenImage21KVCache, whose
per-layer K/V sit on the primary card inside objects in a list. The opaque
check missed them, so the replica's torch.cat mixed cuda:0 and cuda:1 and
the router fell back to one card on every guided render.

The replica now gets its own copy of a cached-mode prefix KV cache on its
card, made once per cache (per prompt and render) and reused by later
steps. The prefill stays on the primary. Opaque detection sees tensors in
lists of value holders, the call signature includes the cached K/V shapes,
and a run-time fallback is reported in the placement decision and the
cfg_parallel status (armed, replica_failures, kv_cache_copies).
@danielhanchen danielhanchen self-assigned this Oct 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-23T16:19:59.460308Z a52ffa2 Manual request
ℹ️ 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

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 50fdc9ad5b

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

# Conflicts:
#	studio/backend/tests/test_diffusion_multigpu_cuda.py

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 13a9cc606f

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

):
return entry[2]
secondary = self.secondary
mirror = _walk_cache(cache, lambda t: t if t.device == secondary else t.to(secondary), [])

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 Budget the prefix cache before copying it

For Qwen-Image-2.1 renders with large condition images, this unconditionally copies the entire prefix cache to the secondary even though _build_replica admits a card with only 1024 MiB beyond the replica weights. The Qwen implementation documents that a 1 MP condition-image cache is about 2.2 GiB (diffusion_qwenimage21.py:281-283), so a card that passes the admission check can OOM here; the router then disables CFG parallel and recomputes on the primary after already paying the replica-build cost. Include the mirror size in the capacity decision or decline oversized caches before attempting the copy.

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, this was real. _build_replica only checks the replica weights plus 1024 MiB, and _kv_mirror then copied the whole prefix cache with no check. A 1 MP condition image's cache is larger than that margin, so a copy that OOMed got caught as a replica call failure and disabled CFG parallel after the replica had already been built.

Fixed in a52ffa2:

  • _kv_mirror now adds up the cache tensors' bytes and compares them with the secondary's free memory, using the same margin as admission (cached-but-unused allocator blocks count as free, 1024 MiB headroom). The free-memory read now lives in a shared _secondary_free_mib, which _build_replica also uses, so the two checks cannot drift apart.
  • If the cache does not fit, it raises _KVMirrorDeclined before anything is copied. The step path catches that and runs the branch on the primary. run_pair returns None, so both halves run on the source. Neither path calls disable, so the replica stays built and armed.
  • The decline is stored per cache for the rest of the render, so free memory is probed once per cache, not once per step. end_render and drop_replica clear it.
  • When the cache fits, the code path is the same as before. The prefix KV output is unchanged and there are no new compiles or captures.

New test test_prefix_kv_cache_too_large_for_the_replica_card_stays_on_the_primary fakes 1024 MiB free on the secondary. That is enough to admit the replica but not the cache. It checks that no copy is attempted, that the render matches eager bit for bit, and that the replica is still armed. It fails on 13a9cc6 and passes now. On two B200s, test_diffusion_multigpu.py plus test_diffusion_multigpu_cuda.py give 138 passed, 0 failed, 0 skipped (137 before plus the new test).

…lica

Admission leaves the replica card only 1 GiB beyond the weights, and a
Qwen-Image-2.1 condition-image cache can exceed that. Measure the cache
against the secondary's free memory with the same margin first; when it
does not fit, that cache's guidance branch stays on the primary for the
render and the replica is kept.

[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. Chef's kiss.

Reviewed commit: a52ffa2c24

ℹ️ 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 added a commit that referenced this pull request Oct 23, 2026
`pre-commit.ci - pr` is failing on new PRs (for example #14954 and
#14955, both queued after the last format fix) because
`unsloth/models/speculative.py` on `main` is not formatted. #14912 left
a blank line after the function-local import in `_drop_stale_head`, and
the pinned `ruff-format-with-kwargs` hook (ruff 0.6.9) removes it. The
hook runs over every file, so every PR inherits the failure.

This is format only:
- the AST is identical before and after;
- re-running `scripts/run_ruff_format.py` over every Python file changed
on `main` since the last format fix leaves nothing else to change.
@danielhanchen
danielhanchen merged commit 036bf6a into main Oct 23, 2026
@danielhanchen
danielhanchen deleted the studio-q21-cfg-parallel-kv-cache branch October 23, 2026 18:27
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