Skip to content

Studio diffusion: one host read per guided step in the CFG-batch and CFG-parallel argument checks - #14734

Merged
danielhanchen merged 1 commit into
mainfrom
diffusion_sync_audit
Oct 22, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
diffusion_sync_audit

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

When CFG batching is armed, each guided step checks that the second branch's arguments match what was batched. That check called torch.equal once per tensor argument, and every call is a blocking device-to-host read. The CFG-parallel prediction check (_take_prediction) did the same for its by-value tensors.

This PR adds diffusion_multigpu._bitwise_equal_all. It compares every pair on its own device, then reads back one combined flag per device. Mismatches in shape, dtype, device, non-tensor values and paths are still caught on the host before any device work. It gives the same answer as the old per-pair _bitwise_equal loop.

Where it is used:

  • diffusion_cfg_batch._matches (the CFG-batch second-branch check)
  • diffusion_multigpu._CfgParallel._take_prediction (the by-value tensor pairs)

Measurements

Studio's denoise loop was run under torch.cuda.set_sync_debug_mode("warn"), counting syncs per step for steps 2 and later. Setup: FLUX.2-klein-base-4B, 768x768, 12 steps, guidance 4, CFG batching forced, offloaded under a 10 GB VRAM cap. Base and head ran interleaved (base, head, base, head) on one card.

syncs per step in the loop from the CFG-batch check
base 4.73 4.55
head 1.09 0.91
  • Outputs: the first base/head pair produced byte-identical images. The second pair differs, but base vs base differs by the same amount. That variation already exists on this path (forced batching under offload on a shared card) and is not caused by this change.
  • Timing: s/step on a heavily shared host spread 0.155 to 0.437 s between the two base runs, so no speed claim is made here.

Tests

  • tests/test_diffusion_cfg_batch_sync.py (new):
    • _bitwise_equal_all gives the same answer as the per-pair form for every single pair and every 3-pair combination. Cases cover NaN, -0.0 vs 0.0, non-contiguous views, stride-0 expands, empty tensors, dtype and shape mismatches, and non-tensors.
    • _matches answers are unchanged.
    • On CUDA, six tensor arguments cost exactly one .item() and no torch.equal.
  • Also run: test_diffusion_cfg_batch.py, test_diffusion_multigpu.py, test_diffusion_multigpu_wiring.py, test_diffusion_cfg_parallel_tier.py, test_diffusion_multigpu_cuda.py. 182 CPU tests passed, plus the CUDA test. The 4 tests in test_diffusion_multigpu_cuda.py that need two GPUs were skipped.

Not covered

  • CFG-parallel on two real GPUs: the 2-GPU tests were skipped on this run.
  • At Studio defaults (compiled and resident, or replaying CUDA graphs), CFG batching does not arm, so default renders do not run this check.

…el argument checks

The second branch's arguments were verified with one torch.equal per tensor
argument, each a blocking device-to-host read (about 4.5 per step on
FLUX.2-klein-base with CFG batching). Compare every pair on its device and
read one combined flag per device instead; the verdict is unchanged.
@danielhanchen danielhanchen self-assigned this Oct 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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-22T15:28:18.519093Z 050645c 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. Another round soon, please!

Reviewed commit: 050645c89c

ℹ️ 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 cf3134d into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the diffusion_sync_audit branch October 22, 2026 21:26
danielhanchen added a commit that referenced this pull request Oct 23, 2026
…cesses so a seed keeps one path (#14849)

## Problem

Single-card CFG batching (#13787, defaults from #14566, #14652, #14734)
decides per request shape whether both guidance branches run as one
doubled call. Batched is a tolerance mode (about LPIPS 0.01-0.02 versus
plain on some models, since the doubled batch can pick other kernels),
so the same seed and prompt only give the same image if every render
takes the same path. Three ways that choice could change:

1. **Between processes.** The verdict lived only on the router
(`CfgBatchRouter.shapes`, keyed on the argument tensor shapes, per
load). Every new process or reload re-ran the 2-sample trial
(`min(batched) > 0.92 * min(plain)`, plus the single-sample
`_RESIDENT_MAX_PAIR_S` gate). A shape near the 0.92 line landed on
either side depending on timing noise.
2. **Between renders in one process.** A shape turned off by memory
pressure (`_OFF_TRANSIENT`: no room before the trial, or an OOM on a
doubled call) had `judged` reset in `end_render`, so the next render
re-timed it and could latch "measured no gain" for the rest of the load.
3. **Within one render.** `_batched` returned plain for a single step
when free memory read below 2x the activation peak and batched again on
the next step, so a fluctuating free-memory reading mixed paths step by
step.

Probe with a controlled timer (per-call lognormal noise, 40 fresh loads
per cell; P = plain pair, B = doubled call):

| doubled / plain pair | noise sigma | main | this PR |
|---|---|---|---|
| 0.92 | 0 (A/A) | 40/40 batched | 40/40 batched |
| 0.90 | 0.05 | 29 batched, 11 plain | 40/40 one path |
| 0.92 | 0.02 | 22 batched, 18 plain | 40/40 one path |
| 0.94 | 0.05 | 20 batched, 20 plain | 40/40 one path |

One transient OOM on render 2, ratio 0.91, sigma 0.03: render 1 and
render 4 took different paths in 2/40 loads on main, 0/40 here. Free
memory moving around the line each step on main: `PPPBPBBB`, `PPBBPPBP`.

## Fix

- The timing verdict is latched on the shape (`_Shape.verdict`). A
transient memory off still makes that render plain, but the next render
batches again from step 3 without a new trial.
- Verdicts are stored in `diffusion_cfg_batch_verdicts.json` next to the
learned peaks. The key covers the load (denoiser class, config, layer
classes, weight dtypes, offload policy, speed tier), the card name,
compiled or eager, the request shape, and the runtime stamp (torch,
diffusers, kernel packages). First writer wins under the same file lock
as the learned peaks, so a later process takes the stored path with no
trial. Only measured timing verdicts are stored. Nothing is stored off
CUDA or for a load that cannot be identified.
`UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS=0` keeps the verdict per load, and
`UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS_FILE` sets the path.
- If a doubled call has no room mid-render, the shape stays plain for
the rest of that render. It no longer skips single steps.
- OOM safety is unchanged: no room or an OOM still falls back to plain
for that render. A shape whose first doubled call comes from a stored
verdict counts that render as its warm-up, so the compiled-graph rules
match the trial path. Nothing changes under Dynamo tracing (the router
still passes straight through) and there is no new per-step work. The
store is read once per shape per load.

## Tests

- New in `studio/backend/tests/test_diffusion_cfg_batch.py`: a
borderline shape keeps one path across fresh loads (both verdicts),
memory pressure never re-times a judged shape, no room mid-render keeps
the rest of that render plain, and the store is keyed on the card and
skipped off CUDA. All 5 fail on main and pass here.
- `test_diffusion_cfg_batch.py`, `_cfg_batch_sync`,
`_cfg_parallel_tier`, `_zimage_cfg_split`, `_speed`,
`test_diffusion_backend.py`, `test_video_backend.py` with `-n 8`: 1465
passed here; on main 1460 passed and the 5 new tests failed.
- Real CUDA (B200, tiny random FLUX.2-klein, resident bf16, CFG 4, 6
steps, 256x256): process 1 ran the trial and stored `batch`. Process 2
skipped the trial (`[1, 1, 1, 1, 2, 2, 2, 2]`) and gave the same image
hash as process 1.

## Not covered

- No real-model LPIPS run: the probe shows the path choice, and the
image difference between paths is the tolerance already measured in
#13787.
- A stored verdict is not re-measured after a driver change, or after
other changes that leave the key the same. Deleting the file or setting
`UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS=0` resets it.
- If memory really runs short partway through a render, that render
still switches to plain from that step on. This is the intended OOM
fallback.
- `activation_mib` is only known when a plain call raises the process's
peak counter, so whether the memory gate applies still depends on
process history. Unchanged here.
- `test_diffusion_backend.py::test_begin_load_rejects_concurrent` hit
its 30 s thread timeout on a loaded host. It fails the same way on main
and is unrelated.

---------

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