Skip to content

Studio diffusion: latch the CFG-batch verdict per load and across processes so a seed keeps one path - #14849

Merged
danielhanchen merged 2 commits into
mainfrom
studio-cfg-batch-latch-decision
Oct 23, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-cfg-batch-latch-decision

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 Studio diffusion: single-card CFG batching for a DiT streamed from host memory #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.

…cesses

The batched-or-plain choice for a request shape came from a live
2-sample timing gate, and a shape turned off by memory pressure was
re-timed on the next render. A borderline shape could therefore take a
different path (and give a slightly different image for the same seed)
in another process, or on a later render after one transient OOM; a
free-memory reading near the line also alternated batched and plain
steps inside one render.

- The timing verdict is latched on the shape: a transient memory off
  retries batching on the next render without re-timing.
- Verdicts are stored next to the learned peaks, keyed on the load
  (class, config, layer classes, dtypes, offload policy, speed tier),
  card, compiled or eager, request shape and runtimes; first writer wins,
  so every later process takes the stored path without a trial.
  UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS=0 keeps it per load.
- No room for a doubled call mid-render turns the shape plain for the
  rest of that render instead of skipping single steps.
@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-23T01:30:31.594431Z 07e3332 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: 07e3332137

ℹ️ 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 f15d723 into main Oct 23, 2026
2 of 34 checks passed
@danielhanchen
danielhanchen deleted the studio-cfg-batch-latch-decision branch October 23, 2026 02:56
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 24, 2026
…just the module layout (unslothai#15047)

## Summary

The cross-process CFG-batch verdict store (unslothai#14849) keys the
batched-vs-plain decision on a load identity that cannot tell a bf16
load from a torchao INT8 or FP8 dynamic load of the same model. A
verdict timed on one is reused on the other without timing. This PR adds
the weight tensor classes and the engaged `transformer_quant` to the
key, and bumps the store version so old entries simply miss. Every other
part of the verdict store is unchanged, so a shape still takes one path
in every process.

## Details

- After torchao `quantize_`, layers are still `nn.Linear` and the
weights still report `torch.bfloat16`, so `_load_identity` hashed bf16,
INT8-dynamic and FP8-dynamic (PerRow) to the same sha1. An INT8 or FP8
load could then be stuck on the path that was faster for bf16, or miss a
gain. Pixels were within the batched tolerance either way, so this is
speed only.
- `_load_identity` now also hashes each parameter's tensor class and,
for torchao subclasses, their non-tensor attributes (`mm_config`,
`act_quant_kwargs`, `kernel_preference`, `dtype`; `block_size` is
skipped since it only follows the layer shape). This separates fp8 with
and without fast accumulate too.
- `install_cfg_batch` takes `transformer_quant`. The image
(`diffusion.py`) and video (`video.py`) loads pass
`transformer_quant_engaged`, the scheme the load already records, so
GGUF and other non-torchao quant paths are covered as well.
- The key also carries the live attention backend
(`_unsloth_attention_backend`), read when the verdict is looked up.
`set_attention_backend()` changes neither the module classes nor the
config, so the load identity alone missed a backend switch.
- The store `version` goes from 1 to 2, and the reader ignores a file of
another version. Old entries simply miss and are replaced on the next
write.

## Tests

New tests in `studio/backend/tests/test_diffusion_cfg_batch.py`, all 6
fail on main and pass here:

- `test_the_verdict_key_tells_bf16_from_torchao_int8_and_fp8_loads`:
bf16, INT8, FP8 fast accumulate on and off all give different keys.
- `test_the_verdict_key_includes_the_engaged_transformer_quant`
- `test_the_same_load_gives_a_stable_verdict_key`: a deep copy of each
load gives the same key.
- `test_install_keys_the_router_on_the_engaged_quant`
- `test_the_verdict_key_follows_the_live_attention_backend`
- `test_a_version_1_verdict_store_is_not_read`

`pytest tests/test_diffusion_cfg_batch.py
tests/test_diffusion_cfg_batch_sync.py`: 48 passed, 2 skipped.
`tests/test_diffusion_memory_vram_budget.py -k cfg`: 3 passed. CPU only.
The speed effect on a real GPU of reusing a bf16 verdict on an INT8 or
FP8 load was not measured.
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