Skip to content

Studio diffusion training: checkpointing budget for SDXL and MiniMax-H3, step down after OOM, cached fp8 backward weights - #18518

Merged
danielhanchen merged 5 commits into
mainfrom
studio-train-gc-budget-sdxl-h3
Nov 20, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-train-gc-budget-sdxl-h3

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 Studio diffusion training: keep block activations when the card has room (20-42% faster per step, bit-identical in deterministic mode) #18301 / Studio diffusion training: plan the nf4 dequant cache around the checkpointing budget (no step-2 OOM fallback; klein 1024 on L4 11% faster, 5.4 GB lower peak) #18416.
  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

…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.
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T21:37:35.356796Z 65008d4 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +4191 to +4193
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 65008d425e

ℹ️ 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 0d70d82 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the studio-train-gc-budget-sdxl-h3 branch November 20, 2026 03:31
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.

2 participants