Repository navigation
Studio diffusion training: Auto trains on a frozen fp8 base on sm89+ cards - #18770
Conversation
…ow the bf16 band Between 1.15x and 1.5x of the dense bf16 size in free VRAM, Auto now picks the frozen fp8 base on NVIDIA sm89+ instead of int8 (or the block swap that replaces it). The fp8 base also loads host-first and is quantized onto the card Linear by Linear, so it never holds the whole bf16 base on the device and fits from 0.9x dense, where Auto used to drop to nf4. UNSLOTH_DIT_AUTO_FP8=0 restores the previous picks.
… 6000 runs Above 1.5x, Z-Image and FLUX.2 klein train on the frozen fp8 base (1.32-1.45x faster than compiled bf16 at the same held-out loss); other families keep bf16 there. Wan2.2-TI2V-5B keeps the block swap / int8 pick between 1.15x and 1.5x, since at 256 tokens per 512 px frame fp8 measured slower than bf16.
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 |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
…lock swap and eager runs, reloads nf4 when bf16 cannot fit - A resume continues the base its bundle recorded: Auto picks fp8 only when that bundle trained fp8 (an int8 / bf16 / nf4 or pre-record bundle was refused after the full load). - A requested block swap streams a bf16 base only, so Auto no longer picks fp8 with one. - The 1.15x-1.5x fp8 pick needs a compiled run (it was measured compiled); an eager run keeps the previous pick. Below 1.15x fp8 stays the pick and the eager-fp8 warning is for explicit fp8. - Auto probes the fp8 GEMM before picking it, and a conversion that fails where the bf16 rest does not fit the card reloads the base as nf4 instead of moving bf16 onto it.
On an L4 (Z-Image 512 px, compile off) eager fp8 lost to the eager picks it would replace: 1.41 s/step vs bf16 + block swap 1.25-1.36 at 1.33x free, 1.69-1.70 vs nf4 1.30-1.34 at 0.93x. An eager run now keeps the previous picks in every band, and the eager-fp8 warning stays as it was. [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: 2c73f4a278
ℹ️ 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".
| transformer = None | ||
| gc.collect() | ||
| _empty_device_cache(device) | ||
| with report_model_load_progress(on_event): | ||
| transformer = spec.load_transformer(fetch_cfg, device, weight_dtype, "nf4") |
There was a problem hiding this comment.
Release the failed fp8 model before loading the nf4 replacement
When fp8 conversion fails after moving some layers onto the GPU and the bf16 remainder does not fit, the caught exc retains _apply_fp8_training's frame through its traceback, including that frame's transformer reference. Setting the caller's transformer to None therefore does not free the old base, and neither garbage collection nor emptying the device cache releases its live GPU tensors. The nf4 replacement is consequently loaded alongside the partially converted base on an already memory-constrained card, potentially causing another OOM instead of recovering. Perform the reload after leaving the exception handler and releasing the exception's retained frames.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Thanks, fixed in 8c8795d: the nf4 reload now runs after the exception handler (the handler only records the message), and the old base and the stale LoRA param list are dropped before gc and the device cache flush, so the half-converted base is no longer held by the traceback while nf4 loads. The reload test now checks through a weakref that the failed base is collected before the nf4 load starts.
… reload, outside the exception handler [skip ci]
|
@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". |
…t, ROCm budgets, DDP precision, block swap (#18967) Follow-ups for the Studio diffusion training changes in #18770, #18771, #18782, #18825 and #18869. There is one commit per fix. Each change is small and has its own kill switch or opt-in. ## Changes 1. **Auto fp8 below 1.15x free VRAM now checks host RAM first (#18770).** In the 0.9x-1.15x band the fp8 base loads the dense bf16 transformer on the host and then streams it to the card. The nf4 pick it replaced loads shard by shard onto the device. Example: on a 32 GB desktop with a 4090 and FLUX.1-dev, roughly 24 GB of bf16 sat in host RAM. The band now uses the same host-RAM check as the bf16 block-swap pick (`_auto_swap_host_ram_ok`: 1.3x dense + 4 GiB, and an unreadable reading counts as no). If the check fails, Auto picks nf4 as before. The 1.15x-1.5x band is unchanged, because the int8 pick it replaced already loaded host-first. 2. **Below 1.5x, Auto picks fp8 only for measured families (#18770).** Both lower bands gave fp8 to every family that was not explicitly denied. Held-out loss was measured only for Z-Image, FLUX.2 klein and Wan. A new `_AUTO_FP8_MEASURED` set gates those bands, the same way `_AUTO_FP8_OVER_BF16` already gates the band above 1.5x. FLUX.1, FLUX.2-dev, FLUX.3 klein, Krea, LTX and the other families keep their int8 / nf4 picks until someone measures them. 3. **The fp8 layer now gives `_scaled_mm` a row-major activation and grad_y.** The fp8 codes keep the input's memory layout, and CUDA `_scaled_mm` rejects a column-major first operand. The flattened input and the incoming gradient now get `.contiguous()` before quantising. This is a no-op when they are already contiguous. 4. **The memory budgets stay off on discrete Windows ROCm cards (#18825).** On Windows ROCm the budgets see the whole card as free, and WDDM serves an overflow from host RAM instead of raising. The OOM step-down therefore never fires. The budgets were measured only on a unified-memory gfx1151. On a discrete (non-APU) Windows ROCm card, budgeted checkpointing and the dequant cache now stay off. Detection uses `is_rocm_torch` and `device_is_integrated`. `UNSLOTH_DIFFUSION_GC_MODE=auto` and `UNSLOTH_DIFFUSION_DEQUANT_CACHE=1` opt back in explicitly. APUs, Linux ROCm and CUDA are unchanged. 5. **Multi-GPU runs now check the base precision after conversion (#18770 / #18782 with #18771).** `agree_precision` fixes one pick for every rank. The fp8 / W8A8 conversion fallbacks, though, run per rank: bf16, an nf4 reload, or torchao weight-only int8. After the conversions, every rank now all_gathers one int64 code for the base it actually trains. If the codes differ, every rank raises a clear error instead of all-reducing grads from different base numerics. 6. **Block-swap plans are resized after a failed conversion (#18869).** The swap plan counts every target Linear as 1-byte codes. A layer whose conversion fails stays bf16, so the plan under-counted it by 2x. If any conversion failed, an auto plan is now resized from the actual tensors. Any extra blocks it needs are added to the first plan, and their codes move to host RAM. 7. **Removed the dead `diffusion_gc_budget._is_rocm` (#18825).** Nothing called it, and it checked only `torch.version.hip`. 8. **The int8 / fp8 numerics tests now use an fp64 oracle (#18782).** The old test checked only cosine similarity. It now bounds the relative L2 error of forward and grad_x against a float64 dense layer: - int8: bound 2e-2, measured 0.86e-2 (0.45e-2 on the dense path under 17 rows). - fp8: bound 6e-2, measured 3.7e-2. A second check shows that a 5% weight-scale error breaks the bound while cosine stays near 1. ## Tests All on CPU and targeted. Each new test was also run against the merge base `b1caa38f6f`: | Item | Test | main | this branch | |---|---|---|---| | 1 | `test_diffusion_fp8_auto_stream.py::test_auto_fp8_below_1_15x_needs_host_ram_for_the_bf16_load` (low / unreadable host RAM keeps nf4) | fails (fp8) | passes | | 2 | `test_diffusion_fp8_auto_stream.py::test_auto_fp8_unmeasured_families_keep_the_previous_pick` (12 cells) | fails | passes | | 3 | `test_diffusion_frozen_fp8_layout.py` (column-major x, column-major grad_y, batch-1 transposed input, under the CUDA layout contract) | fails ("self must be row_major") | passes, bit-identical to contiguous | | 4 | `test_diffusion_gc_budget_rocm_windows.py` (discrete Windows ROCm off; APU, Linux ROCm and CUDA on; explicit opt-in; kill switches) | fails | passes | | 5 | `test_diffusion_ddp_effective_precision.py` (mocked process group on both ranks, plus a real 2-rank gloo run) | fails | passes | | 6 | `test_diffusion_block_swap_lowp.py::test_auto_plan_resized_when_a_conversion_fails` | fails (6 blocks swapped either way) | passes (11 blocks) | | 8 | `test_diffusion_frozen_int8.py` fp64 bounds | passes (test-only change) | passes | Existing tests whose expectations change with item 2, because unmeasured families now keep int8 / nf4: `test_pick_auto_precision_policy_table`, `test_resolve_auto_int8_band_gates_on_torchao`, `test_pick_auto_precision_fp8_band` and `test_pick_auto_precision_per_family`. Every touched module's test file, plus every file that exercises `_resolve_base_precision`, ran on main and on this branch. The failing test IDs match, apart from the intended changes listed above. ## GPU check (item 3) NVIDIA L4 (sm89), torch 2.14.1+cu130, K = N = 3072, T = 1024, with a batch-1 transposed activation and a transposed grad_y: | Case | main | this branch | |---|---|---| | contiguous | ok | ok, bit-identical to main | | column-major x | `CUBLAS_STATUS_NOT_SUPPORTED` | ok, `torch.equal` to contiguous for y and grad_x | | column-major grad_y | `CUBLAS_STATUS_NOT_SUPPORTED` | ok, `torch.equal` to contiguous | The forward relative error against fp64 is 3.69e-2 in both arms. ## Not covered here - Item 1: host-RAM peak for a real 20+ GB family at about 1.0x free VRAM (a cgroup-limited Auto run). The gate is conservative: a family with a hosted fp8 file loads straight to the card, so it could keep fp8 on a low-RAM host but now gets nf4, the pick it had before #18770. - Item 4: not run on a discrete Radeon card under Windows. The gate keeps the pre-#18825 behaviour there. - Item 5: the real multi-GPU trainer loop. The DDP loop tests skip here because the installed diffusers has no Qwen-Image-2.1. The collective itself ran on real gloo with 2 ranks. - Item 6: the resize path has a CPU test only. A conversion failure is hard to trigger on a real card.
…A8 preflight, atomic W8A8 conversion, int8 kernel in resume identity, torch 2.4 op (#18980) ## Summary Follow-up fixes from a recheck of the Studio diffusion LoRA training PRs #18770, #18782, #18825, #18860 and #18869 (frozen fp8 / int8 W8A8 bases, ROCm memory budgets, cached int8 backward weight, low-precision block swap). Each commit fixes one root cause and adds a test that fails on `main` and passes here. Findings already handled by #18967 (fp8 Auto host-RAM gate, measured-family fp8 band, row-major `_scaled_mm`, discrete Windows ROCm budgets off, DDP effective-precision check, block-swap re-plan after a failed conversion) are not repeated. This branch merges cleanly with #18967 and with current `main`. ## Changes 1. **Auto skips the fp8 GEMM probe when fp8 cannot be picked** (#18770). `_resolve_base_precision` ran `_auto_fp8_probe_ok` (allocate, scaled GEMM, sync, plus a failure warning on sm80) before the sm89 and compile checks. An A100 or an eager run paid for the probe even though the policy never picks fp8 there. The cheap gates now run first. Picks are unchanged. 2. **fp16 W8A8 is no longer refused at preflight for a missing torchao** (#18782). On an fp16-fallback card (T4) with `UNSLOTH_DIFFUSION_INT8_TRAIN=w8a8`, the trainer builds the W8A8 base with `torch._int_mm` and raises rather than falling back to torchao. The start preflight still required a functional torchao for `base_precision='int8'`. The bf16 route keeps the check, because its fallback is torchao weight-only int8. 3. **A partly converted W8A8 base is refused, not mixed with torchao int8** (#18782). `convert_frozen_int8` moves each host Linear to the device outside its per-layer handler. If a later move hit an OOM, the error escaped after earlier layers were already W8A8. The bf16 trainer then quantized the remaining `nn.Linear` layers with torchao weight-only, giving a mixed base that compile, the backward-weight cache and the checkpoint all treated as weight-only int8. This case now raises a clear error. A failure before any layer converts still falls back as before. 4. **Resume records whether the int8 base was W8A8 or weight-only** (#18782). Both int8 bases recorded `base_precision_effective='int8'`, so flipping `UNSLOTH_DIFFUSION_INT8_TRAIN` across a resume switched the base math under the restored adapter and optimizer with no refusal. The kernel is now stored as an optional identity field (`base_int8_kernel`), so a switch is refused with a named reason. Bundles written before the field still resume. 5. **The W8A8 backward-weight op registers on torch 2.4** (#18860). The module used `from __future__ import annotations`, so torch 2.4's `custom_op` schema inference saw `'torch.Tensor'` strings and raised. The error was swallowed, and the cache never engaged. On torch 2.4 the base gives 0 cache hits and the head gives 1 hit and 1 miss over two backwards. Gradients are bit-identical either way. ## Testing - Flip tests: each new test fails on `main` (b0bc664) and passes on this branch. Each arm imported its own tree. - Focused suites on head: `test_diffusion_fp8_auto_stream`, `test_diffusion_frozen_int8`, `test_diffusion_frozen_int8_bwd_cache`, `test_diffusion_base_precision`, `test_diffusion_block_swap_lowp`, `test_diffusion_checkpoint_resume`, `test_diffusion_ddp`, `test_diffusion_dit_fp16_t4`, `test_diffusion_dit_trainer`, `test_diffusion_training`: 583 passed, 10 skipped. - Wider trainer suites (22 files): the same 16 failures and 14 errors on base and head, with identical test IDs. They are pre-existing environment import errors (`huggingface_hub.get_cached_repo_tree` / diffusers pipeline imports). - torch 2.4.0 (Python 3.12, CPU) check for change 5: base `int8 op: False`, `hits 0`; head `int8 op: True`, `hits 1 misses 1`. ## Not covered - No GPU run. None of the five changes touches kernel math: they change gate ordering, preflight logic, an error path, checkpoint identity and op registration. Real-GPU W8A8 / fp8 training was not rerun. - Windows ROCm, macOS and multi-GPU were not run.
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), butbase_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_precisionindiffusion_dit_trainer.py, NVIDIA sm89+ only (has_fp8is now false on ROCm, with the Windows-ROCm torchao stub, for families whose explicit fp8 training is refused (qwen-image, moss-image), and withUNSLOTH_DIT_AUTO_FP8=0):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.Auto picks fp8 only when it is safe to:
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.block_swaporUNSLOTH_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.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_precisionfor the quality runs.L4, full card, 3 seeds each:
What the table shows:
Inside the old int8 band: L4, Z-Image, 16.4 GiB free (1.33x), 60 steps, interleaved, 2 runs per Auto arm.
Below it: L4, Z-Image, 11.4 GiB free (0.93x), 150 steps.
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.
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.
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: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.pyandtests/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.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