Repository navigation
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
Conversation
…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
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…n tests [skip ci]
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
… (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.
…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.
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:
Colab L4, eager, 40 steps, nf4, rank 16:
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.UNSLOTH_DIFFUSION_DEQUANT_CACHE_GB) is counted as already used.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.dequant_cache_plannedis emitted after the reservation, so it reports the budget the cache really has. It now includesreserved_gib.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). Withoutfrom_planit behaves exactly as before: it only narrows rebalancing.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.Unchanged:
UNSLOTH_DIFFUSION_DEQUANT_CACHE=0,UNSLOTH_DIFFUSION_FAST_LORA=0,UNSLOTH_DIFFUSION_GC_MODE=plain.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:
FLUX.2-klein-4B, 512 px:
Wan2.2-TI2V-5B, 704 px:
Mean |delta loss| per step over 40 steps, as median [min-max] over pairs:
Reading the tables:
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:from_planit behaves as before.reservemakes 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*.pyandtest_diffusion_dit_trainer*.pygive 310 passed and 17 skipped. On main the same suites have no other failures.Not covered
reservealways cut the plan. The trainer's two calls behave identically there. The 1024 px and Wan arms ran the final code.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:
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.