Skip to content

Studio diffusion training: cast-once LoRA path and nf4 dequant cache (eager DiT LoRA 16-26% faster per step) - #18345

Merged
danielhanchen merged 3 commits into
mainfrom
studio-diffusion-lora-cast-fuse
Nov 18, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio-diffusion-lora-cast-fuse

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Eager (under 200 steps, Studio's default) nf4 DiT LoRA training spends 26 to 51% of device time on elementwise LoRA casts and adds, and up to 22% on nf4 dequantisation, which runs three times per micro-batch: forward, checkpoint recompute and backward.

This PR removes both costs:

  • FLUX.2-klein-4B: 16% faster per step.
  • Wan2.2-TI2V-5B: 26% faster per step.

Both hold on Colab L4 and A100. Loss curves and final LoRA weights stay inside main's own run-to-run band.

card family main s/step [min-max] this PR s/step [min-max] change dequant cache off device ms/step, main to PR
A100-40 klein 512px r16 0.384 [0.383-0.385] 0.322 [0.320-0.322] -16.3% -7.3% 351 to 298
A100-40 Wan 704px r32 0.843 [0.842-0.846] 0.620 [0.620-0.624] -26.4% -6.4% 275 to 208
L4 klein 1.495 [1.494-1.497] 1.249 [1.248-1.252] -16.4% -8.1% 1437 to 1232
L4 Wan 0.902 [0.895-0.908] 0.671 [0.668-0.673] -25.6% -6.6% 535 to 379

Setup: 40 eager steps, nf4 base, gradient checkpointing on. Arms run interleaved in fresh processes on the same VM, 3 repeats each for main and this PR.

Changes

Cast-once LoRA path (core/training/diffusion_lora_fast.py). It covers PEFT LoRA linears on nf4 or dense bases, in eager runs under autocast.

  • One input cast feeds both the base and the LoRA branch. The two branch grads are summed in the input dtype, so fp32 inputs keep PEFT's fp32 sum.
  • bf16 copies of the fp32 A/B masters are made once per optimizer step. They are keyed on an update generation that an optimizer post-hook bumps. Studio's fused AdamW does not bump tensor versions, and a test covers that case.
  • B(A(x)) runs with PEFT's own GEMMs, with no clone and no multiply when the scale is 1. Grads return to the fp32 masters.

nf4 dequant cache (Nf4DequantCache). Every bnb Linear4bit reads its dequantised bf16 weight from a cache; the weights are frozen, so entries stay valid.

  • The budget is set once after step 1:

    0.85 x (free + reserved - step-1 peak scaled to the largest bucket - optimizer state - max(2 GiB, 10% of card))
    

    With no room, nothing is cached and memory is unchanged.

  • The cache is emptied and suspended during preview renders.

  • CUDA only; ROCm is unchanged.

Kill switches:

  • UNSLOTH_DIFFUSION_FAST_LORA=0
  • UNSLOTH_DIFFUSION_DEQUANT_CACHE=0
  • UNSLOTH_DIFFUSION_DEQUANT_CACHE_GB=N pins the budget.

Compiled runs (200+ steps) are untouched.

Memory

On cards with spare VRAM, the cache uses it: training peak goes up by 7.2 GiB on klein and 9.3 GiB on Wan.

Under a 6 GiB budget, the NVML training peak stays close to main and the speedup remains:

card family main peak (GiB) this PR peak (GiB) change
A100 klein 3.37 3.56 -6.6% s/step
A100 Wan 4.26 4.41 -5.9% s/step
L4 klein 3.33 3.91 -8.6% s/step
L4 Wan 4.21 4.37 -6.7% s/step

L4 klein cached 0.40 GiB, within its planned budget. Host RAM is unchanged.

Accuracy

Mean |delta loss| per step against main, compared with main against main, over 40 steps:

card family main vs main PR vs main (3 runs)
A100 klein 0.000253 0.000228 / 0.000232 / 0.000245
A100 Wan 0.000210 0.000206 / 0.000194 / 0.000211
L4 klein 0.000167 0.000198 / 0.000227 / 0.000210
L4 Wan 0.000138 0.000139 / 0.000158 / 0.000157
  • Final LoRA weights: relative L2 is in the same range as main against main.
  • Per layer: forward, input grad and both LoRA grads are bit-identical to PEFT on an A100, for nf4 bases with bf16 and fp32 inputs (cache on and off) and for the dense base. The nf4 cache is bit-identical to per-call dequant.
  • End to end: a full deterministic run is not bit-identical to main. It drifts from step 3 by 0.0008 to 0.0021 in loss, while staying inside the band above.

Engagement

On A100 Wan:

  • 24000 fast LoRA calls (300 layers x 40 steps x forward and recompute), with 0 fallbacks;
  • 12000 master casts, one per layer per step;
  • 300 nf4 layers cached (9.29 GiB), 18300 cache hits.

Tests

studio/backend/tests/test_diffusion_lora_fast.py, 22 tests, covering:

  • parity with PEFT against an fp32 reference;
  • bit-identity on bf16 and fp32 inputs;
  • recasts after fused-AdamW steps;
  • grad accumulation with checkpoint recompute;
  • dropout and fallbacks;
  • cache exactness, budget, suspend and release;
  • kill switches.

They fail on main (the module does not exist) and pass here. The DiT trainer suites give 246 passed, 17 skipped.

Not covered

  • Families not run on GPU: FLUX.1-dev, Z-Image, Qwen-Image, FLUX.3 and LTX-2.
  • Modes not run on GPU: bucketing, grad accumulation above 1, mid-run previews, resume and EMA. These have CPU tests only.
  • Hardware not run: T4 (DiT training refuses non-bf16 cards), RTX PRO 6000, ROCm (cache disabled), XPU and Windows.
  • Interaction with Studio diffusion training: keep block activations when the card has room (20-42% faster per step, bit-identical in deterministic mode) #18301: both plan from free memory after step 1. If both land, the second should subtract the other's reservation; they were not run together.
  • VRAM taken mid-run: the cache keeps VRAM that a model loaded in Studio during training (for example a chat model) would otherwise get. It is sized at step 1 and does not shrink when that happens.

Update: the cache gives VRAM back

The dequant cache now returns its memory when something else on the card needs it:

  • Per-step rebalance: after every optimizer step, if free memory dropped, the cache evicts its newest entries until the next step plus the margin fits, then calls empty_cache(). It grows back once room returns, with a 1 GiB hysteresis.
  • Explicit lend: DiffusionTrainingService.lend_vram(reason) asks the trainer, through the existing stop queue, to drop the cache between steps, and waits up to 30 s for the acknowledgement. When the block exits, the cache re-sizes from what is free then.
    • The dictation (STT) CUDA load is wrapped in it. It was the one Studio GPU load that is not refused during diffusion training.
  • For a second per-step planner: Nf4DequantCache.reserve(nbytes) lets one such as Studio diffusion training: keep block activations when the card has room (20-42% faster per step, bit-identical in deterministic mode) #18301 keep its bytes out of the cache's room.

Colab L4, klein, 30 eager steps, with another process loading 12 GiB at step 10 and releasing it at step 20:

arm 12 GiB load at step 10 training cache
main succeeds completes none
previous head out of memory (10.65 GiB free) completes 7.2 GiB kept
this head succeeds (lend freed 7.2 GiB, 19.2 GiB free) completes re-grew to 7.2 GiB after the release

Speed is unchanged: about 1.25 s/step against 1.51 s/step on main.

tests/test_diffusion_lora_fast_vram_lend.py adds 10 CPU tests:

  • eviction order, growth hysteresis and reserve;
  • lend and return, including a preview inside a lend;
  • the post-step shrink;
  • stop-queue routing, including a lend mixed with a real stop;
  • the STT wrapper.

The related training, STT and VRAM-coexistence suites pass.

…ache)

Eager DiT LoRA runs (under 200 steps, nf4 base) spent a large share of every
step in PEFT's per-call casts, clones and fp32 adds, and in re-dequantising
the nf4 base weights in the forward, the checkpoint recompute and the
backward.

- Plain LoRA linears (nf4 or dense nn.Linear base) cast their input once
  for both branches, use bf16 copies of the fp32 A/B masters made once per
  optimizer step, and run B(A(x)) in a custom autograd function that
  returns fp32 grads to the masters. Same GEMMs, roundings and fp32 sums as
  PEFT per layer; loss curves stay inside main's run-to-run band.
- nf4 linears keep their dequantised weight in VRAM the step does not use,
  sized after step 1 from free memory and the step-1 peak (activations
  scaled to the largest bucket); suspended during preview renders; with no
  room nothing is cached.
- Both are driven from optimizer hooks, so the training loop is untouched.
  Compiled runs are unchanged. Kill switches UNSLOTH_DIFFUSION_FAST_LORA=0
  and UNSLOTH_DIFFUSION_DEQUANT_CACHE=0; UNSLOTH_DIFFUSION_DEQUANT_CACHE_GB
  pins the cache budget.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 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-18T16:06:32.566491Z e9ed035 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.

…eds it

The DiT dequant cache keeps 7-9 GiB of otherwise idle VRAM for the run.

- Every optimizer step after the plan rebalances the cache against what is
  free now: when another process took memory it stops growing and evicts
  the newest entries until the next step's activations plus the margin fit,
  then empties torch's pool so the driver can hand the memory out; when
  room comes back (past a 1 GiB hysteresis) it grows toward its plan.
- DiffusionTrainingService.lend_vram(reason): a parent-side context
  manager that asks the trainer, through its stop queue, to drop the cache
  and cache nothing; the child serves it between steps and acknowledges
  through the event queue; on exit the cache re-sizes from what is free.
  Proceeds after a timeout, as loads did before. The STT (dictation) CUDA
  load, the one Studio load not refused during diffusion training, uses it.
- Nf4DequantCache.reserve(nbytes) lets another per-step planner (budgeted
  checkpointing) keep its bytes out of the cache's room.
@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. What shall we delve into next?

Reviewed commit: e9ed0353b4

ℹ️ 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 b06f4dc into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-lora-cast-fuse branch November 18, 2026 20:29
danielhanchen added a commit that referenced this pull request Nov 19, 2026
Bring in the cast-once LoRA path, the nf4 dequant cache (#18345) and
budgeted gradient checkpointing (#18301), and make them compose with the
fp16 path:

- The fp16 step loop keeps main's OOM replay: the loss is scaled inside
  _forward_backward, so a fully checkpointed rerun is scaled too.
- The checkpointing budget is planned on the first applied update; a
  GradScaler skip allocates no optimizer moments.
- Fast LoRA and the dequant cache skip fp32 island roots. Patched on top
  of an island they ran its module under fp16 autocast. Modules inside an
  island keep the fast path, which sees autocast off and falls back to
  PEFT in fp32; their nf4 linears dequantise in fp32.
- The resume-loop source test accepts the while loop when it starts at
  resumed and advances by one applied step.
danielhanchen added a commit that referenced this pull request Nov 19, 2026
…PUs in fp16 with loss scaling (FLUX.2-klein, Z-Image, Wan 2.2 5B) (#18355)

## Summary

Studio's DiT LoRA trainer refused every GPU without native bf16, such as
the T4 (sm75), before any model loaded:

```
ValueError: This trainer requires a bfloat16-capable GPU (Ampere or newer); this CUDA device does not support bf16.
```

This PR trains FLUX.2-klein, Z-Image and Wan 2.2 5B LoRAs on those cards
in fp16 with dynamic loss scaling. Cards with bf16 keep the unchanged
code path.

On a Colab T4, fp16, 200 steps, 512 px, rank 16, nf4 base, gradient
checkpointing on:

| family | applied / skipped / NaN | s/step | peak VRAM | loss, steps
1-50 to 151-200 |
|---|---|---|---|---|
| FLUX.2-klein-base-4B | 200 / 0 / 0 | 2.79 | 3.33 GB | 0.2848 to 0.2581
|
| Z-Image Turbo | 200 / 0 / 0 | 7.82 | 4.82 GB | 0.3593 to 0.2295 |
| Wan 2.2 5B (1 frame) | 200 / 0 / 0 | 1.11 | 3.57 GB | 0.1159 to 0.1042
|

## Changes

**Which runs take the fp16 path** (`diffusion_train_common.py`):
- `dit_fp16_fallback()` is true only on an NVIDIA CUDA card without
native bf16. `UNSLOTH_STUDIO_DIT_FP16=0` brings back the old refusal;
`=force` takes the fp16 path on a bf16 card for parity checks.
- The refusal is lifted for `flux.2-klein`, `z-image` and
`wan2.2-ti2v-5b` only.
- Dense bases are refused before eviction, and the UI offers `nf4`.
- The resume identity records `fp16`.

**Precision layout** (new `diffusion_dit_fp16.py`):
- The nf4 base computes its matmuls in fp16. Every other parameter and
buffer is fp32, and latents and text embeddings enter in fp32, so the
residual stream stays fp32.
- A per-family table of fp32 islands runs with autocast off. The islands
are installed after the LoRA attaches, so their LoRA branches are fp32
too.
- Finite checks on the T4 decided the table:
- klein and Wan never overflowed; the modulation, time embedding and
output layers stay fp32.
- Z-Image needs `attention.to_out.0` and `feed_forward.w2` in fp32 in
every block. Its activations reach 8.7e5, and with only the refiners in
fp32, block 0 still overflowed.

**Trainer** (`diffusion_dit_trainer.py`):
- fp16 autocast with a GradScaler; LoRA weights stay fp32.
- Gradient accumulation scales each micro-step and unscales once before
clipping.
- A step skipped on inf gradients does not advance the LR scheduler, EMA
or step counter. 30 skips in a row raise a named error instead of
training nothing.
- The scaler state and skip count are stored in the checkpoint.
- `torch.compile` is off on this path.
- Progress events carry `grad_scale` and `skipped_steps`.

## Accuracy

Per-step loss against an L4 bf16 run at the same seed (median relative
difference):

| family | bf16 repeat vs repeat | L4 fp16 vs L4 bf16 | T4 fp16 vs L4
bf16 |
|---|---|---|---|
| klein | 4.9e-4, 5.7e-4 | 1.4e-3 | 7.3e-3 |
| Wan | 2.3e-3, 2.0e-3 | 4.2e-3 | 4.4e-2 |

- On the same card, fp16 moves per-step loss about 2 to 3 times the bf16
run-to-run noise. The final-window loss is within 0.2% of bf16.
- The larger T4 gap is the hardware change, not the precision: it is
already there in steps 1-50, and on the L4 the fp16 run stays close to
bf16.
- The samples after training are coherent for all three families.

Mechanics checked on the T4:
- **Resume** from step 50 matches the uninterrupted run (step 51: 0.5477
vs 0.5475).
- **Gradient checkpointing** on vs off: 3.33 vs 10.7 GB peak, losses
agree to 2.1e-4.
- **Z-Image with grad accumulation 2:** 50 steps, 0 skipped.

## bf16 cards are unchanged

- CPU routing tests cover sm80/86/89/90/100/120 for the three families.
Each keeps `bfloat16`, no fp16 AMP and `mixed_precision == "bf16"`.
- A test fails if the GradScaler is touched on bf16.
- On the L4, this PR's bf16 loss falls inside main's own repeat spread.

## Tests

`studio/backend/tests/test_diffusion_dit_fp16_t4.py`, 42 CPU tests. On
main, the 20 T4 tests fail on the refusal, and the 20 bf16 routing tests
pass on both.

## Not covered

- No Z-Image bf16 comparison on an L4: no L4 was free.
- The T4 runs are Colab T4, not Kaggle T4x2.
- An overflow skip never happened on real hardware; skip, freeze and
scale halving are covered by CPU tests only.
- Z-Image is slow on a T4 (7.8 s/step), because about 30% of its linear
FLOPs run in fp32.
- Still refused on T4: FLUX.1-dev, Qwen-Image, Krea 2, FLUX.2-dev,
FLUX.3, LTX-2, MiniMax-H3.
- Not run: compile on this path, ROCm / XPU, and a UI check.


## Update: merged with main's fast LoRA and budgeted checkpointing

Main now has the cast-once LoRA path with the nf4 dequant cache (#18345)
and budgeted gradient checkpointing (#18301). On the fp16 path:
- **Fast LoRA stays on.** `install_fast_lora` now skips the fp32 island
modules. Before, it replaced their forward and ran them under fp16
autocast, which would re-expose the Z-Image layers that overflow. Layers
inside an island fall back to PEFT in fp32. On bf16 there are no
islands, so this is inert.
- **The nf4 dequant cache is off on fp16.** On the T4, it and the
checkpointing budget both size themselves from step 1's free memory. The
cache took 7.44 GiB while the budget kept all 25 blocks, so step 2 ran
out of memory and fell back to checkpointing every block (2.98 s/step).
- **Budgeted checkpointing stays on.** It is planned on the first
optimizer step that actually applies, since a skipped step allocates no
optimizer state.
- The fp16 loss scaling moved into the shared forward / backward helper,
so main's out-of-memory rerun is scaled too.
- The resume-loop source test accepts the `while` loop that advances
only on an applied step. A self-test checks it still rejects a loop that
starts at 0 or advances by anything else.

Colab T4, FLUX.2-klein-base-4B, fp16 nf4, 50 steps, 512 px, rank 16:

| | loss mean, steps 1-50 | s/step | peak | skipped / NaN |
|---|---|---|---|---|
| this PR before the merge | 0.2848 | 2.79 | 3.33 GB | 0 / 0 |
| merged, as committed | 0.2847 | 2.00 | 10.7 GB | 0 / 0 |

- Per-step loss matches the earlier run: median difference 5.5e-5.
- The higher peak is the checkpointing budget keeping all 25 blocks'
activations, which is where the speedup comes from.
- 60 fast-LoRA layers engaged with 0 fallbacks, and all 6 fp32 islands
measured fp32.

CPU: the fp16, fast-LoRA, checkpointing-budget, resume and DiT trainer
suites give 468 passed (main 422) with no new failing test IDs. Not run
on GPU after the merge: Z-Image, Wan, resume, a real overflow skip, and
a bf16 regression check.


## Update: AMD test fixture, compile switch and a declined-compile
warning

- **Tests on ROCm hosts:** the `card` fixture now also pins
`torch.version.hip` and `rocm_bf16.is_rocm_torch`, so the spoofed T4 is
no longer read as a bf16 AMD card. 11 of the new tests failed on a real
gfx1151 runner before this; the file now passes 46 of 46 on plain CPU
torch and under a ROCm-build spoof.
- **Compile switch:** on non-bf16 NVIDIA cards the training panel no
longer offers torch.compile for the three fp16 families, since the fp16
path always trains eager. bf16 cards (sm89 checked) keep the switch.
- **Declined compile request:** an API caller that still sends
`compile_transformer="on"` on the fp16 path now gets a `warning` event
and a log line saying the run trains eager. `auto`, `off` and unset stay
silent. The call sits under `if fp16_amp:`, so bf16 cards run the same
code as before.

GPU detection sweep, 26 device classes x 29 family keys x 5 env cases
(2080 cells): 128 move from refused to admitted, all non-bf16 NVIDIA
cards for flux.2-klein, z-image and wan2.2-ti2v-5b; 20 more are bf16
cards with the `UNSLOTH_STUDIO_DIT_FP16=force` opt-in. Every ROCm, XPU,
MPS and CPU cell is unchanged, and a real gfx1151 card (Linux, ROCm
torch) answers identically on main and this branch.

bf16 regression check, Colab L4, klein nf4, 512 px, rank 16, 30 steps,
interleaved base / head / base / head in fresh processes: loss mean
0.28249 / 0.28248 (main) vs 0.28248 / 0.28243 (this PR), 0.885-0.903 vs
0.894-0.913 s/step, the same 18.449 GB peak, 60 fast-LoRA layers and
7.219 GiB dequant cache on both.
danielhanchen added a commit that referenced this pull request Nov 19, 2026
…kpointing budget (no step-2 OOM fallback; klein 1024 on L4 11% faster, 5.4 GB lower peak) (#18416)

## 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.
danielhanchen added a commit that referenced this pull request Nov 21, 2026
…t grad to one fp32 ulp (#18739)

## Problem


`studio/backend/tests/test_diffusion_lora_fast.py::test_dense_base_with_fp32_inputs_is_bit_identical_to_peft`
failed on an unrelated PR (#18734, base `15a985f32d`) in `(Python 3.13,
diffusion)`:

```
assert torch.equal(got[0], want[0]) and torch.equal(got[1], want[1])
E   assert (True and False)
```

## Cause

The test drew its input with an unseeded `torch.randn`, so `x` depended
on whatever the earlier tests in the same xdist worker left in the
global RNG. For most inputs the fast path and PEFT agree bit for bit,
but for a small fraction one element of the **input** gradient differs
by one fp32 ulp. Reproduced locally with seed 1049 (1 of 300 seeds):

| tensor | bit-identical | max abs diff |
|---|---|---|
| forward output | yes | 0 |
| input grad | no, 1 element | 3.6e-12 (relative 3.8e-9) |
| all six LoRA grads | yes | 0 |

The block feeds one layer norm into both `q` and `k`, so its input
gradient is a sum of the two branches, and autograd's accumulation order
can change the last bit of a rare element. That is not a gradient error.
`diffusion_lora_fast.py` (#18345) is correct; the test's exact-equality
claim on the input grad is stricter than the arithmetic allows.

## Fix

Test-only change:

- The input comes from a dedicated generator, parametrized over seed 0
and seed 1049 (the failing case), so the test no longer depends on test
order.
- The forward output and every LoRA gradient still require
`torch.equal`.
- The input gradient is checked with `torch.testing.assert_close(rtol =
1e-6, atol = 1e-9)`, which admits ulp-level accumulation-order noise and
nothing a real bug would produce.

## Verification

- `studio/backend/tests/test_diffusion_lora_fast.py`: 23 passed.
- The previous exact check fails on seed 1049, as on CI.
- Sabotage: scaling the fast path's LoRA input gradient by 1.01 in
`_LoraProduct.backward` fails both parametrizations (8176 of 8192
elements mismatched). Restored afterwards.
danielhanchen added a commit that referenced this pull request Nov 22, 2026
… cache on ROCm too (#18825)

Diffusion LoRA training kept two speedups CUDA only: the budgeted
gradient checkpointing (#18301, keeps block activations when the card
has room) and the nf4 / int8 dequant cache (#18345). Both refused ROCm
outright, so an AMD card checkpointed every block and dequantised every
nf4 weight on every call. Neither refusal came from a measured ROCm
problem: both PRs say ROCm was simply not run.

## Change

- `diffusion_gc_budget.enable_budgeted_checkpointing` no longer returns
None on ROCm.
- `diffusion_dit_trainer._dequant_cache_wanted` no longer excludes ROCm.
The fp16 path still declines the cache, as before.
- The budgets plan from free memory. They now read it through
`utils.hardware.trusted_mem_get_info`, which caps the over-reported free
memory on Windows ROCm (WDDM reports nearly the whole card free whatever
is resident). Everywhere else it passes the driver's numbers through
unchanged.

Kill switches are unchanged: `UNSLOTH_DIFFUSION_GC_MODE=plain` and
`UNSLOTH_DIFFUSION_DEQUANT_CACHE=0`.

## Measured on gfx1151 (Radeon 8060S)

FLUX.3 klein base LoRA, 512x512, 8 images, rank 16, 20 steps. Main and
this change ran in the same job, plus a second main-vs-main pass for the
noise floor.

| OS | precision | main samples/s (two main runs) | this change |
speedup | max loss difference vs main | main vs main loss difference |
peak GB main -> this |
|---|---|---|---|---|---|---|---|
| Linux, torch 2.11.0+rocm7.13.0 | bf16 | 0.568 / 0.566 | 0.796 | 1.40x
| 0 (bit-identical) | 0 | 12.05 -> 15.61 |
| Linux | nf4 | 0.354 / 0.352 | 0.596 | 1.69x | 0 (bit-identical) | 0 |
5.60 -> 20.85 |
| Windows, torch 2.11.0+rocm7.14.0 (this head) | bf16 | 0.445 / 0.469 |
0.627 | 1.34-1.41x | 8.0e-4 | 0 | 12.19 -> 17.52 |
| Windows (this head) | nf4 | 0.353 / 0.352 | 0.534 | 1.51x | 2.5e-3 | 0
| 5.60 -> 20.85 |

On Linux, host RAM available during training stayed between 99.9 and
109.7 GiB in every arm. On Windows, main repeats itself bit for bit, so
the small loss difference there comes from this change. The first two
steps are identical and the loss curve (0.73 -> 0.85 over the run) is
unchanged at three decimals. Windows runs the trainer eagerly, since the
boxes have no C++ compiler for torch.compile, and Linux runs it
compiled. The nf4 peak rises by design: the cache holds 200 of 231
dequantised layers (7.5 GiB) and is planned from free memory.

## Tests

- `test_diffusion_gc_budget.py::test_rocm_uses_the_budget_too`: ROCm now
gets the budget, and `UNSLOTH_DIFFUSION_GC_MODE=plain` still turns it
off.
- `test_diffusion_gc_budget.py::test_budget_reads_trusted_free`: the
budget reads the trusted free memory.
-
`test_diffusion_dit_fp16_t4.py::test_dequant_cache_stays_off_on_the_fp16_path`:
ROCm keeps the cache, and the fp16 path still declines it.
- Against main: 2 tests fixed, 1 new-API test, 101 unchanged. Two
`test_diffusion_gc_budget_trainers.py` tests (SDXL, H3-Image) fail
identically on main and here: a diffusers / huggingface_hub version
mismatch in the test environment.

## Not proven here

- Windows ran eager, since the boxes have no C++ compiler for
torch.compile. The compiled ROCm path was measured on Linux only.
- No discrete Radeon card, no multi-GPU setup, and no families other
than FLUX.3 klein were run.
- The Windows free-memory cap in the spawned trainer is in the measured
head. The peaks match the earlier run without it, so on this 82 GB
unified-memory card the cap did not change the plan.
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