Repository navigation
Studio diffusion: block swap over a frozen fp8 or int8 W8A8 base - #18869
Merged
Merged
Conversation
Swapped blocks are quantized Linear by Linear on the card (same kernels as a resident layer) and their 1-byte codes go back to host RAM as frozen parameters, which the unsloth_zoo swapper streams; the per-row scales stay resident. The swap plan is sized from the converted bytes. The fp8 backward weight cache is keyed by data_ptr, which a ring slot reuses across blocks of the same shape, so swapped fp8 layers take an uncached column-major copy. torchao weight-only int8 stays refused. UNSLOTH_DIT_BLOCK_SWAP_LOWP=0 keeps the bf16-only gate.
…cache test A swapped weight is a frozen parameter whose .data is a slot view while resident and empty when evicted. The wrong hit needs block A resident in one slot while block C reuses A's previous slot; the test now drives exactly that pattern, with and without the swapped-layer bypass.
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. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
This was referenced Nov 23, 2026
danielhanchen
added a commit
that referenced
this pull request
Nov 23, 2026
…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.
danielhanchen
added a commit
that referenced
this pull request
Nov 23, 2026
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Until now, DiT block swap in Studio diffusion LoRA training only took a bf16 base. Asking for
block_swapwithbase_precision="fp8"or int8 gave an error, so a model whose 8-bit base still does not fit the card had to train on nf4. Qwen-Image (40.9 GB in bf16, about 20 GB as int8 codes) on a 24 GB L4 is one example. This PR lets block swap stream a frozen fp8 or int8 W8A8 base.Change
The frozen fp8 and W8A8 linears keep their codes and scales as buffers. zoo's
BlockSwapstreams only frozen parameters, and_place_restmoves every buffer to the card. If only the gate were lifted, the swapped weights would quietly stay on the GPU. This change is all on the Studio side, sounsloth_zooneeds no change or release.core/training/diffusion_block_swap.py:fp8, andint8when it is the frozen W8A8 base (UNSLOTH_DIFFUSION_INT8_TRAIN=w8a8).UNSLOTH_DIT_BLOCK_SWAP_LOWP=0restores the bf16-only gate._frozen_bytesand the new_model_bytescount a target Linear as its converted size: 1-byte codes in the block, plus the fp32 per-row scale, which stays resident. So both the auto plan and the fit check use the converted bytes, not bf16.install_dit_block_swap, before anything is placed:host_lowp_weightthen moves each layer's codes (and bias) back to host RAM as annn.Parameter(requires_grad=False), which the swapper streams. The scale buffer goes to the card with the rest.core/training/diffusion_frozen_fp8.py:Fp8BackwardWeights.getis keyed byq.data_ptr(), but a swapped weight lives in a ring slot that other blocks of the same shape reuse.core/training/diffusion_dit_trainer.py:_apply_fp8_training/_apply_int8_w8a8steps are skipped, so nothing moves the host codes back.Measurements
Every arm runs in a fresh process. Z-Image runs at 512 px, rank 16 LoRA.
Bit-identity: eager,
torch.use_deterministic_algorithms(True), 3 steps, warmup 2. The loss tensor and all 476 LoRA grads are compared withtorch.equalat every step.Speed and memory: L4, compiled, 20 steps. s/step is the median of steps 6-20, two arms each, run off / 8 / 8 / off.
Read-out:
Capacity: Qwen-Image (40.9 GB bf16) on L4 (22 GiB usable, 53 GB host RAM), compiled where the base allows, 12 steps, same seed. The last three arms ran on one exclusive VM.
block_swap="auto"(this PR)block_swap="auto"Read-out:
Fallbacks and gates:
block_swap=8is refused up front with a clear message.UNSLOTH_DIT_BLOCK_SWAP_LOWP=0with fp8 + swap is refused before the load.Tests
tests/test_diffusion_block_swap_lowp.py, 12 CPU tests, covering:Other results:
test_gatingintest_diffusion_block_swap.pyno longer expects fp8 to be refused.test_differential: 13 new tests fail on main (missing names) and pass here. All other block swap, fp8 cache and int8 tests are unchanged.tests/test_diffusion_{block_swap,frozen,gc_budget,fp8_prequant,dit_}*.pygives 455 passed. The 9 red tests are red on main as well, with the same IDs:test_diffusion_dit_trainer_ltx25(4),test_diffusion_dit_trainer_qwen_image_21(3) andtest_diffusion_gc_budget_trainers(2), all failing on this host's diffusers / huggingface_hub import.test_diffusion_dit_trainer_moss_imagefails at collection for the same reason. One flow-shift sampling test failed once in the combined run, then passed on both trees alone.Not proven here