Skip to content

Studio diffusion training: budgeted checkpointing and the nf4 dequant cache on ROCm too - #18825

Merged
danielhanchen merged 2 commits into
mainfrom
studio-rocm-diffusion-train-v4
Nov 22, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-rocm-diffusion-train-v4

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Diffusion LoRA training kept two speedups CUDA only: the budgeted gradient checkpointing (#18301, keeps block activations when the card has room) and the nf4 / int8 dequant cache (#18345). Both refused ROCm outright, so an AMD card checkpointed every block and dequantised every nf4 weight on every call. Neither refusal came from a measured ROCm problem: both PRs say ROCm was simply not run.

Change

  • diffusion_gc_budget.enable_budgeted_checkpointing no longer returns None on ROCm.
  • diffusion_dit_trainer._dequant_cache_wanted no longer excludes ROCm. The fp16 path still declines the cache, as before.
  • The budgets plan from free memory. They now read it through utils.hardware.trusted_mem_get_info, which caps the over-reported free memory on Windows ROCm (WDDM reports nearly the whole card free whatever is resident). Everywhere else it passes the driver's numbers through unchanged.

Kill switches are unchanged: UNSLOTH_DIFFUSION_GC_MODE=plain and UNSLOTH_DIFFUSION_DEQUANT_CACHE=0.

Measured on gfx1151 (Radeon 8060S)

FLUX.3 klein base LoRA, 512x512, 8 images, rank 16, 20 steps. Main and this change ran in the same job, plus a second main-vs-main pass for the noise floor.

OS precision main samples/s (two main runs) this change speedup max loss difference vs main main vs main loss difference peak GB main -> this
Linux, torch 2.11.0+rocm7.13.0 bf16 0.568 / 0.566 0.796 1.40x 0 (bit-identical) 0 12.05 -> 15.61
Linux nf4 0.354 / 0.352 0.596 1.69x 0 (bit-identical) 0 5.60 -> 20.85
Windows, torch 2.11.0+rocm7.14.0 (this head) bf16 0.445 / 0.469 0.627 1.34-1.41x 8.0e-4 0 12.19 -> 17.52
Windows (this head) nf4 0.353 / 0.352 0.534 1.51x 2.5e-3 0 5.60 -> 20.85

On Linux, host RAM available during training stayed between 99.9 and 109.7 GiB in every arm. On Windows, main repeats itself bit for bit, so the small loss difference there comes from this change. The first two steps are identical and the loss curve (0.73 -> 0.85 over the run) is unchanged at three decimals. Windows runs the trainer eagerly, since the boxes have no C++ compiler for torch.compile, and Linux runs it compiled. The nf4 peak rises by design: the cache holds 200 of 231 dequantised layers (7.5 GiB) and is planned from free memory.

Tests

  • test_diffusion_gc_budget.py::test_rocm_uses_the_budget_too: ROCm now gets the budget, and UNSLOTH_DIFFUSION_GC_MODE=plain still turns it off.
  • test_diffusion_gc_budget.py::test_budget_reads_trusted_free: the budget reads the trusted free memory.
  • test_diffusion_dit_fp16_t4.py::test_dequant_cache_stays_off_on_the_fp16_path: ROCm keeps the cache, and the fp16 path still declines it.
  • Against main: 2 tests fixed, 1 new-API test, 101 unchanged. Two test_diffusion_gc_budget_trainers.py tests (SDXL, H3-Image) fail identically on main and here: a diffusers / huggingface_hub version mismatch in the test environment.

Not proven here

  • Windows ran eager, since the boxes have no C++ compiler for torch.compile. The compiled ROCm path was measured on Linux only.
  • No discrete Radeon card, no multi-GPU setup, and no families other than FLUX.3 klein were run.
  • The Windows free-memory cap in the spawned trainer is in the measured head. The peaks match the earlier run without it, so on this 82 GB unified-memory card the cap did not change the plan.

… cache on ROCm too (gfx1151 klein LoRA 1.40-2.18x per step, Linux losses bit-identical)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T03:18:46.742817Z 68af83d Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 7540833911

ℹ️ 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".

…d trainer too

The trainer runs in a spawned process that never calls detect_hardware(), so IS_ROCM stays False there and
trusted_mem_get_info passed the WDDM free reading straight through to the checkpointing and dequant cache
budgets. Until detection has answered, rocm_windows_free_is_untrusted now asks the torch build already
imported (version.hip or a rocm tag). Off Windows, and after detection, the answer is unchanged.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 68af83dfcb

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 939f7df into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the studio-rocm-diffusion-train-v4 branch November 22, 2026 04:50
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant