Skip to content

Studio diffusion: keep CFG batching off for a resident denoiser with no device timer (CPU, MPS) - #14652

Merged
danielhanchen merged 1 commit into
mainfrom
kfix-cfg-batch-untimed-device
Oct 22, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
kfix-cfg-batch-untimed-device

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

#14566 turned CFG batching on for resident denoisers, behind the per-shape timing gate: a shape batches only where one doubled call was measured at least 8% faster than two plain calls. That gate needs a CUDA device timer. When the latents are not on CUDA (a CPU load, or MPS on Apple Silicon), CfgBatchRouter._trial skipped the measurement and judged the shape as batchable anyway. So every guided render on CPU or MPS batched both guidance branches without being measured, and its output changed compared with before #14566.

Before #14566 this branch was only reachable by offloaded denoisers, which are always on CUDA in practice. The resident path made it reachable on CPU and MPS.

What it does

  • diffusion_cfg_batch.py: when the trial cannot time the doubled call and the denoiser is resident, the shape is turned off with the reason no device timer on <device> to price the doubled call. UNSLOTH_DIFFUSION_CFG_BATCH=force still batches. Offloaded denoisers, and anything on CUDA (ROCm included), behave as before.
  • New test test_a_resident_denoiser_off_cuda_stays_plain_unless_forced: a resident CPU denoiser renders twice with only plain calls, matches two plain calls exactly, and reports the reason. Under force it still batches. The test fails on main and passes with this change.

Evidence

Found on a Kaggle CPU kernel (no GPU) while checking today's merged diffusion PRs against their merge base (9f303b3). This is the tiny Wan pipeline through Studio's real VideoBackend, guidance 5, 2 prompts, same seeds:

tree CFG batched steps (prompt 1 / 2) shape off reason frame hash prompt 1 prompt 2
merge base 9f303b3 not armed - 8c598ead de66c6a0
main 2749eee 2 / 4 none (batched without a measurement) a48be48b b6eb8278
this branch 0 / 0 no device timer on cpu 8c598ead de66c6a0

The same thing showed up on Kaggle's CPU kernel: main batched 2 / 4 steps and its frames differed from the merge base.

On CUDA nothing changes: on a Kaggle T4 the gate already measures and keeps batching off for compute-bound FLUX.2-klein-base-4B pairs (compute-bound: a plain pair takes 2.40 s).

Tests

  • pytest studio/backend/tests/test_diffusion_cfg_batch.py: 35 passed, 1 skipped (the CUDA timer test, run on a CPU host).

…no device timer (CPU, MPS)

The resident-denoiser CFG batching from #14566 is gated on a per-shape timing trial, but the trial
judged a shape as batchable whenever the latents were not on CUDA, so CPU and MPS loads batched
both guidance branches without any measurement and rendered differently from before. Such a shape
now stays plain unless UNSLOTH_DIFFUSION_CFG_BATCH=force.
@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-22T10:21:15.122630Z ed32eba 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. What shall we delve into next?

Reviewed commit: ed32eba7ee

ℹ️ 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 cc10707 into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the kfix-cfg-batch-untimed-device branch October 22, 2026 17:43
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant