Repository navigation
Studio diffusion training: checkpointing budget for SDXL and MiniMax-H3, step down after OOM, cached fp8 backward weights - #18518
Conversation
…H3 trainers, step down after OOM, cached fp8 backward weights - The SDXL, MiniMax-H3 video and MiniMax-H3-Image trainers now use the same checkpointing budget as the DiT trainer: after step 1, blocks whose activations fit in free memory skip the backward recompute (same kernels, same inputs, bit-identical loss and gradients). The plain path stays the fallback (ROCm, non-CUDA, UNSLOTH_DIFFUSION_GC_MODE=plain|partial). The loop side (record the micro-batch, rerun after an out-of-memory error, plan after the first update) lives in diffusion_gc_budget so the trainers share it. - An out-of-memory error with blocks kept now halves the kept bytes and reruns the step from its host copies, instead of checkpointing every block for the rest of the run; only an error with nothing left to drop (or while still measuring) checkpoints everything. The plan also keeps cheaper blocks after one that does not fit. - fp8 training: the column-major weight grad_x needs is kept in the room the checkpointing plan leaves unused, instead of being copied from the row-major weight on every backward. The lookup runs inside an opaque custom op, so the compiled graph is the same with or without the cache (no recompile when it fills, clears or is lent back to Studio). UNSLOTH_DIFFUSION_FP8_BWD_CACHE=0 turns it off.
…weights, keep the inline copy outside budgeted runs The cache lookup sits in an opaque op, so an uncached layer no longer got inductor's tiled transpose but aten's strided copy, which is several times slower for 1-byte elements: with no room for the cache an fp8 step was 22% slower on L4. The uncached copy now uses a tiled Triton transpose (aten when Triton is missing), and the op path is only traced in when a budgeted trainer run turns it on; everything else, and UNSLOTH_DIFFUSION_FP8_BWD_CACHE=0, keeps the inline copy exactly as before.
…ch.library.custom_op is unavailable
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. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b8552e2f26
ℹ️ 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 fp8_backward is not None: | ||
| # What kept activations leave of the plan's room holds column-major fp8 weights for grad_x. | ||
| fp8_backward.plan(gc_budget.spare_bytes) |
There was a problem hiding this comment.
Release cached fp8 backward weights during preview rounds
For fp8 runs with previews enabled, the new cache retains its GPU weight copies during _sample(), even though sampling never uses backward weights. _sample() already suspends the dequant cache before moving the preview VAE onto the GPU, but has no equivalent handling for fp8_backward. When the preview's VAE and inference allocations need the memory now occupied by these copies, a preview that previously fit will OOM, and the exception handler permanently disables sample images for the remaining run. Temporarily clear the backward cache while preserving its budget around preview rounds, then allow subsequent training backwards to refill it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5e001f5 (test c5c552c618): before each preview the fp8 backward copies are dropped with their budget kept, and the next training backward refills them; a lent-memory return is also capped by what is free now.
| if freed and torch.cuda.is_available(): | ||
| torch.cuda.empty_cache() | ||
| elif kind == "return": | ||
| cache.plan(lent["budget"]) |
There was a problem hiding this comment.
Could the return handler size the FP8 cache against the GPU space that is free after the load? Studio's dictation loader exits lend_vram when the new engine has started, while its weights remain resident. Restoring the old budget here lets the next backward fill memory the engine now occupies. If the checkpoint plan already keeps zero blocks, gc_budget.can_retry is false and the allocation error ends training.
I tested the worker's lend/return messages and the actual CUDA weight-copy cache on an RTX 3090 (PyTorch 2.11.0+cu130), with a 184 MiB process allocator limit. The cache lent 64 MiB, then I kept an 80 MiB allocation resident to represent the newly loaded model. On return the budget was 64 MiB again. Of four 16 MiB weight copies, the third failed after the cache retained the first two. The merge-base transpose completed all four. Subtracting the drop in free memory across the loan also completed all four, and restored the full 64 MiB when the borrower retained nothing. This exercises cache allocation and transposition only. Native FP8 GEMM requires a newer GPU.
…s and for a lent load A preview render now drops the cached column-major fp8 weights first, as the nf4 dequant cache already does, so a preview that fit before the cache still fits. Returning lent VRAM caps the restored budget at what the plan has left: nothing after a step-down, and less by whatever the lent load took since the plan.
…kward copies held Runs the real DiT loop (tiny Qwen-Image-2.1, CPU) as an fp8 budgeted run with a preview every step and checks each preview after the plan sees an empty cache with its budget kept. [skip ci]
|
@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". |
Summary
Three changes to diffusion LoRA training, all exact (same kernels on the same inputs, so losses and gradients do not change):
What changes
diffusion_gc_budget.BudgetedStepsis 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.UNSLOTH_DIFFUSION_GC_MODE=plain|partial, and diffusers models withoutgradient_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.diffusion_frozen_fp8): the grad_x GEMM runs through an opaque custom op that looks upFp8BackwardWeights. Because the op is opaque, the compiled graph is the same whether the cache fills, clears or is lent back to Studio throughlend_vram. There is no recompile and no graph break.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):
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:
fp8 backward weights. FLUX.3 klein base, fp8 compiled, L4, 512 px, base A/A 0.4535 / 0.4583 / 0.4547:
UNSLOTH_DIFFUSION_FP8_BWD_CACHE=0The 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.pyandtests/test_diffusion_frozen_fp8_bwd_cache.py; updatedtest_diffusion_gc_budget.pyandtest_diffusion_gc_budget_replay.py. The new and updated tests fail on the merge base (20 failed, 7 errors) and pass here. They cover: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.torch.equalto full checkpointing. An out-of-memory error injected in step 2 steps down once and still gives the identical adapter.torch.equalwith the cache on or off. The cache keeps to its budget.lend_vramfrees the copies and they come back after the return. An inactive cache never touches the backward, and the kill switch works.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.pyalso fail on the merge base.Not covered