Repository navigation
Studio diffusion training: kernel-audit fixes for fp8 Auto, fp8 layout, ROCm budgets, DDP precision, block swap - #18967
Merged
Conversation
…ing fp8 below 1.15x free VRAM The fp8 base loads the dense bf16 transformer on the host and streams it to the card, while the nf4 pick it replaced in the 0.9x-1.15x band streams shard by shard to the device. Apply the same host-RAM check the bf16 block-swap pick uses (_auto_swap_host_ram_ok, 1.3x dense + 4 GiB, unreadable counts as no) and keep nf4 when it fails. The 1.15x-1.5x band replaced int8, which already loaded host-first, so it is unchanged.
…sured families The 0.9x-1.15x and 1.15x-1.5x bands gave the frozen fp8 base to every family not explicitly denied, while the held-out loss was measured only for Z-Image, FLUX.2 klein and Wan. Gate both bands on _AUTO_FP8_MEASURED, the same way the above-1.5x band already uses _AUTO_FP8_OVER_BF16; FLUX.1, FLUX.2-dev, Krea, LTX and the other families keep their int8 / nf4 picks until they are measured.
… grad_y The fp8 codes keep the input's layout, and CUDA _scaled_mm refuses a column-major first operand. A transposed activation (a batch-1 x.reshape view) or a column-major grad_y would raise mid-training, past the load-time probe. Call .contiguous() on the flattened input and on grad_y before quantising; both are no-ops when already contiguous.
…nversion fails The swap plan counts every target Linear as 1-byte fp8 / W8A8 codes, but a layer whose conversion fails stays bf16, so it was under-counted 2x. After converting, an auto plan with failed layers is re-sized from the tensors as they are now; any extra blocks it needs are added to the first plan and their codes moved to host RAM.
…ndows ROCm cards until measured On Windows ROCm the budgets see the whole card as free (the trusted free cap is blind to other processes) and WDDM satisfies an overflow from host RAM instead of raising, so the OOM step-down never fires. The budgeted checkpointing and the dequant cache were measured only on a unified-memory gfx1151. Leave both off on a discrete (not APU) Windows ROCm card, detected via is_rocm_torch and device_is_integrated; UNSLOTH_DIFFUSION_GC_MODE=auto and UNSLOTH_DIFFUSION_DEQUANT_CACHE=1 opt in explicitly. APUs, Linux ROCm and CUDA are unchanged.
It has had no callers since the budgets stopped refusing ROCm, and it checked only torch.version.hip, not the tag-only wheels is_rocm_torch covers. The tests that patched it now run on a tagged ROCm torch instead.
…nst a float64 oracle The int8 numerics test checked only cosine similarity, which cannot see a scale error. Add a relative-L2 bound on forward and grad_x against a float64 dense layer for FrozenInt8Linear (2e-2; 0.86e-2 measured, int8 and dense row paths) and FrozenFp8Linear (6e-2; 3.7e-2 measured, where a CPU fp8 GEMM exists), plus a check that a 5% weight-scale error trips the bound while cosine stays near 1.
…se precisions after conversion agree_precision fixes one pick for every rank, but the fp8 and W8A8 conversions fall back per rank (to bf16, an nf4 reload, or torchao weight-only int8). A rank whose conversion failed then trained a different base, and the LoRA all-reduce mixed the two without any error. After the conversions every rank all_gathers one int64 code for the base it actually trains and all of them raise a clear error when the codes differ.
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. Already looking forward to the next diff. 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". |
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.
danielhanchen
added a commit
that referenced
this pull request
Nov 23, 2026
…VFP4 nested kernel, Kaggle input via env) (#19027) ## Summary Four tests are red on `main` and fail on every PR whose staging run includes them (seen on #18918, #18925 and #19000). Each was reproduced on `main` before fixing. In all four the code under test is right and the test is not. | Failing test (shard) | Introduced by | Cause | Fix | |---|---|---|---| | `test_diffusion_ddp_effective_precision.py::test_real_gloo_two_ranks[fp8,*]` (`(Python 3.13, diffusion)`) | #18967 | The verdicts are right (`SAME`, `REFUSED ...`), but gloo prints `[Gloo] Rank N is connected to 1 peer ranks ...` on the child's stdout first, and the test required the output to start with the verdict. | Read the verdict from the child's last line. | | `test_diffusion_base_precision.py::test_resolve_auto_uses_klein_variant_size` and `test_auto_sizes_flux2_klein_9b_off_its_own_weights[*]` (`(Python 3.13, diffusion)`): `'nf4' == 'fp8'` | #18967 | Near the 8-bit band (20 GB free against the 18.2 GB dense 9B), Auto's fp8 pick also checks host RAM through `_auto_swap_host_ram_ok`, because that load holds the bf16 base on the host. The tests fake the GPU but read the runner's real RAM, so a 16 GB CI runner gets `nf4` (correctly) and a large dev box gets `fp8`. | An autouse fixture pins host RAM high, like the file's existing `_not_rocm` pin, since these cases simulate GPU tiers. New `test_klein_9b_near_the_8bit_band_falls_back_to_nf4_on_a_small_host` pins the small-host fallback explicitly. | | `tests/test_nvfp4_qat_backward_skip.py::test_cpu_forward_kernel_is_restored_on_exit` (`Repo tests (CPU, rest)`): `there's already a kernel registered from python overriding nvfp4_qat_linear_v2's behavior for CPU` | #18864 | The test enters `_cpu_forward_kernel(op)` inside the module-scoped `op` fixture, which has already registered that kernel. torch 2.10 refuses a second Python registration for the same op, key and namespace, so the test fails on every run. | The `op` fixture is per test, and the restore test takes the bare op (new `raw_op` fixture), so it checks a real register-then-restore from a clean state. | | `tests/kaggle/test_fire_and_forget.py::test_every_gate_budget_covers_the_reaper_window` (`Repo tests (CPU, rest-2)`): `the collector's default age ceiling is not readable from the workflow` | #18969 | #18969 correctly moved the dispatch input out of the script into `MAX_AGE_HOURS: ${{ inputs.max_age_hours \|\| '3' }}`, and the test's regex only knew the inline form. | Read the default from either form, and when it is an env var, assert that variable is what reaches `--max-age-hours`. | Only tests change. ## Testing - The four files: all red on `main`. With this change, 98 passed / 6 skipped (the two diffusion files) and 125 passed (the NVFP4 and Kaggle files); `tests/kaggle/` as a whole: 1081 passed. - Sabotage, each guard still catches what it is for: - **gloo:** making `check_effective_precision` a no-op fails the `REFUSED` case. - **klein:** removing the host RAM gate from `_resolve_base_precision` fails the new small-host test. Forcing a 16 GB runner over the whole file fails the same 5 cases CI did, plus the new one. - **NVFP4:** keeping the test library alive instead of destroying it fails the restore test. - **Kaggle:** a workflow default of `9` fails (it no longer matches `collect.DEFAULT_MAX_AGE_HOURS`), and so does not passing `$MAX_AGE_HOURS` to `--max-age-hours` (`MAX_AGE_HOURS never reaches --max-age-hours`).
danielhanchen
added a commit
that referenced
this pull request
Nov 23, 2026
… graph release and quantize OOM (#19011) ## Summary Follow-up fixes from a recheck of the merged Studio training and memory PRs #18967, #18978 and #18980. Each commit fixes one root cause and adds a test that fails on the merge base (`02bed8883e`) and passes here. #18964 and #18983 were rechecked as well and need no change. ## Changes 1. **DDP compares the converted layer set, not only the precision label** (#18967). `check_effective_precision` gathered one precision code per rank. The fp8 and W8A8 converters keep a layer that fails to convert in bf16 and still report success, so two ranks could both report `fp8` while training different frozen bases. In a real two-process Gloo run with one rank-local constructor failure, rank 0 converted 2 of 2 layers, rank 1 converted 1 of 2, and both passed. Each rank now also sends a digest and count of its sorted `(name, format)` set from `lowp_layers_digest`, and every rank refuses when they differ. A count alone would miss equal counts at different layers. Callers that pass no `layers` keep the old one-int64 exchange. 2. **An unreadable Windows ROCm card keeps the default memory budgets** (#18967). `rocm_windows_discrete()` negated `device_is_integrated()`, which answers False when the device property cannot be read. An APU whose classification failed therefore lost budgeted checkpointing and the dequant cache, like a known discrete Radeon. The new `device_integrated_status()` returns True, False or None (unknown), and only a positive discrete reading turns the budgets off. `device_is_integrated()` behaves as before. 3. **The env oversized override releases idle CUDA graphs like the request flag** (#18978). `graph_release_fits` cleared `allow_oversized` for its un-overridden check, but `image_activation_verdict` still read `UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_GENERATE`. With the env override set, the release returned 0 without reading the pool, and the request took the oversized path even when dropping the graphs would have let it run normally. On the recorded L4 6-image case, `allow_oversized=True` released 3.3 GiB while the env override released 0. The check now ignores both overrides (`env_override=False`). 4. **Graph release credits only the pools this pipeline frees, on the card being checked** (#18978). The guard credited every live graph pool on the card and then reset only the image pipeline's handles. The whole-step pool is shared across the process. While a co-resident video pipeline still recorded into it, the reset freed nothing, and the image graphs were dropped for no gain. `releasable_pool_bytes(handles, device)` counts only whole-step pools that no other live wrapper records into, plus the block-graph pools these handles own, on the named card. A layer split's block card could also be refused because of its own idle block-graph pool, with no release, because only the primary card ran one. That card now drops the graphs and re-reads when their pool there closes the gap. `UNSLOTH_DIFFUSION_GUARD_RELEASE_GRAPHS=0` still turns both off. 5. **An OOM while quantizing a frozen layer is no longer counted as a kept layer** (#18980). `convert_frozen_int8` and `convert_frozen_fp8` caught `torch.cuda.OutOfMemoryError` (a `RuntimeError`) in their per-layer `except (RuntimeError, ValueError)`. An allocation failure inside the second layer's quantization therefore produced `[FrozenInt8Linear, Linear]` and `True`. That run recorded the same `base_int8_kernel='w8a8'` resume identity as a full conversion. The OOM now propagates. W8A8 refuses a partly converted base through the check #18980 added. fp8 had the same hole, and an exception escaping after some layers converted left them inside a base the caller recorded as bf16. The fp8 path now refuses a partial base the same way. The host-first nf4 reload (`Fp8FallbackDoesNotFit`) still runs first. Deliberate per-layer skips (alignment, a non-OOM error) are unchanged. ## Not changed - #18980: a T4 without torchao passes the W8A8 preflight, but `_resolve_base_precision` would refuse it. That function only runs on the bf16 route. The fp16 route (`fp16_amp`) sets `base_precision` directly and never calls it, so the preflight and the trainer agree. - #18980: torch 2.1 `is_autocast_enabled(device)` and torch 2.4 compiled-backward cache misses are both below the supported torch floor. The 2.4 case only affects performance, and its gradients are bit-identical. Torch 2.10 through 2.15 engage the cache. ## Testing - Flip tests: every new test fails on the merge base and passes here, and each arm imports its own tree. Behavioural probes that use no new symbols, base then head: - Two-rank Gloo, rank-local fp8 layer failure: both ranks accepted, then both ranks refused. - Unreadable Windows ROCm card: `rocm_windows_discrete()` was True (budgets off), now False. - Image reset with a video wrapper sharing the pool: 3 GiB credited, now 0. - Env oversized override, L4 6-image case: release was 0, now 3.3 GiB. - OOM inside the second W8A8 layer: returned True with a mixed base, now refused. - Changed test files on head (`test_diffusion_ddp_effective_precision`, `test_diffusion_gc_budget_rocm_windows`, `test_diffusion_guard_graph_release`, `test_diffusion_frozen_int8`, `test_diffusion_layer_split_lifecycle`): 85 passed. - 19 related training, graph and memory suites: base and head both 853 passed, 95 skipped, with the same 4 pre-existing failures (three `test_integrated_gpu_no_host_pin` source scans and `test_capture_then_replay_uses_one_graph_and_copies_statics`, which cannot import `torch_config_guard` in its subprocess). - `test_diffusion_dit_trainer`, `test_diffusion_training`, `test_rocm_windows_vram_7072` on head: 340 passed. ## Not covered - No GPU run. A real multi-GPU check (two cards, W8A8 or fp8 with one injected rank-local failure) should confirm that both ranks refuse before the first optimizer step and that a clean run trains. - A real CUDA OOM during conversion, co-resident image and video graphs on one card, and a layer split with block graphs on the second card were tested with mocks only. - The unreadable Windows ROCm property case was tested by mocking the property read. No Windows ROCm hardware was used.
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.
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
Auto fp8 below 1.15x free VRAM now checks host RAM first (Studio diffusion training: Auto trains on a frozen fp8 base on sm89+ cards #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.Below 1.5x, Auto picks fp8 only for measured families (Studio diffusion training: Auto trains on a frozen fp8 base on sm89+ cards #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_MEASUREDset gates those bands, the same way_AUTO_FP8_OVER_BF16already 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.The fp8 layer now gives
_scaled_mma row-major activation and grad_y. The fp8 codes keep the input's memory layout, and CUDA_scaled_mmrejects 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.The memory budgets stay off on discrete Windows ROCm cards (Studio diffusion training: budgeted checkpointing and the nf4 dequant cache on ROCm too #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_torchanddevice_is_integrated.UNSLOTH_DIFFUSION_GC_MODE=autoandUNSLOTH_DIFFUSION_DEQUANT_CACHE=1opt back in explicitly. APUs, Linux ROCm and CUDA are unchanged.Multi-GPU runs now check the base precision after conversion (Studio diffusion training: Auto trains on a frozen fp8 base on sm89+ cards #18770 / Studio diffusion training: opt-in frozen int8 W8A8 base (UNSLOTH_DIFFUSION_INT8_TRAIN=w8a8) #18782 with Studio: data-parallel DiT LoRA training across GPUs (num_gpus) #18771).
agree_precisionfixes 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.Block-swap plans are resized after a failed conversion (Studio diffusion: block swap over a frozen fp8 or int8 W8A8 base #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.
Removed the dead
diffusion_gc_budget._is_rocm(Studio diffusion training: budgeted checkpointing and the nf4 dequant cache on ROCm too #18825). Nothing called it, and it checked onlytorch.version.hip.The int8 / fp8 numerics tests now use an fp64 oracle (Studio diffusion training: opt-in frozen int8 W8A8 base (UNSLOTH_DIFFUSION_INT8_TRAIN=w8a8) #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:
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: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)test_diffusion_fp8_auto_stream.py::test_auto_fp8_unmeasured_families_keep_the_previous_pick(12 cells)test_diffusion_frozen_fp8_layout.py(column-major x, column-major grad_y, batch-1 transposed input, under the CUDA layout contract)test_diffusion_gc_budget_rocm_windows.py(discrete Windows ROCm off; APU, Linux ROCm and CUDA on; explicit opt-in; kill switches)test_diffusion_ddp_effective_precision.py(mocked process group on both ranks, plus a real 2-rank gloo run)test_diffusion_block_swap_lowp.py::test_auto_plan_resized_when_a_conversion_failstest_diffusion_frozen_int8.pyfp64 boundsExisting 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_bandandtest_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:
CUBLAS_STATUS_NOT_SUPPORTEDtorch.equalto contiguous for y and grad_xCUBLAS_STATUS_NOT_SUPPORTEDtorch.equalto contiguousThe forward relative error against fp64 is 3.69e-2 in both arms.
Not covered here