Repository navigation
Studio diffusion training: keep block activations when the card has room (20-42% faster per step, bit-identical in deterministic mode) - #18301
Conversation
DiT LoRA training checkpointed every transformer block, so each block ran its forward twice per step. After the text encoders stream, a 4-bit run peaks at 3 to 6 GiB and most of a 22 to 80 GB card sits idle while the step pays for the recompute. Step 1 now runs fully checkpointed except the first block of each block class, whose kept activations are measured. After step 1 the free memory left on the card (minus max(2 GiB, 10%) and a 15% safety share) decides how many blocks keep their activations; the rest stay checkpointed. Skipping a recompute runs the same kernels on the same inputs, so losses and LoRA weights are unchanged (bit-identical in deterministic mode). An out-of-memory error in a step that keeps activations turns the plan off and reruns that step fully checkpointed from the same inputs, so the run continues exactly as a fully checkpointed run would. UNSLOTH_DIFFUSION_GC_MODE=plain (or partial) restores the old behaviour. The plan is CUDA only; ROCm, XPU and CPU keep the old path.
|
@codex review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d40d287c5d
ℹ️ 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".
| loss = (per * w).mean() | ||
| (loss / cfg.gradient_accumulation_steps).backward() | ||
| step_acc = accumulate_loss(step_acc, loss, cfg.gradient_accumulation_steps) | ||
| micro_inputs.append((latents, noise, timesteps, sigmas, noisy, embeds)) |
There was a problem hiding this comment.
Avoid retaining every micro-batch's inputs on the GPU
With gradient accumulation above one, this list retains the latents, noise, noisy latents and collated embeddings for every micro-batch until the optimizer step finishes, whereas previously completed micro-batches' inputs could be released. GPU input memory now grows with gradient_accumulation_steps, which can make previously fitting high-resolution runs run out of memory. This also affects plain mode, disabled gradient checkpointing, and runs after fallback, even though none can use the saved inputs for a retry. Only retain replay inputs while budgeted checkpointing can retry, and keep those replay copies off-device so accumulation retains its memory-saving behavior.
Useful? React with 👍 / 👎.
| for inputs in micro_inputs: | ||
| acc = accumulate_loss(acc, _forward_backward(*inputs), cfg.gradient_accumulation_steps) |
There was a problem hiding this comment.
Restore RNG states when replaying failed micro-steps
When cfg.lora_dropout > 0 and a step hits OOM, replaying the saved tensors does not reproduce the original micro-steps: successful forwards and the failed forward have already advanced the CUDA RNG, so the replay uses different dropout masks and changes both the gradients and subsequent noise/timestep draws. This contradicts the fallback's same-step recovery guarantee even with deterministic algorithms enabled. Save the RNG state immediately before each micro-step's forward, restore the corresponding state for its replay, and leave the RNG at the state a single successful execution would have produced.
Useful? React with 👍 / 👎.
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
…and replay its RNG The budgeted checkpointing kept every micro-batch's inputs on the GPU until the optimizer step, so with gradient accumulation the device held all of them, also in plain mode, with checkpointing off and after a fall back, where no rerun can use them. The replay copies now live on the host (pinned on CUDA) and are only taken while a fully checkpointed rerun could still help: during step 1's measurement or while blocks keep their activations. A rerun also used fresh dropout masks: the successful forwards and the failed one had advanced the RNG. The CPU and CUDA RNG states are now saved right before each micro-batch's forward and restored for its replay, which leaves the RNG where a single successful pass would have, so the adapter and every later noise and timestep draw match a run that never ran out of memory. CPU tests on the real training loop (tiny Qwen-Image-2.1 pipe): accumulation holds one micro-batch at a time in plain mode, with the budget on and after a fall back, and an injected out-of-memory error with lora_dropout 0.1 under deterministic algorithms gives bit-identical losses, LoRA weights and timestep draws to a clean run. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e8f786ba1a
ℹ️ 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".
| if oom: | ||
| # Handled outside the except block, so the failed step's tensors are already released. | ||
| step_acc = _retry_fully_checkpointed() |
There was a problem hiding this comment.
Release the failed micro-batch's device inputs before replay
When an OOM occurs on a card close to its fully checkpointed memory limit, the retry still retains the original GPU tensors through inputs and the loop's latents, noise, timesteps, sigmas, noisy, and embeds locals. StepReplay.replay() then creates another device copy of the recorded inputs, so the supposedly lower-memory fallback needs two micro-batches' inputs simultaneously and can OOM even where ordinary fully checkpointed training fits. Leaving the exception handler releases the failed forward's traceback, but not these caller-owned tensors. Clear all references to the original device inputs before starting the host-backed replay.
Useful? React with 👍 / 👎.
|
Codex Review: Didn't find any major issues. Swish! 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". |
…out-of-memory replay The replay ran while the loop still held the failed micro-batch's device tensors (inputs, latents, noise, timesteps, sigmas, noisy latents, embeddings) and the earlier micro-batches' losses, so on a card near its fully checkpointed limit the rerun could run out of memory where a clean fully checkpointed step fits. Those references are now dropped before the cache is emptied and the step replays from its host copies. CPU test on the real training loop: when the first replayed forward starts, no tensor of the failed micro-batch and no part of its forward's output is alive. [skip ci]
|
Codex Review: Didn't find any major issues. More of your lovely PRs 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". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
…(eager DiT LoRA 16-26% faster per step) (#18345) ## 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 #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 #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.
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.
…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.
…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.
…e Gemma 4 worker, dev DiT, baked into the distilled Video page model) (#18386) ## Summary Studio runs LTX-2.5 on the Video page, but its diffusion trainer refused it. The family was never marked trainable, `get_trainer` and `_DIT_TRAIN_FAMILIES` only knew `ltx-2`, and a local LTX-2.5 folder was explicitly refused. This PR adds LTX-2.5 LoRA training using the same still-image style flow as LTX-2. A trained LoRA loads back on the Video page. ## Design - **Caption encoding.** The Gemma 4 12B encoder needs transformers >= 5.10.1, while Studio pins 5.5.4, so the Video page already runs it in a separate worker with its own transformers. The trainer process has already imported 5.5.4, so the encoder cannot load in-process. - Captions are encoded once, before the DiT loads, through that same worker, at the Video page's default encoder precision. - The worker is then stopped, which frees its GPU and host memory. - Studio's conditioning cache is reused; on a warm cache the worker never starts. - **Downloads.** Conditioning fetches only the small components and one copy of the connectors. It skips both DiTs, the dense encoder (the worker reads it) and the prompt enhancer. - **Which DiT.** The LoRA trains on the dev DiT (`transformer_full/`), since the model card says "The dev transformer is fully trainable". The Video page bakes it into the distilled DiT it renders with, as Studio already does for Krea and FLUX.2 Klein. The dev scheduler gives exactly LTX-2's sigma table. - When the fetch comes from the `unsloth/LTX-2.5-FP8` mirror, which has no dev DiT, the dev DiT is read from `Lightricks/LTX-2.5-Diffusers` if the token can access it. Otherwise training falls back to the distilled DiT with a warning. - `UNSLOTH_LTX25_TRAIN_DIT=distilled` trains the distilled DiT on purpose. - **Base precision.** The default is the same nf4 4-bit path `ltx-2` uses. The hosted INT8-ConvRot / FP8 files are distilled-only and are not training bases; GGUF was already refused. - **Routing.** - A local LTX folder is routed by its `model_index.json`. - Training a local 2.5 folder as `ltx-2`, or a 2.0 folder as `ltx-2.5`, is still refused. - The single-file `Lightricks/LTX-2.5` release is refused with a pointer to the Diffusers pack. ## Results LTX-2.5, A100-80 on Colab: nf4 base, 512 px, rank 32, lr 2e-4, 300 steps, seed 0, 16 style stills. | steps | 1-50 | 51-100 | 101-150 | 151-200 | 201-250 | 251-300 | |---|---|---|---|---|---|---| | mean loss | 1.389 | 1.248 | 1.101 | 0.999 | 0.996 | 1.066 | - **GPU memory:** the trainer process peaks at 10.9 GiB and the training loop at 11.7 GB. The encoder worker used 12.4 GiB on the card and was stopped before the DiT loaded; the whole-card peak was 22.9 GB. - **Host RAM:** 20.5 GB process-tree peak. - **Speed:** 1.07 samples/s. Video page renders through Studio's `VideoBackend`, distilled two-stage defaults, 768x512, 25 frames, seed 7: | prompt | LoRA strength | LPIPS vs no LoRA | |---|---|---| | cat on a sofa | 0 (second load) | 0, bit-identical | | cat on a sofa | 0.5 / 1.0 | 0.608 / 0.741 | | mountain sunset | 0 (second load) | 0, bit-identical | | mountain sunset | 0.5 / 1.0 | 0.449 / 0.772 | The effect grows with strength, and the backend status shows the LoRA baked at the requested weight. **LTX-2 regression,** same VM, interleaved base / head / base / head / base, 40 steps: - mean loss: base 1.3501 / 1.3541 / 1.3470; head 1.3514 / 1.3490; - the two head runs fall inside the base-vs-base per-step spread; - VRAM peaks are the same. ## Tests - `studio/backend/tests/test_diffusion_dit_trainer_ltx25.py` has 25 tests. They fail at import on main and pass here. - They include a tiny CPU end-to-end run: train on the dev DiT with the real encoder worker process, then publish and bake the LoRA into the distilled DiT through the real `VideoBackend`. The output difference grows with strength. - Two existing tests changed on purpose: the old "training refuses LTX-2.5" contract became a routing test. - The related diffusion and video suites (58 files) pass: 3070 passed, 0 failed. ## Not covered - No run on an RTX PRO 6000 (G4); Colab gave A100-80 every time. - No video-clip training, only the still-image style flow, as for LTX-2. - The mirror-only fallback to the distilled DiT is covered by unit tests only. - The training child spawned by the Studio server and the UI flow were not run end to end; the trainer and `VideoBackend` were driven directly. - Only nf4 ran on GPU; the int8 / fp8 / bf16 training bases have unit tests. - Merges cleanly with #18301, and the combined tree passes both test sets.
…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.
… 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.
Summary
Diffusion LoRA training now keeps block activations instead of recomputing them when the card has room. Since #18123 streams the text encoders, memory is no longer the limit on L4 or A100. The main cost left is the second forward that gradient checkpointing runs for every block.
Time per step, compiled training (Studio's default for 500-step runs). Each cell is 3 interleaved fresh processes per arm on the same Colab VM:
Eager training (runs under 200 steps) on L4:
Deterministic mode (math attention, deterministic algorithms): losses, LoRA weights and the end-of-run sample are bit-identical to main for every family on both cards.
How it works
New
core/training/diffusion_gc_budget.py, wired intodiffusion_dit_trainer.py:Scope:
plainandpartialmodes. The SDXL and MiniMax-H3 trainers are not touched.Kill switch:
UNSLOTH_DIFFUSION_GC_MODE=plainrestores the old behaviour. With it set, every L4 family ran at main's speed and peak.Memory
This trades free VRAM for speed, so the training peak goes up on cards with room. Allocated training peak, GiB:
peak_memory_gbStudio shows rises to match. On L4, the whole Qwen-Image-2.1 and FLUX.3 runs, including the preview render, reached 21.7 of 22 GB.Accuracy in normal mode
bf16 attention backward is nondeterministic, so main differs from itself from run to run. Against that:
The deterministic bit-identity above is the stronger evidence.
Testing
tests/test_diffusion_gc_budget.py, 19 CPU tests. They include LoRA gradients matching an uncheckpointed run in every state on a tiny Z-Image.test_diffusion*andtest_decision_training*show the same failing test IDs on main and on this branch. They are environment failures in inference modules.Not covered