Skip to content

Studio: build the CFG-parallel replica outside inference mode and catch in-place edits of inference weights - #14626

Merged
danielhanchen merged 5 commits into
mainfrom
fix_cfg_replica_inference
Oct 22, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fix_cfg_replica_inference

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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).

…in-place edits of inference weights

The router builds its replica on the first guided step, inside the render's
torch.inference_mode(). There, detaching a torchao weight subclass (int8 /
fp8 / NVFP4 / MX) made outside it raised "Cannot set version_counter for
inference tensor", so CFG-parallel never engaged at the default int8 tier,
and copying one made inside it left the copy on the source card. The copy
now runs under inference_mode(False) + no_grad, and a replica holding a
weight on another CUDA card is refused.

Inference tensors carry no version counter, so weights_fingerprint missed
in-place edits of them and the replica kept the old values. weights_probe
samples a few bytes of each such tensor (one host sync), compared once per
render; models whose weights carry version counters probe nothing. LoRA
switches now also drop the replica explicitly.
@danielhanchen danielhanchen self-assigned this Oct 22, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T08:54:24.040212Z 33ed4df 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. Hooray!

Reviewed commit: 33ed4df85d

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

build_replica deep-copied the cache diffusion_cond_blocks keeps in the
source transformer's __dict__. Only direct tensor attributes are moved to
the replica's card, so the copied states stayed on the source card, and
end_render clears only the source's cache, so they were never freed. The
replica receives the conditioning through the forwarded call, so the cache
is dropped from the copy.

[skip ci]
# Conflicts:
#	studio/backend/tests/test_diffusion_multigpu.py

[skip ci]
@danielhanchen
danielhanchen merged commit d5f0d8b into main Oct 22, 2026
2 of 35 checks passed
@danielhanchen
danielhanchen deleted the fix_cfg_replica_inference branch October 22, 2026 19:27
danielhanchen added a commit that referenced this pull request Oct 23, 2026
…erence weights (#14844)

## Problem

#14626 added `weights_probe`, which samples 64 bytes from every
inference-tensor weight so CFG-parallel can notice an in-place edit and
rebuild its replica. The sample offsets came from

```python
torch.linspace(0, n - 1, steps = min(n, 64), device = ...).long()
```

where `n` is the weight's size in bytes. `linspace` runs in float32, so
once `n - 1 >= 2**24` the last offset can round up to `n`, one past the
end:

| weight | bytes | last offset |
|---|---|---|
| 3072 x 3072 bf16 | 18,874,368 | 18,874,368 (out of range) |
| 3072 x 12288 int8 qdata | 37,748,736 | 37,748,736 (out of range) |

On CPU `index_select` raises `IndexError`. On CUDA it is a device-side
assert in the gather kernel, which poisons the CUDA context: the router
catches the exception and turns CFG-parallel off, but every later CUDA
call in that Studio process fails too.

It is reached when a denoiser holds inference-tensor weights (loaded or
moved under `torch.inference_mode`) and CFG-parallel engages. The
existing tests only use small weights, below 16 MiB.

## Fix

The offsets are computed in int64: `arange(k) * (n - 1) // (k - 1)`.
That gives the same evenly spaced samples, always ends exactly at `n -
1`, and stays exact at any size. The per-size index cache and everything
else are unchanged.

## Tests

- New
`test_probe_stays_inside_inference_weights_past_two_to_the_24_bytes`: a
3072 x 3072 bf16 inference weight (18,874,368 bytes) must probe without
error, return 64 samples, and see a change to its very last byte.
  - main: fails with `IndexError: index out of range in self`
  - this branch: passes
- `tests/test_diffusion_multigpu.py`: 122 passed. The one failure,
`test_execution_device_reports_the_primary_of_a_split_pipeline`, is an
`ImportError` (`get_cached_repo_tree`) from a diffusers /
huggingface_hub version mismatch in the local environment and fails the
same way on main.

## Not covered

No two-card CFG-parallel render with real inference-tensor weights was
run; the fix is checked at the probe level on CPU.

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant