Skip to content

Studio diffusion training: plan the nf4 dequant cache around the checkpointing budget (no step-2 OOM fallback; klein 1024 on L4 11% faster, 5.4 GB lower peak) - #18416

Merged
danielhanchen merged 7 commits into
mainfrom
studio-dit-cache-gc-budget
Nov 19, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
studio-dit-cache-gc-budget

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

The nf4 dequant cache (#18345) and budgeted gradient checkpointing (#18301) both size themselves after step 1 from the same free-memory reading, and each takes 85% of it. When a run needs most of that room for both, step 2 runs out of memory. The trainer then falls back to checkpointing every block, which costs the whole gc speedup. #18345's PR body flagged this interaction.

This PR has the two planners share one budget:

  • gc budget first. Kept activations save far more time per GiB than cached weights, so the gc plan is the same one it makes alone.
  • The cache re-plans on the room the kept activations leave. Its cap becomes its own plan minus 0.85 x the kept-activation bytes, the same 85% share it takes of any free room. The max(2 GiB, 10% of the card) margin and the per-step live check are unchanged, so step 2 no longer runs out of memory, and a card with room for both keeps its whole cache.

Colab L4, eager, 40 steps, nf4, rank 16:

family main s/step this PR s/step OOM fallback, main / PR peak GB, main / PR
FLUX.2-klein-4B 1024 px 4.548 [4.547-4.548] 4.035 [4.034-4.037] (-11.3%) 3/3 / 0/3 22.50 / 17.12
FLUX.2-klein-4B 512 px 0.905 [0.898-0.906] 0.918 [0.911-0.918] (+1.4%) 0/3 / 0/3 18.45 / 17.43
Wan2.2-TI2V-5B 704 px 0.374 [0.372-0.375] 0.376 [0.372-0.378] (same) 0/3 / 0/3 17.17 / 17.17

Changes

core/training/diffusion_dit_trainer.py, new _plan_after_first_step. It runs right after step 1's optimizer step, when the cache has already sized itself in the optimizer hook. The cache is still empty at that point, because step 1 caches nothing.

  1. gc plan. The gc budget plans as before. A pinned cache budget (UNSLOTH_DIFFUSION_DEQUANT_CACHE_GB) is counted as already used.
  2. Reserve. The kept-activation bytes are reserved in the cache with reserve(kept, from_plan = True). This lowers the cache's cap to its plan minus 0.85 x the reservation and keeps the bytes out of its per-step rebalance.
  3. Report. dequant_cache_planned is emitted after the reservation, so it reports the budget the cache really has. It now includes reserved_gib.
  4. OOM fallback. If step 2 still runs out of memory, the reservation is handed back with reserve(0, from_plan = True). The cache can then regrow through its rebalance, as live memory allows.

core/training/diffusion_lora_fast.py, Nf4DequantCache:

  • reserve(nbytes, from_plan = False). Without from_plan it behaves exactly as before: it only narrows rebalancing.
  • With from_plan, it lowers the cap and the budget to the plan minus the reservation, and evicts the newest entries if they no longer fit.
  • A pinned budget is never shrunk.

Unchanged:

  • Kill switches: UNSLOTH_DIFFUSION_DEQUANT_CACHE=0, UNSLOTH_DIFFUSION_FAST_LORA=0, UNSLOTH_DIFFUSION_GC_MODE=plain.
  • One feature off: with either feature off, the other plans exactly as on main.
  • Compiled runs: these have no dequant cache, so the gc plan is main's.
  • Per-step cost: the new code runs once after step 1 (and on an out-of-memory fallback), on the host between steps. It adds no per-step device query or sync and nothing inside compiled regions.

Results

Same Colab L4 VM per family. Arms are interleaved, each in a fresh process: main, this PR, main with the cache off, and main with the gc budget off. There are 3 repeats each, after one untimed warm-up run. s/step is the median over steps 2 to 40, shown as median [min-max] across the 3 runs.

FLUX.2-klein-4B, 1024 px:

arm OOM fallback blocks kept (GiB) cache planned / held GiB s/step peak GB
main 3/3 12 of 25 (10.23) 10.91 / 7.22 4.548 [4.547-4.548] 22.50
this PR 0/3 12 of 25 (10.23) 0.69 / 0.63 4.035 [4.034-4.037] 17.12
main, cache off 0/3 12 of 25 (10.23) none 4.037 [4.037-4.038] 16.44
main, gc budget off 0/3 none 12.33 / 7.22 4.551 [4.550-4.551] 13.21

FLUX.2-klein-4B, 512 px:

arm OOM fallback blocks kept (GiB) cache planned / held GiB s/step peak GB
main 0/3 25 of 25 (7.13) 13.54 / 7.22 0.905 [0.898-0.906] 18.45
this PR 0/3 25 of 25 (7.13) 6.41 / 6.27 0.918 [0.911-0.918] 17.43
main, cache off 0/3 25 of 25 (7.13) none 0.988 [0.983-0.988] 10.69
main, gc budget off 0/3 none 14.00 / 7.22 1.276 [1.273-1.276] 11.08

Wan2.2-TI2V-5B, 704 px:

arm OOM fallback blocks kept (GiB) cache planned / held GiB s/step peak GB
main 0/3 30 of 30 (3.41) 13.66 / 9.29 0.374 [0.372-0.375] 17.17
this PR 0/3 30 of 30 (3.41) 10.26 / 9.29 0.376 [0.372-0.378] 17.17
main, cache off 0/3 30 of 30 (3.41) none 0.478 [0.478-0.483] 7.26
main, gc budget off 0/3 none 13.75 / 9.29 0.620 [0.613-0.625] 13.57

Mean |delta loss| per step over 40 steps, as median [min-max] over pairs:

family main vs main (3 pairs) PR vs PR (3 pairs) PR vs main (9 pairs)
klein 1024 px 0.000060 [0.000045-0.000061] 0.000038 [0.000032-0.000039] 0.000047 [0.000035-0.000059]
klein 512 px 0.000127 [0.000090-0.000131] 0.000098 [0.000094-0.000139] 0.000103 [0.000070-0.000140]
Wan 704 px 0.000055 [0.000050-0.000056] 0.000055 [0.000046-0.000060] 0.000059 [0.000042-0.000071]

Reading the tables:

  • klein 1024 px:
    • On main, all 3 runs hit the OOM fallback at step 2 and ran at the cache-only speed. Peak was 22.5 GB, the whole card.
    • With this PR the gc plan holds: no fallback, the gc-only speed, and a peak about 5 GB lower.
  • klein 512 px: there is room for both features. Main uses about 0.8 GiB more than one planner's budget, eating into the 15% share. This PR keeps that share, so the cache holds 6.3 of 7.2 GiB. That is 1.4% slower than main, with a 1.0 GB lower peak, and still faster than either feature alone.
  • Wan 704 px: the dequantised weights (9.29 GiB) are smaller than the cache budget left after the gc reservation (10.26 GiB), so nothing changes.

Loss: PR vs main sits inside the spread of main vs main and PR vs PR. The mean loss over 40 steps matches main to within 0.00002 for every family. On Wan, where this PR changes nothing (same blocks kept, same 9.29 GiB cached), PR vs main reaches 0.000071 against 0.000060 for PR vs PR, which is the same run-to-run noise.

Tests

studio/backend/tests/test_diffusion_gc_budget_dequant_cache.py, 14 CPU tests. They drive step 1 through the real optimizer hooks with simulated CUDA memory, using T4 klein (the observed case: a 7.44 GiB cache with all 25 blocks kept), L4 klein 1024 px and A100 Wan. They check:

  • Within one budget: kept activations plus the cache budget stay inside one planner's budget, and step 2's projected memory leaves the margin.
  • gc plan unchanged: the gc plan is identical to the one it makes alone, and the cache keeps exactly the rest.
  • Pinned budget: a pinned cache budget is held out of the gc plan and never shrunk.
  • No gc budget: with no gc budget, the cache plan is unchanged.
  • Reserve: a reservation evicts the newest entries, is handed back on fallback, and regrows through rebalance. Without from_plan it behaves as before.
  • No cache: without a cache (compiled runs, ROCm, bf16 bases, cache kill switch), the joint plan is exactly main's gc plan.
  • No new device queries: step 1 reads free memory twice, as on main. reserve makes no device call, and later steps keep main's single rebalance probe.

The 10 planner tests fail on main except the no-gc-budget case, which passes on both. All 14 pass here.

The suites test_diffusion_lora_fast*.py, test_diffusion_gc_budget*.py and test_diffusion_dit_trainer*.py give 310 passed and 17 skipped. On main the same suites have no other failures.

Not covered

  • T4: main refuses DiT training on cards without bf16, so the observed T4 fp16 case was only modelled in the CPU test.
  • Families not run on GPU: FLUX.1, Z-Image, Qwen-Image, FLUX.3, LTX-2 and MOSS-Image. The change is family-neutral.
  • A100: not run.
  • klein 512 px revision: the PR arm ran one revision earlier, where reserve always cut the plan. The trainer's two calls behave identically there. The 1024 px and Wan arms ran the final code.
  • Training modes not run on GPU: bucketing, grad accumulation above 1, mid-run previews and resume.
  • Other platforms: ROCm, XPU and Windows. The dequant cache is CUDA-only, and the gc budget does not engage on ROCm or XPU.

Update: the cache keeps its share on cards with room for both

The first version took every kept-activation byte off the cache plan, so the cache also shrank on cards where main fit both, and those cells ran 1.4% to 2.0% slower. The cap is now the plan minus 0.85 x the kept bytes (the cache's usual share of the room they leave). Margin, live check and the gc plan are unchanged. Interleaved on one VM per row, fresh processes:

cell main first version now
L4 klein 1024 px 4.664 s/step, OOM fallback 1/1, 22.5 GB 4.135, 17.12 GB 4.118, 18.82 GB, no fallback
L4 klein 512 px 0.941 [0.934-0.949] 0.959 (+2.0%) 0.948 [0.947-0.949], inside main's range, same peak
A100-SXM4-40GB klein 1024 px 0.707, 35.43 GB 0.719 (+1.7%), 30.31 GB 0.711 (+0.6%), 33.67 GB

Loss is inside main's run-to-run spread in every arm. Across 2304 simulated planner cells (base vs this PR), 339 move, none gets a different gc plan without a pin, and no cache cap exceeds main's. Compiled training has no dequant cache, so its plan is main's.

With #18355 merged on top, the two PRs conflict only where both add helpers at the same spot (keep both); on fp16, #18355 turns the cache off and this change reduces to main's gc plan. The merged tree passes 245 tests, 1 skipped.

…t's kept activations

Both step-1 planners sized themselves from the same free memory, so with the
nf4 dequant cache and budgeted gradient checkpointing on together step 2 could
run out of memory and fall back to checkpointing every block. The gc budget now
plans first and the cache keeps what is left of its plan (reserve with
from_plan); a pinned cache budget is held out of the gc plan instead, and an
OOM fallback hands the reservation back to the cache.
…in without a cache and adds no device queries
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T07:29:21.397358Z 39ea595 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: c915d75852

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

…om kept activations leave

Taking the kept-activation bytes off the cache plan whole kept both planners inside one planner's
budget, which also cut the cache on cards that had room for both. The cache now re-plans on the room
the kept activations leave: plan minus 0.85 x kept. Measured on the same VMs, interleaved:

- L4, FLUX.2-klein-4B 512 px: every nf4 weight stays cached (7.22 GiB); s/step back inside main's
  range (main 0.934-0.949, before 0.959-0.960, now 0.947-0.949), same peak as main.
- L4, klein 1024 px: still no OOM fallback (main 1/1), 4.117-4.120 s/step vs 4.131-4.139 before.
- A100-40GB, klein 1024 px: +0.6% vs main instead of +1.7%, peak 33.67 GB vs main's 35.43.

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: bd50a9adde

ℹ️ 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/core/training/diffusion_dit_trainer.py

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 72e644030e

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

…f-memory rerun

Step 1's dequant cache plan reads torch.cuda.max_memory_allocated(). After a
step-1 out-of-memory error the rerun kept the failed attempt's near-full peak,
so the cache was planned to nothing for the whole run. The rerun now banks that
peak for the reported training peak and restarts the allocator peak.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 39ea595c6f

ℹ️ 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 4db250a into main Nov 19, 2026
@danielhanchen
danielhanchen deleted the studio-dit-cache-gc-budget branch November 19, 2026 09:23
danielhanchen added a commit that referenced this pull request Nov 20, 2026
… (exact, +7.4% with spare memory) (#18451)

## Problem

When Auto (or the user) picks an int8 base for diffusion LoRA training,
the frozen int8 layers run eager, because int8 never compiles in
training. torchao then rebuilds the bf16 weight on every forward and
backward call. nf4 bases already have a budgeted dequant cache for this;
int8 bases had none.

## Change

The budgeted dequant cache now covers int8 bases too:
- **What is cached:** the int8 weight cast to bf16, which torchao
rebuilds on each call. Forward and backward are bit-identical to today.
- **torchao layouts:** both are covered, 0.14-0.17 and 0.18.
- **Self-check:** the first cached layer is compared with torchao's own
output. A mismatch turns int8 caching off for the run.
- **Memory budget:** it shares the nf4 cache's budget and the
checkpointing reserve from #18416. It also gives its memory back under
`lend_vram`, the same as nf4.
- **Kill switch:** `UNSLOTH_DIFFUSION_INT8_DEQUANT_CACHE=0`.

## Results

| cell | card | change |
|---|---|---|
| FLUX.3 klein base, int8, 512 px, memory to spare | Colab L4 | +7.4% |
| FLUX.3 klein base, int8, in Auto's tight int8 band (16 GB simulated) |
Colab L4 | +0.3 to 0.6%, inside the noise; peak memory +0.1 to 0.17 GB |
| FLUX.3 klein base, int8, 1024 px | Colab L4 | under 1% |

- **Exactness (B200, correctness only):** with checkpointing and 3 AdamW
steps, losses and gradients are bit-identical with and without the
cache.
- **End to end on GPU:** training is not repeatable run to run, so the
gate there is the loss inside the spread of repeated identical runs,
which holds.
- **Depends on #18416:** without #18416's shared budget, the cache made
Qwen-Image-2.1 on L4 run out of memory at step 2. #18416 is merged, so
this PR builds on it.

## Tests

- `tests/test_diffusion_int8_dequant_cache.py` is new, with 13 CPU
tests. They pass on torch 2.14 / torchao 0.18 / transformers 5.17, and
on torch 2.6 / torchao 0.15 / transformers 4.57.6 / peft 0.18.
- With the checkpointing-budget and trainer suites on current main: 146
passed.
danielhanchen added a commit that referenced this pull request Nov 20, 2026
…H3, step down after OOM, cached fp8 backward weights (#18518)

## Summary

Three changes to diffusion LoRA training, all exact (same kernels on the
same inputs, so losses and gradients do not change):

1. **Checkpointing budget in the SDXL, MiniMax-H3 video and
MiniMax-H3-Image trainers.** These trainers still checkpointed every
block. After step 1 they now keep the activations of as many blocks as
free memory allows, which is what the DiT trainer has done since #18301
/ #18416.
2. **Step down after an out-of-memory error instead of giving up.** If a
step runs out of memory while blocks are kept, the kept bytes are halved
and the step is rerun from its host copies. Before, the run checkpointed
every block from then on.
3. **fp8 training keeps the column-major weight that grad_x needs.**
Before, it was copied from the row-major weight on every backward. The
copies use only the room the checkpointing plan left unused.

## What changes

- `diffusion_gc_budget.BudgetedSteps` is the loop side of the budget,
shared by all three new trainers. It records each micro-batch's inputs
and RNG state on the host, reruns the whole step after an out-of-memory
error, and plans the budget after the first optimizer update. An fp16
step that the GradScaler skipped is never planned on.
- The plain path is still the fallback: ROCm, non-CUDA devices,
`UNSLOTH_DIFFUSION_GC_MODE=plain|partial`, and diffusers models without
`gradient_checkpointing_func`.
- `BudgetedCheckpoint.step_down()` keeps at most half the kept bytes and
always drops at least one block. It checkpoints every block only when
nothing is left to drop, or when the error hit while step 1 was still
measuring.
- The DiT trainer uses the same rule, and a second error during the
rerun steps down again.
- The plan also keeps a cheaper block that comes after one that does not
fit, instead of stopping at the first miss.
- fp8 (`diffusion_frozen_fp8`): the grad_x GEMM runs through an opaque
custom op that looks up `Fp8BackwardWeights`. Because the op is opaque,
the compiled graph is the same whether the cache fills, clears or is
lent back to Studio through `lend_vram`. There is no recompile and no
graph break.
- An uncached layer is copied by a tiled Triton transpose (aten when
Triton is missing). An earlier version used aten's strided copy here and
was 22% slower on L4 when nothing was cached; the measurements below are
for the fixed version.
- The op path is only traced in during a budgeted trainer run.
Everything else, and `UNSLOTH_DIFFUSION_FP8_BWD_CACHE=0`, keeps the
inline copy exactly as before.

## Numbers

All on Colab, 50 steps, seed 0, rank 16, 8-image dataset, same VM per
table. s/step is the median of steps 3 to 50; peak is torch
`max_memory_allocated`.

SDXL base 1.0, compiled bf16 (L4, 1024 px) and fp16 (T4, 768 px):

| card | base s/step (A/A) | head s/step (2 runs) | change | peak GB
base -> head | blocks kept |
|---|---|---|---|---|---|
| L4 | 0.665 / 0.679 | 0.466 / 0.464 | -31% | 6.12 -> 11.71 | 86 / 86 |
| T4 | 0.879 / 0.890 | 0.635 / 0.637 | -28% | 5.88 -> 9.11 | 86 / 86 |

Loss trajectories sit inside the A/A band. L4: mean per-step difference
6e-6 head vs base, against 4e-6 base vs base. T4: 1e-6 for both.

Step down after an out-of-memory error. FLUX.3 klein base, bf16
compiled, L4, 512 px. After the step-1 plan, free memory was cut to step
1's transient plus 0.55x the kept bytes, so the planned keep set no
longer fits:

| tree | after the error | s/step |
|---|---|---|
| base | every block checkpointed | 0.788 |
| head | 20 of 38 blocks kept (one step down) | 0.669 (-15%) |

fp8 backward weights. FLUX.3 klein base, fp8 compiled, L4, 512 px, base
A/A 0.4535 / 0.4583 / 0.4547:

| arm | s/step | vs base median | peak GB | layers cached |
|---|---|---|---|---|
| room for every layer | 0.4237 / 0.4231 | -6.9% | 11.29 -> 15.29 | 194
(3.69 GiB) |
| room for half (plan capped at 1.8 GiB) | 0.4419 | -2.8% | 13.23 | 97 |
| no room (plan 0) | 0.4561 / 0.4566 | +0.3%, inside the 1% A/A spread |
11.29 | 0 |
| `UNSLOTH_DIFFUSION_FP8_BWD_CACHE=0` | 0.4568 | +0.5%, inside the
spread | 11.29 | 0 |

The loss trajectory stays inside the base A/A band: 0.0004 to 0.0006
mean per-step difference, against 0.00043 to 0.00048 between base runs.

Graph breaks: 0 on every arm. Unique graphs: equal base vs head (SDXL 3,
fp8 5, bf16 3). Host syncs per step under
`torch.cuda.set_sync_debug_mode("warn")`: SDXL 3 vs 3, fp8 2 vs 2.

## Tests

New `tests/test_diffusion_gc_budget_trainers.py` and
`tests/test_diffusion_frozen_fp8_bwd_cache.py`; updated
`test_diffusion_gc_budget.py` and `test_diffusion_gc_budget_replay.py`.
The new and updated tests fail on the merge base (20 failed, 7 errors)
and pass here. They cover:

- **Step down:** the arithmetic, planning past a block that does not
fit, scaling to the largest bucket, the measuring case, and zero-byte
blocks.
- **`BudgetedSteps`:** the rerun is bit-identical, including the RNG
left after it, with one or two failures inside one step. Other errors
are never retried. A plan with nothing kept re-raises the error. The
plan runs once.
- **End to end on CPU, tiny SDXL and tiny MiniMax-H3-Image
(deterministic mode):** the budget keeps every block, and the trained
adapter and losses are `torch.equal` to full checkpointing. An
out-of-memory error injected in step 2 steps down once and still gives
the identical adapter.
- **DiT trainer:** two out-of-memory errors in one step step down twice
and match the clean run bit for bit. An error while measuring
checkpoints every block.
- **fp8 cache:** grad_x is `torch.equal` with the cache on or off. The
cache keeps to its budget. `lend_vram` frees the copies and they come
back after the return. An inactive cache never touches the backward, and
the kill switch works.
  - A compiled graph keeps one graph across budget changes.
- CUDA only: the tiled transpose matches aten byte for byte on seven
shapes.

Related suites (gc budget, dequant cache, replay, base precision, fp8
prequant, VRAM lend, train perf / speed, hot loop, checkpoint resume,
bucketing, samples, H3 / H3-Image / SDXL trainers, training routes)
pass. The 3 failures in `test_integrated_gpu_no_host_pin.py` also fail
on the merge base.

## Not covered

- The MiniMax-H3 video and H3-Image trainers were checked on CPU only,
with tiny models, and with real weights on no GPU. Their speed-up is not
measured here.
- The step-down numbers come from a forced memory cut, not a natural
out-of-memory error. #18416 removed the known natural trigger (nf4 cache
plus budget on L4).
- AMD stays on the plain path, as before.
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