Repository navigation
Studio diffusion training: train DiT LoRAs on T4 and other non-bf16 GPUs in fp16 with loss scaling (FLUX.2-klein, Z-Image, Wan 2.2 5B) - #18355
Conversation
…caling FLUX.2-klein, Z-Image and Wan2.2-TI2V-5B were refused on pre-Ampere CUDA cards. They now train there on the nf4 base under fp16 autocast with a GradScaler, fp32 LoRA weights, an fp32 residual stream and per-family fp32 modules (modulation, final layer, and the Z-Image refiner projections that overflow fp16, found with finite checks). Overflow steps skip the update without advancing the step counter, LR schedule or EMA; the scaler state rides in resume checkpoints. bf16 cards keep the old path; UNSLOTH_STUDIO_DIT_FP16=0 restores the refusal.
A finite-check pass with only the refiner blocks in fp32 found layers.0 w2 overflowing on every forward (its input alone reached 2.3e5), so the post-norm output projections run fp32 in all blocks.
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 |
|
Codex Review: Didn't find any major issues. 🚀 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". |
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.
On a T4 the dequant cache and the checkpointing budget both plan from step 1's free memory: the cache took 7.4 GiB, the budget kept all 25 klein blocks (7.1 GiB), and step 2 ran out of memory and fell back to checkpointing every block (2.98 s/step against 2.27 s/step with the budget alone). bf16 runs keep the cache unchanged.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
[skip ci]
…r the tiny fixture (#2598) ## Summary `tests/test_grpo_fused_route.py::test_prefix_grouper_forward_matches_log_prob_route` fails all four cases (grpo, dapo, cispo, sapo) against current unsloth main: ``` tests/test_grpo_fused_route.py:251: in test_prefix_grouper_forward_matches_log_prob_route E assert (2 == 2 and False) E + where 2 = len([None, None]) ``` Seen in both unsloth "Core zoo" jobs (HF default + TRL default, and HF 4.57.6 + TRL<1) on the staging run for unslothai/unsloth#18355, which is on current unsloth main. ## Cause unslothai/unsloth#18405 (the companion to #2596) adds a saved-token cost gate to PrefixGrouper. `build_group_layout` returns `None` when a call would save fewer than `UNSLOTH_GRPO_PREFIX_GROUPER_MIN_SAVED` prompt tokens (default 1024, from L4 break-even measurements), so short prompts stay on the faster packed path. That is intended behaviour. This test's fixture is 2 prompts of 4 tokens with 3 completions each, so it saves only a handful of tokens. The gate now declines both layouts, and the test's own assertion (both arms grouped the batch) fails. The test checks that the grouped forward matches the log-prob route. It does not test the gate. Bisected: | unsloth | zoo | result | |---|---|---| | `beec0a3800^` (before #18405) | `11c88bac1` | 4 passed | | `beec0a3800` (#18405) | `11c88bac1` | 4 failed | | `beec0a3800` | `e9728df56` (before #2590 .. #2597) | 4 failed | So the zoo commits are not involved. ## Fix Test-only. `_prefix_grouper_funcs` sets unsloth's `_MIN_SAVED` floor to 0, through `monkeypatch`, when the loaded `prefix_grouper` has one. Older unsloth without the gate is untouched. The test still asserts that both arms built a layout and ran the shared-prefix forward, so if grouping stops engaging for any other reason it still fails. ## Verification `tests/test_grpo_fused_route.py`, all 76 tests: | unsloth | this branch | |---|---| | main (`beec0a3800`, with the gate) | 76 passed (before: 4 failed) | | before #18405 (no gate) | 76 passed | ruff is clean.
…ts too The card fixture patched torch_is_rocm but not the torch build check in native_bf16_supported, so on a ROCm host (gfx1151 runner) the spoofed T4 read as a bf16 AMD card and 11 T4 tests failed. Patch torch.version.hip and is_rocm_torch as well.
The fp16 trainer always runs eager, but family_train_infos still reported supports_compile for klein, Z-Image and Wan 5B on a T4, so the panel showed a compile control that the run ignored. bf16 cards are unchanged.
…lines An API caller sending compile_transformer='on' on a GPU without bf16 was run eager with no message. Log a warning and emit the same warning event the trainer uses for other declined options; the run still trains. bf16 cards never reach this code. [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
…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.
…ds on T4 (1.7x per step) (#19057) ## Summary Z-Image LoRA training on a T4 (fp16 path from #18355) spent about half of every step in fp32 `volta_sgemm`: `attention.to_out.0` and `feed_forward.w2` run as fp32 islands in all 34 blocks because their activations pass the fp16 range. This PR keeps those islands but runs their nf4 matmul on fp16 tensor cores with fp32 accumulate and fp32 output. A power-of-two input scale keeps the fp16 operand in range, so nothing can overflow. Colab T4, Z-Image-Turbo, nf4, 512 px, rank 16, gradient checkpointing, 300 steps, 3 seeds each: | | s/step (median) | peak | skipped steps | |---|---|---|---| | main | 6.62, 6.64, 6.60 | 11.51 to 11.52 GB | 0 | | this PR | 3.88, 3.89, 3.87 | 11.46 GB | 0 | That is 1.71x faster per step (-41%). At 1024 px (5 steps, so only a rough speed): 18.6 vs 26.1 s/step, peak 11.20 vs 11.09 GB. The checkpointing budget fills the card to about the same level in both, so the peak is that budget, not a floor. ## What overflows (measured on the T4) Max over 5 real training steps, all 34 blocks: | module | max abs input | max abs output | max abs grad out | modules past 65504 | |---|---|---|---|---| | `to_out.0` | 1.7e3 | 1.4e5 | 17 | output: 2 of 34 | | `w2` | 2.3e5 | 8.7e5 | 143 | input: 1 of 34 (`layers.0`), output: 14 of 34 | | `w1` (fp16, reference) | 56 | 481 | 939 | none | - The forward activations overflow, not the grads: with the GradScaler at 65536 the largest grad is 1.5e3. - `w2`'s input is fp32 (the LoRA wrapper returns fp32 for `w1` / `w3`), so `silu(w1) * w3` reaches 2.3e5 before the island. - The weights stay well inside fp16 range (max 2.7). They are not exact in fp16, though: see "Weight precision" below. ## How `diffusion_dit_fp16.py`: - New table `FP16_SCALED_MM_MODULES` (Z-Image `to_out.0` and `w2` only). The island still turns autocast off and runs the LoRA branch in fp32. Only the nf4 base matmul changes. - Forward: scale the input by a power of two so its amax lands in (2^14, 2^15], split it into fp16 high and low parts, run one fp16 GEMM with fp32 output (`torch.mm(out_dtype=torch.float32)`), then undo the scale. The split keeps about 22 mantissa bits of the input. Both parts are written straight into the fp16 buffer, with no fp32 copy of the input. - The scale exponent is bounded at +/-113, so every finite fp32 amax (up to fp32 max) lands at or under 2^15. - Input grad: the same scaled GEMM with one fp16 term. - The nf4 weight is dequantised straight to fp16 (one rounding of the exact value). - inf or nan inputs stay non-finite, so the GradScaler still skips those steps. - Falls back to the fp32 island when `torch.mm` has no `out_dtype`, on GPUs below sm70, for a weight past the fp16 range, or with `UNSLOTH_STUDIO_DIT_FP16_SCALED_MM=0`. The support probe runs per device (`cuda:N`), on the card the nf4 weights live on. A CUDA out-of-memory during the probe or the install check propagates instead of being cached as "unsupported". - `model_load_completed` reports `fp16_scaled_mm` (layers installed, 68 on Z-Image). At the end of the run, `fast_lora_stats` (or `fp16_stats` without fast LoRA) adds `fp16_scaled_mm_calls`, the scaled GEMM forwards actually taken. On the T4 that is about 94 per step. klein and Wan 2.2 5B are unchanged: their island tables have no scaled entries (`fp16_scaled_mm: 0`). ## Weight precision `dequantize_4bit` returns the quant state's dtype, which is bf16 on Z-Image. bitsandbytes' own fp32 forward (the fp32 island on main) dequantises straight to fp32. Until the last commit the scaled GEMM used the bf16 copy, so its weights carried 8 mantissa bits. It now asks for fp16 directly. Real nf4 `w2` (10240 to 3840) under a PEFT LoRA on a T4, inputs up to 2.3e5, rel-L2: | | bf16 dequant (before) | fp16 dequant (this PR) | |---|---|---| | weights vs exact nf4 values | 1.6e-3 | 2.1e-4 | | forward vs the fp32 island | 1.5e-3 | 2.0e-4 | | input grad vs exact weights | 1.6e-3 | 2.9e-4 | | GEMM vs fp32 on the same weights, forward | 1.6e-5 | 1.6e-5 | | GEMM vs fp32 on the same weights, input grad | 2.1e-4 | 2.1e-4 | The fp32 island's own input grad also dequantises to bf16 (1.6e-3 from exact). Same speed: 3.83 s/step over 40 steps, with all 68 layers installed and about 95 scaled GEMM calls per step. ## GEMM accuracy and speed on captured tensors Real Z-Image inputs and grads from training, T4, error vs an fp64 matmul on the same weights (rel-L2), CUDA-event median. These numbers predate the last commit. They measure the GEMM on fixed fp16 weights, which that commit did not change: | GEMM (1056 tokens) | fp32 island | fp16 one term | fp16 hi + lo (this PR) | |---|---|---|---| | `w2` forward error | 0.5e-6 to 2e-6 | 4.5e-5 to 1.4e-4 | 5e-6 to 2.3e-5 | | `w2` forward time | 29 ms | 5.5 to 6.2 ms | 8.3 to 9.4 ms | | `w2` input-grad error | 0.6e-6 to 0.7e-6 | 1.4e-4 to 2.0e-4 | (one term) | | `w2` input-grad time | 25 ms | 4.7 ms | (one term) | | `to_out` forward time | 7.8 ms | 1.6 ms | 3.0 ms | Every other nf4 linear in the step already runs fp16 in and out: `w1` measures 2.1e-4 to 2.5e-4 on the same data. Profile, 2 steps: GEMM time 4.05 s to 1.56 s per step, elementwise 1.15 s to 1.35 s. ## Accuracy ### LoRA grads vs an all-fp32 reference Same seed and data, step 1. The reference runs every block as an fp32 island. Aggregate rel-L2 over all LoRA grads, median of the per-parameter rel-L2, and the worst parameter: | | aggregate | median per parameter | worst parameter | |---|---|---|---| | main A/A (two main runs) | 0.05% | 0.0% | 0.13% | | main | 0.99% | 0.11% | 4.2% (`noise_refiner.0.feed_forward.w3.lora_B`) | | this PR before the fp16 dequant | 1.49% | 0.26% | 5.4% (`layers.15.attention.to_k.lora_B`) | | this PR | 1.29% | 0.12% | 5.7% (`noise_refiner.0.feed_forward.w3.lora_B`) | | fp16 one term, bf16 weights | 2.34% | 0.26% | 8.5% | - Steps 2 and 3, same reference: main 10.8% and 1.46%, this PR 12.5% and 1.27% (median per parameter 0.10% / 2.8% vs 0.13% / 2.6%). Before the fp16 dequant: 53% and 2.8%. - Step 2 amplifies any change: Adam's first update is close to sign(g), so near-zero grads that flip sign change the weights. ### Short runs (40 steps) Measured before the last two commits, same seed and data, fresh process per arm, base and head interleaved on one T4: | | main A/A | this PR vs main | |---|---|---| | per-step loss, median relative difference | 0.7e-4 to 1.6e-4 | 4.2e-4 to 4.8e-4 | | mean loss, steps 1-40 | 0.36307 to 0.36334 (4 runs) | 0.36304, 0.36307 | | mean loss, steps 21-40 | 0.31547 to 0.31601 (4 runs) | 0.31550, 0.31558 | | sample LPIPS after 40 steps | 0.0013, 0.0014 | 0.0013 to 0.0021 | | sample LPIPS before training | 0.0 | 0.0014 | ### Training quality after 300 steps Z-Image-Turbo is a few-step distilled model, so LPIPS against main's samples says little about quality. The adapters were trained on the head before the fp16 dequant commit, which is the less accurate variant, then scored on one common inference path (main's fp32 islands), so arms differ only in their adapter. 3 seeds each, 8 training images. Held-out denoising loss: 4 images from the same 3dicon set that are not in the training set, 6 fixed sigmas (0.15 to 0.9), 2 fixed noise draws each: | seed | main | this PR | difference | |---|---|---|---| | 0 | 0.28690 | 0.28739 | +0.00050 | | 1 | 0.28562 | 0.28570 | +0.00008 | | 2 | 0.28696 | 0.28706 | +0.00010 | | no LoRA | 0.39001 | | | Main's seed-to-seed spread is 0.00134. The mean difference (+0.00022) is 0.17x of it. Text alignment and preference: 10 prompts (4 of the sample prompts plus 6 new 3dicon prompts), one fixed noise per prompt, 8-step Euler. CLIP-T is `openai/clip-vit-large-patch14`, 100 x cosine; PickScore is `yuvalkirstain/PickScore_v1`. Both score against the prompt without the trigger words: | | main, per seed | this PR, per seed | mean difference | main seed-to-seed range | |---|---|---|---|---| | PickScore | 21.54, 22.10, 22.06 | 21.46, 22.16, 22.02 | -0.02 | 0.57 | | CLIP-T | 29.97, 30.20, 29.73 | 27.82, 30.85, 29.49 | -0.58 | 0.46 | - Per prompt, the PR vs main on the same seed is closer than main vs main across seeds. PickScore median abs difference 0.13 vs 0.31; CLIP-T 0.92 vs 1.35. - PickScore: the mean difference is 0.04x of main's seed-to-seed range; paired t over prompts is -0.27. - CLIP-T: seeds 1 and 2 sit inside main's range. Seed 0 is lower (-2.15), mostly on two prompts, so the mean difference (-0.58) is just outside main's per-seed range (0.46); paired t over prompts is -1.74, which is not significant. Seed 0 run again on the same VM: main with the same seed and code (the backward is not bit-reproducible, so two main runs drift apart), and this PR with the fp16 dequant commit. Same eval; the no-LoRA scores repeat to the last digit, so the eval is deterministic: | seed 0 | main | main again | this PR before the fp16 dequant | this PR | |---|---|---|---|---| | held-out loss | 0.28690 | 0.28742 | 0.28739 | 0.28720 | | CLIP-T | 29.97 | 29.33 | 27.82 | 29.45 | | PickScore | 21.54 | 21.83 | 21.46 | 21.84 | | s/step | 6.62 | 6.71 | 3.88 | 3.86 | - Main against itself on seed 0 moves CLIP-T by 0.64 on the mean and 1.79 per prompt, and held-out loss by 0.00052. - This PR lands between the two main runs on held-out loss and CLIP-T, and within 0.01 of "main again" on PickScore. Per prompt it is 0.62 (CLIP-T) and 0.20 (PickScore) from "main again". - The earlier head's seed-0 CLIP-T (-2.15) is outside that run-to-run drift. Against the spread of all four main runs (CLIP-T 29.33 to 30.20, range 0.87), its 3-seed mean difference of -0.42 is inside. - 68 scaled layers and 28240 scaled GEMM calls in 300 steps (94 per step), 0 skipped steps. ### Cross-seed check (300 steps, earlier run) Same T4 VM, fresh process per arm, interleaved base s0, head s0, base s1, head s1, base s2, head s2; 300 steps each; sampler noise pinned so every seed renders from the same noise. Measured on b6f05c2. The T4 path is unchanged from there to the commit before the fp16 dequant: the step-1 model output on a fixed batch is bit-identical. LoRA grads differ by 5.6e-4, the same as two runs of the same code (5.5e-4; the backward is not bit-reproducible). | seed | main, mean loss steps 201-300 | this PR | difference | |---|---|---|---| | 0 | 0.23995 | 0.23878 | -0.00118 | | 1 | 0.23813 | 0.23793 | -0.00020 | | 2 | 0.23414 | 0.23450 | +0.00036 | - Main's seed-to-seed spread is 0.0058; every head value sits inside it. - Samples after 300 steps (4 prompts, 12 of 12 pairs): head vs main on the same seed is mean LPIPS 0.037 (0.0012 to 0.174); main vs main across seeds is 0.101 (0.030 to 0.358). One of the 12 images (seed 2, prompt 2) was missing from the earlier table because the executed notebook dropped its output line. It was recovered from the run's streamed log (LPIPS 0.0012). - The repeat run above (seeds 0, 1, 2) gives main 0.23935 / 0.23817 / 0.23442 and head 0.23963 / 0.23770 / 0.23425 for the same window. ## Final head on a T4 Colab T4, Studio installed at the final head, main = the same install with this diff reversed, 40 Z-Image LoRA steps (nf4, 512px, rank 16, gradient checkpointing, seed 0), fresh process per run, interleaved: | run | scaled layers | scaled calls | skipped steps | s/step | step-40 loss | peak | |---|---|---|---|---|---|---| | main, run 1 | - | - | 0 | 6.32 | 0.3366 | 11.52 GB | | main, run 2 | - | - | 0 | 6.33 | 0.3365 | 11.52 GB | | this PR, run 1 | 68 | 3800 | 0 | 3.63 | 0.3373 | 11.47 GB | | this PR, run 2 | 68 | 3800 | 0 | 3.31 | 0.3374 | 11.47 GB | | this PR, Q/K/V-only adapter | 68 | 3176 | 0 | 3.00 | 0.4348 | 11.71 GB | The mean loss over the last 20 steps is 0.3154 here against 0.3158 on main, and the loss scale stays at 65536 throughout. The Q/K/V-only run leaves to_out.0 and w2 without an adapter, so the islands wrap the bare nf4 linears: the scaled path still runs and nothing overflows (its loss is a different adapter's, not comparable). `test_diffusion_dit_fp16_t4.py` on the same T4: 71 passed, including the CUDA test against the fp32 island. GTX 16xx cards (sm75 without tensor cores) now keep the fp32 islands. ## Tests `studio/backend/tests/test_diffusion_dit_fp16_t4.py`, all CPU unless noted (all new ones fail on main): - install on `to_out.0` / `w2` only, and the kill switch installs nothing - finite past fp16 range, matching fp32 in the forward and in the input grad - the split keeps fp32-level input precision, and the in-buffer split equals the old fp32-copy split (200-case sweep, 1e-30 to 1e30, zeros, -0, nan) - power-of-two scale bounds, including amax 1e30, fp32 max and tiny values - non-finite inputs stay non-finite - fallback for a weight past fp16, pre-sm70 GPUs and `torch.mm` without `out_dtype` - per-device probe cache, probe on the weights' card, OOM propagates and is not cached (probe and install) - runtime call counter, and the trainer's load and end-of-run reports (behavioural, replacing a source-text check) - dequant asks bitsandbytes for fp16 directly - gradient checkpointing recompute - CUDA: a real bitsandbytes nf4 `w2` (10240 to 3840) under PEFT. It checks that 1 layer is installed, the probe returns True on sm75, and one call is counted. It also checks the GEMM against fp32 on its own weights, end to end against the fp32 island within the weight rounding, and the input grad closer to exact than the island's own. It passed on the Colab T4 (70 passed there). The fp16, fast LoRA, frozen int8, int8 dequant cache, DiT trainer and LoRA trainer suites: 501 passed, 1 skipped (the CUDA test, no local GPU). ## Not covered - 300 steps on 8 images at 512 px. 1024 px only for 5 steps (peak and a rough speed). No gradient accumulation, no resume. - The 300-step quality runs used the head before the fp16 dequant commit, except one seed-0 run of the final head. The final head has no 3-seed run. - Only a Colab T4 (sm75). Other non-bf16 cards and torch builds without `mm(out_dtype=)` take the fp32 fallback, which has only CPU tests. The per-device probe has only CPU tests with mocked devices. - klein and Wan regression runs are short (20 and 12 steps). Their code path is unchanged.
Summary
Studio's DiT LoRA trainer refused every GPU without native bf16, such as the T4 (sm75), before any model loaded:
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:
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=0brings back the old refusal;=forcetakes the fp16 path on a bf16 card for parity checks.flux.2-klein,z-imageandwan2.2-ti2v-5bonly.nf4.fp16.Precision layout (new
diffusion_dit_fp16.py):attention.to_out.0andfeed_forward.w2in 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):torch.compileis off on this path.grad_scaleandskipped_steps.Accuracy
Per-step loss against an L4 bf16 run at the same seed (median relative difference):
Mechanics checked on the T4:
bf16 cards are unchanged
bfloat16, no fp16 AMP andmixed_precision == "bf16".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
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:
install_fast_loranow 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.whileloop 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:
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
cardfixture now also pinstorch.version.hipandrocm_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_transformer="on"on the fp16 path now gets awarningevent and a log line saying the run trains eager.auto,offand unset stay silent. The call sits underif 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=forceopt-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.