Repository navigation
Studio diffusion training: opt-in frozen int8 W8A8 base (UNSLOTH_DIFFUSION_INT8_TRAIN=w8a8) - #18782
Conversation
…LOTH_DIFFUSION_INT8_TRAIN=w8a8) Weights quantized once per row; forward and the input gradient run torch._int_mm on per-row int8 activation / grad codes. For A100, RTX 30xx and T4, which have int8 tensor cores but no fp8. Compiles under regional compile; the T4 fp16 path can take it instead of nf4.
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 Summary: ❌ FailedThis 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7902f716b3
ℹ️ 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".
| new._studio_lowp = "int8_w8a8" | ||
| setattr(parent, child, new) |
There was a problem hiding this comment.
Preserve fp32 islands when replacing untargeted linears
With W8A8 enabled on the fp16 path, Z-Image training with attention-only LoRA targets loses the fp32 protection on its untargeted feed_forward.w2 layers. _train_dit installs the islands before this conversion, and make_fp32_island stores the autocast-disabling wrapper on the original module's forward; replacing that module here discards both the wrapper and its island marker. These layers then run under fp16 autocast even though diffusion_dit_fp16.py explicitly identifies them as overflowing, which can produce non-finite losses and repeated skipped training steps. Reinstall the islands after conversion or preserve their behavior on the replacement modules.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Thanks, fixed in e629260: when the W8A8 conversion replaces a module that carried an fp32 island it re-installs the island on the new FrozenInt8Linear, so an untargeted layer such as Z-Image feed_forward.w2 still computes fp32 on the fp16 path. Covered by test_conversion_keeps_the_fp32_island_on_an_untargeted_layer. 62f5676 also keeps int8 eager when W8A8 did not build and refuses W8A8 below sm75 at the preflight.
…th's fp32 islands On the fp16 path the fp32 islands are installed before the W8A8 conversion and live on the module's forward, so replacing an untargeted island layer (Z-Image feed_forward.w2 under an attention-only LoRA) dropped its autocast-off fp32 wrapper. The converted layer now gets the island re-installed.
…and the preflight refuses W8A8 below sm75 [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
# Conflicts: # studio/backend/core/training/diffusion_dit_trainer.py [skip ci]
…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.
On GPUs with int8 tensor cores but no fp8 (A100, RTX 30xx, T4), Studio's int8 LoRA training base is torchao weight-only int8. That base rebuilds a bf16 weight for every matmul and cannot be compiled, so on an A100 it trains 1.7x slower than compiled bf16. This adds a frozen W8A8 int8 base, built the same way as the frozen fp8 base and behind
UNSLOTH_DIFFUSION_INT8_TRAIN=w8a8. With the variable unset, nothing changes.Change
core/training/diffusion_frozen_int8.py(new):FrozenInt8Linearreplaces each frozen basenn.Linear(the PEFTbase_layer).Int8MixedPrecisionTrainingConfig, which quantizes its bf16 weights again every step.torch._int_mm, with both scales applied in fp32._int_mmruns against the same int8 weight laid out column-major. There is no weight gradient, and x is not saved._int_mm's M > 16 floor (AdaLN modulation at batch 1) use the dequantized weight instead.allow_in_graph, so int8 now takes the regional compile.diffusion_dit_trainer.py, with the gate on:int8converts the host-loaded base onto the card one Linear at a time, after an_int_mmprobe. If the probe fails, training falls back to the torchao base._should_compilelets int8 compile, and the torchao int8 dequant cache stays off.int8is allowed and replaces nf4. The base lands on the card first and is then cast to the fp16 path's fp32 rest. The fp32 islands are installed before the conversion and live on each module's forward, soconvert_frozen_int8re-installs the island on every converted layer that had one. For example, Z-Image's untargetedfeed_forward.w2under an attention-only LoRA keeps running fp32 with autocast off.training_precision_preflight_errormirrors the fp16 allowance.Measurements
FLUX.2-klein-base-4B LoRA: 512 px, rank 16, lr 1e-4, 16 tarot cards to train on and 4 held out. Each arm ran in a fresh process on the same VM, on origin/main 8b7cde7 plus this branch. 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.
Colab A100 40 GB (sm80), 150 steps:
Colab T4 (sm75, fp16 path, uncompiled), 100 steps:
Tests
tests/test_diffusion_frozen_int8.py(new, CPU, 9 tests) covers:fullgraph=Trueand no graph breaks;feed_forward.w2returns fp32 under autocast and the targetedto_qreturns bf16. Against 7902f71 this test fails before the fix and passes after.test_differential.py: API_ONLY, new_api=8, head_fail=0. The related suites pass: base precision, T4 fp16 and the ROCm gate, 202 passed.Not proven here