Skip to content

Studio diffusion: cache the W8A8 int8 backward's column-major weights - #18860

Merged
danielhanchen merged 1 commit into
mainfrom
studio-int8-bwd-cache
Nov 22, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
studio-int8-bwd-cache

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

The W8A8 int8 training base (UNSLOTH_DIFFUSION_INT8_TRAIN=w8a8) copies every frozen weight to column-major on every backward call (q.t().contiguous().t() in diffusion_frozen_int8.py). The fp8 base already avoids this with a budgeted cache (Fp8BackwardWeights). This PR reuses that cache for int8.

  • Int8BackwardWeights subclasses Fp8BackwardWeights. It has the same budget, plan, lend and return handling, but it is keyed by the owning FrozenInt8Linear instead of data_ptr. An entry is only served while that module's weight is still the same tensor, storage and version it was copied from. If the weight is replaced or written in place, the module's single entry is rebuilt, so a stale copy is never served and no second entry is added. A weight that no FrozenInt8Linear owns is copied inline.
  • The lookup runs inside an opaque custom op (unsloth_studio::frozen_int8_grad_input), like the fp8 one, so changing the budget never recompiles.
  • The trainer plans this cache from the same gc_budget.spare_bytes as fp8 and uses the same lend/return VRAM handler. The cache is only used when the W8A8 base is active and checkpointing is budgeted.
  • Kill switch: UNSLOTH_DIFFUSION_INT8_BWD_CACHE=0 restores the inline copy. Fp8BackwardWeights.enabled() now reads a class ENV, and the stats keys use a class prefix. The fp8 behaviour and its keys are unchanged.

int32 accumulation is exact, so grad_x is bit-identical with or without the cache.

Results

Setup: FLUX.2 klein base 4B, 512 px, batch 1, rank 16, base_precision="int8" with W8A8, seed 0. Each arm ran in a separate process on the same VM, interleaved base/head x3, plus one head run with the kill switch. Timing is the mean over steps 11 to the end. A100 and L4 were compiled; T4 runs eager because the fp16 path does not compile.

GPU steps main s/step (3 runs, spread) this PR s/step (3 runs, spread) kill switch speedup peak alloc main / PR (GiB) cached / budget (GiB)
A100 40GB 60 0.1175 (0.9%) 0.1104 (0.5%) 0.1172 1.064x 7.93 / 11.31 3.38 / 22.16
L4 60 0.4440 (0.3%) 0.4009 (0.2%) 0.4439 1.108x 7.93 / 11.31 3.38 / 9.04
T4 40 2.2929 (0.2%) 2.0831 (0.8%) 2.2949 1.101x 10.19 / 10.94 0.76 / 0.76
  • Engagement: 94 of the 100 converted linears are cached. The other 6 run the small-row (M <= 16) dequant path. Hits are 5452 per 60-step compiled run, and 0 with the kill switch, which runs at main's speed.
  • Extra VRAM is the cached copies, and it stays inside the checkpointing spare budget. On T4 the budget limits the cache to 0.76 GiB and it still gives 10%.
  • grad_x bit-identity: on a T4 VM, torch.equal holds for cache vs inline copy on klein dX shapes (4608x27648x3072, 4608x3072x12288, 4096x3072x3072, 512x9216x3072, and M=8), in fp16 and bf16, both eager and compiled.
  • End-to-end losses cannot be compared bit for bit, because main against itself (A/A) already differs from step 1 at the 1e-3 level. The mean loss per run is the same for main and this PR to within 2e-4 on every card (A100 0.7083-0.7085 vs 0.7083-0.7084, L4 0.7080-0.7081 vs 0.7081-0.7082, T4 0.7242-0.7244 vs 0.7242-0.7243).

Tests

  • tests/test_diffusion_frozen_int8_bwd_cache.py (CPU) covers:
    • bit-identical grad_x with the cache;
    • one entry per module;
    • a replaced weight and an in-place write are never served stale;
    • .to() keeps the owner;
    • an unowned weight is copied inline;
    • the budget holds;
    • inactive and kill-switch runs match main;
    • fp8 and int8 caches stay separate;
    • a compiled budget change gives no recompile.
  • test_diffusion_frozen_fp8_bwd_cache.py, test_diffusion_frozen_int8.py and test_diffusion_gc_budget_replay.py still pass.

…in a budgeted cache

The int8 W8A8 backward copied every frozen weight to column-major on each call
(q.t().contiguous().t()). Reuse the fp8 base's budgeted Fp8BackwardWeights for it,
keyed by the owning FrozenInt8Linear instead of the storage address: an entry is
served only while that module's weight is the same tensor, storage and version it
was copied from, and a replaced weight rebuilds the module's one entry. The lookup
is an opaque custom op (unsloth_studio::frozen_int8_grad_input), so a budget change
never recompiles. int32 accumulation is exact, so grad_x is bit-identical.
UNSLOTH_DIFFUSION_INT8_BWD_CACHE=0 keeps the inline copy.
@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-22T08:37:34.807526Z 91b3d0b 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. More of your lovely PRs please.

Reviewed commit: 91b3d0be3c

ℹ️ 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 b17ab8b into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the studio-int8-bwd-cache branch November 22, 2026 09:43
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