Repository navigation
Studio diffusion training: DiT block swap, used by auto where int8 was the only fit - #18604
Conversation
…do not fit block_swap = off | auto | N keeps N repeated blocks' frozen bf16 weights in pinned host RAM and streams them per step through unsloth_zoo's BlockSwap (host copy authoritative, side-stream prefetch, reverse prefetch in the recompute). The base loads on the host, every block is checkpointed (no checkpointing budget), and the regional compile compiles each block's forward so the swap hooks stay outside the graph. Default off; refused for nf4 / int8 / fp8 / mxfp8, without gradient checkpointing, off CUDA and on integrated GPUs.
…ck swap When base_precision=auto lands in the int8 band (the dense base fits with little headroom), train bf16 with block_swap=auto instead on a discrete NVIDIA card. On an L4 this was 1.41x to 1.48x faster than int8 at bf16 loss (FLUX.2-klein 9B: 1.585 vs 2.35 s/step at 512 px with nothing swapped, 5.35 vs 7.55 s/step at 1024 px with 14 of 32 blocks swapped). The swap installs before checkpointing is set up, so a plan that swaps nothing keeps the checkpointing budget and the regional compile. If the swap cannot be installed (host RAM) auto falls back to int8 from the same host copy. UNSLOTH_DIT_AUTO_BLOCK_SWAP=0 keeps int8; ROCm, integrated GPUs and runs without gradient checkpointing keep int8.
|
@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: d8adb0f90b
ℹ️ 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".
| gc_budget = None if swapping else enable_budgeted_checkpointing(transformer, device) | ||
| if gc_budget is None: | ||
| enable_diffusion_gradient_checkpointing(transformer) |
There was a problem hiding this comment.
Force full checkpointing when blocks are swapped
When UNSLOTH_DIFFUSION_GC_MODE=partial is set, disabling the checkpointing budget does not ensure that every block is checkpointed: the subsequent enable_diffusion_gradient_checkpointing(transformer) call still reads that environment variable and checkpoints only every Nth block. Swapped blocks that run without checkpointing must retain their weights until backward, causing BlockSwap to grow its slot pool beyond the memory plan and potentially OOM on the memory-constrained runs this feature targets. Pass mode="plain" when swapping is true while preserving the configured mode for unswapped runs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e69e3ac: when blocks are swapped the fallback call is now enable_diffusion_gradient_checkpointing(transformer, mode="plain"), so UNSLOTH_DIFFUSION_GC_MODE=partial cannot leave a swapped block unchecked; unswapped runs keep the configured mode. New test test_swapping_checkpoints_every_block_even_with_partial_mode sets partial mode and checks the swapped path checkpoints every block (every_n_blocks=1) while the unswapped path keeps partial.
…ever the gc mode [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
…18640) #18604 added a block swap for DiT LoRA training (`cfg.block_swap` / `UNSLOTH_DIT_BLOCK_SWAP` = off, auto or a block count). It could only be turned on through the trainer config dict or the env var. The training API dropped the field, because `DiffusionTrainingStartRequest` did not declare it, and the Train tab had no control for it. This PR lets you pick it from both. ## Change Backend: - `DiffusionTrainingStartRequest.block_swap`: optional, `"off"`, `"auto"` or an integer 0..1024. The default is unset, which sends nothing to the trainer, so behaviour is the same as today, and `UNSLOTH_DIT_BLOCK_SWAP` still applies. A count is passed on in the trainer's string form. - `/api/train/diffusion/start` now calls `block_swap_start_error`, which runs before any GPU residents are freed. It refuses a block swap the trainer would only refuse after loading the base, plus families whose trainer has no swap path: - families outside the DiT trainer (SDXL, MiniMax-H3) - `base_precision` other than `bf16` - `gradient_checkpointing` off - the pre-Ampere fp16 fallback - no CUDA device - an integrated GPU `off` and `0` are accepted for every family. Only the request field is checked here, not the env var. - `family_train_infos` reports `supports_block_swap`, which is true for DiT families that list `bf16` and are not on the fp16 fallback. - The DiT trainer emits a `block_swap` event right after the swap is installed. The fields are `swapped_blocks`, `total_blocks`, `host_gib` and `pinned_gib`. The training service folds it into a new `block_swap` field on `/api/train/diffusion/status`. Before this, the only trace was a warning message that the first progress event overwrote. Frontend (Images > Train): - A Block swap select (Off / Auto / Fixed number of blocks, plus Blocks to swap). It shows only when all of these hold: - the family reports `supports_block_swap` - Base precision is bf16 - gradient checkpointing is on - the host passes the same hardware rule as core LLM layer offload (`offloadHardwareSupported`, reused from `features/training/api/mappers.ts`) - When hidden or set to Off, nothing is sent. - While a run is going, the run card shows the resolved outcome under the stats, e.g. "Block swap: 21 of 57 blocks from host RAM (8.1 GiB pinned)". ## Tests - `studio/backend/tests/test_diffusion_block_swap_api.py` (18, CPU) covers: - request parsing - forwarding of `auto` and a count through the real route to the service, and that the forwarded value parses back in the trainer - unset stays unset - every refusal returns 400 without freeing the GPU - `off` is accepted for SDXL - the env var is not judged at the route - the family flag - the status fold - the trainer emitting the event `test_differential.py` against b57c06f: DISCRIMINATING, 3 FIXED + 15 NEW_API, head_fail 0. - Existing suites (`test_diffusion_training.py`, `test_diffusion_block_swap.py`, `test_diffusion_base_precision.py`, `test_diffusion_dit_trainer.py`, checkpoint resume, samples, LTX-2): all pass. - `studio/frontend/tests/diffusion-train-block-swap.test.ts` covers when the control shows, the payload, the status line and the panel wiring. The full `npm test` passes (16915 tests, 0 failures), and so does `npm run build`. ## GPU check (Colab L4, 22.5 GiB, standing in for a 24 GB card) Wan2.2-TI2V-5B, bf16 base, 512 px, rank 16, 50 steps, seed 0. Each arm ran in a fresh process, interleaved off / N / auto / N / off, plus one more repeat of each. The request went through `DiffusionTrainingStartRequest` and the route preflight, using the host's real GPU facts. The status came from the service's event fold. | arm (request `block_swap`) | runs | steady s/step, median [range of run medians] | peak alloc GiB | loop host RSS GiB | status `block_swap` | mean abs dloss vs off_1 | |---|---|---|---|---|---|---| | unset / `off` | 3 | 0.170 [0.169-0.172] | 11.39 | 5.5-5.6 | none | A/A 0.00031-0.00032 | | `auto` | 2 | 0.170 [0.168-0.172] | 11.39 | 5.6 | 0 of 30 blocks | 0.00015-0.00024 | | `10` | 3 | 0.519 [0.519-0.519] | 7.89 | 4.9 | 10 of 30, 3.05 GiB pinned | 0.00023-0.00034 | Notes on the results: - At this size Wan 5B fits on the L4. So `auto` swaps nothing and runs at the same speed as off, and the status says so. - A forced N=10 frees 3.5 GiB of peak allocation and costs about 3x per step. At 512 px the step is copy-bound: about 12 GB/s over PCIe against roughly 0.17 s of compute. - The losses match off within the off-vs-off spread. - Graph breaks were 0 in every arm, with 2 unique graphs. Resume with the same `block_swap=10`: one process stopped and saved at step 25 (checkpoint-25). A new process resumed from that output dir to 50. The resumed run reported `resumed` at step 25, picked up the same swap (10 of 30 blocks), and trained steps 26 to 50. Its loss over steps 26 to 50 differs from the three uninterrupted `10` runs by a mean absolute 0.00028-0.00046 per step. The uninterrupted runs differ from each other by 0.00041-0.00055 on the same steps, so the resumed curve is inside run-to-run noise. Mean loss over steps 26 to 50: 0.2375 for the resumed run, 0.2375 for the uninterrupted one. Wan renders no previews (video families refuse `sample_every`), so the preview leg used FLUX.2-klein-base-4B with bf16 and `block_swap=8`. Status showed 8 of 25 blocks with 2.29 GiB pinned, at 0.83 s/step with a 6.6 GiB peak. The samples rendered at steps 0, 10 and 20 while the swap was on. ## Not proven here - Only an L4 was tested: no 3090/4090/5090 and no PCIe Gen3 host. No model that needs the swap on a 24 GB card was run end to end through the API in this PR. FLUX.1-dev and FLUX.2-klein-9B were measured in #18604 through the trainer config. - ROCm discrete GPUs: the route and the panel allow an explicit swap there, as the trainer does, but it is unmeasured. The integrated-GPU refusal is CPU-tested only. - The UI shots were taken on a CPU host, with `/api/system` and the family listing rewritten in the browser to a 24 GB CUDA card. The rewrite was the same on both sides. ## UI Train tab, FLUX.1 with a bf16 base. Before (main) and after (this branch): the **Block swap** select and, for a fixed count, **Blocks to swap**.  The running job's status line after the base loads (the job is faked with the FLUX.1-dev numbers from #18604: 21 of 57 blocks, 8.1 GiB pinned). 
…18684) #18604 added DiT block swap and switched the gradient checkpointing budget off whenever a run swaps blocks (`gc_budget = None if swapping`), so every block was checkpointed. On an L4 with Z-Image at 512 px and 10 of 34 blocks swapped, that run trained at 1.19 s/step with a 10.5 GiB loop peak, leaving about 12 GiB of the card unused. The same model without swap trains at 0.79 s/step with the budget. ## Change The budget now runs alongside block swap: - `install_dit_block_swap` marks each swapped block. `BudgetedCheckpoint` always checkpoints a marked block and never measures or plans it, because kept activations would hold its streamed weights on the card until backward. Only resident blocks are planned, into the room the swap leaves after step 1. - Swapped blocks go through a plain non-reentrant checkpoint without the saved-attention policy. Their swap hooks copy the next block's weights inside the checkpointed region, and in the other direction during the recompute. The selective checkpoint rejected that in backward (`aten.copy_.default encountered during backward but not found in storage`). Resident blocks keep saved attention. - On an out-of-memory rerun, `reset_block_swaps` returns every slot to the pool before the step replays. - The swap pool's auto prefetch growth gets no reservation. The pool only grows into the room left by the previous step's peak, and that peak already includes the kept activations. - With `UNSLOTH_DIFFUSION_GC_MODE=plain` or `partial`, or on ROCm, nothing changes: `_checkpoint_mode(swapping)` still forces plain checkpointing for a swapped run. ## Results Colab L4 (22.5 GiB), torch 2.14.1, Z-Image bf16 at 512 px, LoRA r16, 50 steps, `block_swap=10`, compile auto. Base is origin/main. Each arm ran in a fresh process, arms interleaved, 6 runs per side over two passes on the same VM. | arm | steady s/step median [range] | loop peak alloc GiB | mean loss over 50 steps [range] | |---|---|---|---| | main (every block checkpointed) | 1.186 [1.168-1.196] | 10.49 | 0.40719-0.40723 | | this PR (24 of 24 resident blocks kept) | **0.921** [0.917-0.930] | 14.02 | 0.40722-0.40739 | | no swap, budget (reference) | 0.788 [0.783-0.793] | 17.29 | 0.40723-0.40735 | - **Speed:** 1.29x faster per step with the same 10 blocks streamed. The two ranges do not overlap. - **Loss:** the largest per-step loss gap between main and this PR has a median of 0.0014, inside the spread between this PR's own repeats (median 0.0016). Mean losses agree to 2e-4. - **Compile:** 0 graph breaks, 5 unique graphs and 0 recompiles on both sides. - **Out-of-memory retry:** a test allocation after the plan left room for only a third of the kept activations. Step 2 ran out of memory and stepped down five times, from 24 kept blocks to 12, 6, 3, 2 and 1, replaying the step each time. All 50 steps finished (2 of 2 runs), with mean loss 0.40725 and 0.40723, the same as main. Steady speed was then 1.19 s/step, the same as main. - **FLUX.2-klein 9B, 1024 px, `block_swap=auto`, L4 (14 of 32 blocks swapped):** tested on an earlier revision of this branch that held back room for pool growth. That revision planned 0 of 18 resident blocks and ran at 5.44 s/step against 5.53 on main, 4 runs each, losses inside the A/A spread. This is the reason the reservation was dropped. - **No-swap path on A100 40 GB:** FLUX.2-klein 9B auto swaps 0 blocks there. Main and this PR are identical, at 0.959-0.961 s/step, 21 of 32 blocks kept and a 31.9 GiB peak. ## Tests New file `tests/test_diffusion_block_swap_budget.py`, CPU only: - `test_trainer_keeps_the_budget_with_block_swap`: the trainer enables the budget for swapped runs, and the out-of-memory rerun resets the swap pools before replaying. Fails on main, passes here. - `test_swapped_blocks_are_never_measured_or_kept`: swapped blocks always go through the plain checkpoint, are never measured, and are never kept after the plan. Resident blocks are planned. Fails on main, passes here. - `test_swapped_blocks_use_a_checkpoint_without_the_selective_policy`: the swapped-block checkpoint has no saved-attention policy, and its backward runs. - `test_install_marks_only_the_swapped_blocks`: `install_dit_block_swap` marks exactly the planned blocks (BlockSwap stubbed). - `test_rerun_resets_the_swap_pools`: `reset_block_swaps` resets every installed swapper. `tests/test_diffusion_block_swap*.py`, `tests/test_diffusion_gc_budget*.py`, `tests/test_diffusion_gc_saved_attention.py` and `tests/test_diffusion_train_speed.py` all pass. Differential test against main: 1 fixed, 4 new, 117 unchanged, 0 failing on this branch. ## Not proven here - The final revision has no L4 run with a model that needs `block_swap=auto`. On FLUX.2-klein 9B at 1024 px it should now plan some resident blocks into the room the pool reservation used to hold. The out-of-memory step-down still covers a plan that turns out too large. - The CPU tests cannot reproduce the selective-checkpoint `copy_` failure, because it needs the real CUDA swap hooks. It showed up on the L4 runs before the fix and is gone after it. - Only L4 and A100 were tested. No consumer 24 GB card, no Blackwell, no AMD. Block swap is CUDA-only.
…cards (#18770) Studio's DiT LoRA trainer already has a frozen fp8 base (`diffusion_frozen_fp8.py`: per-row e4m3 weights, rowwise activation scales, `torch._scaled_mm`), but `base_precision="auto"` never picked it. On an sm89+ NVIDIA card Auto chose int8 (or, since #18604, bf16 with block swap) between 1.15x and 1.5x of the dense bf16 size in free VRAM, and nf4 below that. Both are slower than fp8 there, and nf4 also trains a worse adapter. ## Change `_pick_auto_precision` / `_resolve_base_precision` in `diffusion_dit_trainer.py`, NVIDIA sm89+ only (`has_fp8` is now false on ROCm, with the Windows-ROCm torchao stub, for families whose explicit fp8 training is refused (qwen-image, moss-image), and with `UNSLOTH_DIT_AUTO_FP8=0`): - **1.15x to 1.5x:** fp8 instead of int8 / bf16 block swap. Wan2.2-TI2V-5B keeps the old pick (see below). - **0.9x to 1.15x:** fp8 instead of nf4. This works because the fp8 base now loads host-first and `convert_frozen_fp8(..., device=)` quantizes it onto the card one Linear at a time, the same way int8 already streams. The bf16 base is never whole on the device, so the peak is the fp8 base plus one bf16 Linear. Before this, explicit fp8 moved the whole bf16 base to the card and then converted it. - **Above 1.5x:** compiled bf16 as before, except Z-Image and FLUX.2 klein, which take fp8 when the run compiles (measured 1.27x to 1.45x faster). - Below sm89, and below 0.9x, nothing changes. Auto picks fp8 only when it is safe to: - **Compiled runs only.** With `compile_transformer="off"` or no Triton, eager fp8 was slower than the pick it would replace (table below), so an eager run keeps the old picks in every band. - **No block swap.** A requested block swap (`block_swap` or `UNSLOTH_DIT_BLOCK_SWAP`) streams a bf16 base only. Before this, Auto plus a swap above 1.5x was refused at load for Z-Image and klein. - **Resume.** A resume keeps the base its checkpoint recorded. Auto picks fp8 only if that bundle trained fp8. Before this, resuming an int8 / bf16 / nf4 bundle was refused after the full model load ("different resolved base precision (int8 vs fp8)"). A bundle from before the field was recorded counts as not fp8. - **Probe first.** Auto runs the fp8 GEMM probe before it picks fp8, so a card where fp8 fails gets the old pick at decision time. A hosted pre-quantized fp8 file still loads directly, as before. The bf16 fallback still applies when the fp8 conversion fails, and it now moves the host-resident base to the card. One exception: if the bf16 rest does not fit the free VRAM (the 0.9x to 1.15x band, where main trained nf4), the base reloads as nf4 with a fresh adapter instead of going out of memory. ## Measurements Colab L4 (sm89) and RTX PRO 6000 Blackwell (sm120), torch 2.14.1, diffusers 0.42.1. Each arm ran in a fresh process. Settings: 512 px, rank 16, lr 1e-4, 150 steps, compile auto, 16 tarot cards for training and 4 held out. Held-out is a fixed-noise denoising MSE at sigma 0.25 / 0.5 / 0.75, scored on a bf16 base with each run's LoRA, so every arm is judged on the same base. Base is origin/main, using explicit `base_precision` for the quality runs. **L4, full card, 3 seeds each:** | model | held-out MSE, bf16 (mean, range) | held-out MSE, fp8 | int8 (seed 0) | no LoRA | s/step bf16 / fp8 / int8 | pre-loop peak GiB, bf16 / fp8 | |---|---|---|---|---|---|---| | Z-Image | 0.47076 (0.47067-0.47092) | 0.47076 (0.47057-0.47103) | 0.47059 | 0.47338 | 0.759-0.773 / 0.524-0.533 / 1.217 | 12.64 / 6.96 | | FLUX.2 klein base 4B | 0.75697 (0.75671-0.75733) | 0.75708 (0.75651-0.75772) | 0.75728 | 0.76177 | 0.526-0.550 / 0.403-0.412 / 0.871 | 8.34 / 4.88 | | Wan2.2-TI2V-5B | 0.33123 (0.32964-0.33371) | 0.33086 (0.32979-0.33211) | - | 0.34001 | 0.169 / 0.214-0.216 / - | 9.96 / 5.39 | What the table shows: - **Held-out quality:** on all three models, fp8's held-out MSE sits inside the bf16 seed spread. - **Training loss:** the per-step loss tracks bf16 within 0.15 to 0.9% (mean absolute difference per step, same seed). - **Compile:** graph breaks and recompiles were 0 on every arm. - **Loop peak:** the same for bf16 and fp8, because the checkpointing budget fills the room fp8 frees. - **Wan at 512 px:** a frame is 256 tokens here, and fp8 is slower than bf16. That is why Wan keeps its old pick in the 1.15x to 1.5x band. **Inside the old int8 band:** L4, Z-Image, 16.4 GiB free (1.33x), 60 steps, interleaved, 2 runs per Auto arm. | arm | s/step | loop peak GiB | pre-loop peak GiB | |---|---|---|---| | main Auto (bf16 + block swap, 0 of 34 blocks swapped) | 1.057 / 1.075 | 13.80 | 12.64 | | this branch Auto (fp8) | 0.592 / 0.590 | 13.08 | 6.92 | | explicit int8 (eager) | 1.378 | 14.14 | 7.71 | **Below it:** L4, Z-Image, 11.4 GiB free (0.93x), 150 steps. | arm | s/step | held-out MSE (bf16 base) | loop peak GiB | |---|---|---|---| | main Auto (nf4) | 1.289 | 0.47516, worse than no LoRA (0.47338) | 9.06 | | this branch Auto (fp8, streamed) | 0.737 | 0.47066 | 8.83 | | this branch Auto at 1024 px (20 steps) | 3.514 | - | 9.29 | At this free VRAM, main's explicit fp8 cannot load: the 11.46 GiB bf16 base does not fit in 11.4 GiB free. With a full card, the streamed load trains the same way as the old one. Measured: 0.514 vs 0.519 s/step, loss mean 0.39069 vs 0.39071, live held-out 0.47492 vs 0.47513. **Compile off:** L4, Z-Image, 40 steps, ballasted. Each arm ran 2 to 3 times across two passes on the same VM. | free VRAM | main Auto (eager) | explicit fp8 (eager) | this branch Auto (eager) | |---|---|---|---| | 16.4 GiB (1.33x) | bf16 + block swap (0 of 34 swapped): 1.250 / 1.254 / 1.355 s/step | 1.409 / 1.414 / 1.430 | same pick as main: 1.307 / 1.343 | | 11.4 GiB (0.93x) | nf4: 1.300 / 1.336 | 1.686 / 1.703 (the pick before this fix) | nf4, same as main | Eager fp8 was slower than both eager alternatives, by more than the repeat spread, so Auto now requires compile. **RTX PRO 6000 (sm120):** Z-Image, full card, 50 steps, 2 runs each. | px | bf16 s/step | fp8 s/step | speedup | pre-loop peak GiB, bf16 / fp8 | |---|---|---|---|---| | 512 | 0.1172 / 0.1179 | 0.0887 / 0.0895 | 1.32x | 12.76 / 7.04 | | 1024 | 0.468 | 0.367 | 1.27x | 15.27 / 9.58 | **Cost:** a warm launch takes about 20 s longer to reach step 1 with fp8 (55-65 vs 34-45 s on L4). On the first run on a VM it is no slower (88-105 vs 102-112 s). Z-Image pays that back after about 85 steps, klein after about 150. ## Tests - `tests/test_diffusion_fp8_auto_stream.py` (new, CPU), covering: - the streamed conversion lands on the device, and untargeted modules wait for the final move; - the bf16 fallback ends on the device; - the fp8 load without a hosted file stays on the host; - the band table for each family and capability, the family denies, the compile gate in every band and the kill switch; - the resume rule: a recorded fp8 bundle, other bases, a pre-record bundle, an unreadable bundle; - no fp8 with a block swap (config and env), the probe gate (cached per device); - a failed conversion that cannot fall back raises before anything moves, and the host-bytes fit check. - `tests/test_diffusion_gc_budget_replay.py`: a tiny Qwen-Image-2.1 CPU run where the fp8 conversion cannot fall back. The base reloads as nf4, the adapter attaches to the reloaded model and the run trains. - `tests/test_diffusion_base_precision.py` and `tests/test_dense_quant_rocm_gate_9396.py`: the policy rows that move are updated, each with its kill-switch row. - `test_differential.py`: DISCRIMINATING, head_fail=0. - The 25 test modules that touch Auto precision, block swap or fp8: the same single failure on main and on this branch, `test_diffusion_windows_rocm_wide_head.py::test_the_sdxl_trainer_routes_its_vae_attention_before_encoding_latents`. It passes alone on both trees, so it depends on test order and was already there. ## Not proven here - No H100, B200, RTX 40xx or Windows NVIDIA run. sm89 and sm120 were measured; sm90 and sm100 follow the same rule. - Wan was measured only on 512 px images, not video clips (where tokens are many times more). Its 1.15x to 1.5x band keeps the old pick until that is measured. - Only Z-Image was run between 0.9x and 1.15x, and only one seed per arm. That band rests on that run plus the nf4 loss penalty measured earlier on FLUX.3 and Qwen-Image-2.1. - The 16 GB band numbers come from a ballasted L4, not a real 16 GB card. - No GPU run exercised the nf4 reload after a failed conversion (no card here fails the conversion after passing the probe). The CPU run covers the control flow.
Studio diffusion LoRA training can now stream frozen bf16 DiT blocks from pinned host RAM (block swap), and
base_precision=autouses this instead of int8 in the band where the dense base only just fits.Why
When a bf16 transformer barely fits,
autopicks weight-only int8, and int8 trains eager. On an L4 that is 1.4x to 1.5x slower than bf16 at the same loss. unsloth_zoo already has the block swap the LLM trainer uses (unsloth_zoo.block_swap.BlockSwap). It keeps the host copy authoritative, so nothing is copied back, prefetches on a side stream with a depth+1 slot pool, and prefetches in reverse during the checkpoint recompute. This PR wires it into the DiT trainer.Change
core/training/diffusion_block_swap.py.block_swap = off | auto | N(alsoUNSLOTH_DIT_BLOCK_SWAP), bf16 only. N blocks are spread over every repeated block list (FLUX has two).autoswaps the fewest blocks that keep a training reserve free, net of the slot pool.forwardinstead of callingcompile_repeated_blocks. The swap hooks live in_call_impl, and inside a fullgraph compile they would raise. Withsuppress_errorsthat would silently fall back to eager. Measured: 0 graph breaks, the same unique-graph count as the unswapped model.base_precision=auto: when the policy picks int8, train bf16 withblock_swap=autoinstead. If the swap cannot be installed (for example, host RAM), it falls back to int8 from the same host copy. It stays int8 on ROCm, on integrated GPUs, without gradient checkpointing, or withUNSLOTH_DIT_AUTO_BLOCK_SWAP=0. The nf4 and bf16 bands and every explicit precision are unchanged.Numbers (Colab L4, torch 2.14.1, diffusers 0.42.1, fresh process per arm, interleaved, steady = median over steps 11+)
Loss: mean abs per-step difference between head and int8 is 0.00012 to 0.00028. That is close to the bf16 A/A spread of 0.00007 to 0.00019. Peak allocated is 19.0 / 14.6 GiB here vs 18.0 / 16.6 GiB on main. Host RSS is about 10 GiB steady with 7.3 GiB pinned, and about 20 GiB peak while loading.
FLUX.1-dev on the L4 (bf16 does not fit) stays on nf4, because nf4 + compile is faster than bf16 + swap:
block_swap=auto(21 of 57 blocks, 8.1 GiB)There the swap is opt-in, for exact bf16 maths at 1.55x the speed of int8. Copies ran at 12.3 GB/s, about 16 GB per step.
Host RAM guard
A swapped base loads dense on the host, while the int8 path it replaces streams the load. So
autotakes bf16 + swap only when available host RAM (cgroup-aware, the same reading the prequant cache uses) is at least 1.3x the dense bf16 size plus 4 GiB; otherwise, or if the reading is unavailable, it keeps int8. Covered bytest_auto_swap_needs_host_ram_for_the_dense_base.Tests
tests/test_diffusion_block_swap.py(CPU, 21 tests) covers request parsing, gating, both planners, block list discovery, compile routing, and the auto int8-band decision including every exclusion.test_diffusion_dit_trainer.py+test_diffusion_gc_budget.py+ the new file: 98 passed.Not proven here