Repository navigation
Studio diffusion: cache the W8A8 int8 backward's column-major weights - #18860
Merged
Merged
Conversation
…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.
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. 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". |
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.
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()indiffusion_frozen_int8.py). The fp8 base already avoids this with a budgeted cache (Fp8BackwardWeights). This PR reuses that cache for int8.Int8BackwardWeightssubclassesFp8BackwardWeights. It has the same budget, plan, lend and return handling, but it is keyed by the owningFrozenInt8Linearinstead ofdata_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 noFrozenInt8Linearowns is copied inline.unsloth_studio::frozen_int8_grad_input), like the fp8 one, so changing the budget never recompiles.gc_budget.spare_bytesas fp8 and uses the same lend/return VRAM handler. The cache is only used when the W8A8 base is active and checkpointing is budgeted.UNSLOTH_DIFFUSION_INT8_BWD_CACHE=0restores the inline copy.Fp8BackwardWeights.enabled()now reads a classENV, 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.torch.equalholds for cache vs inline copy on klein dX shapes (4608x27648x3072, 4608x3072x12288, 4096x3072x3072, 512x9216x3072, and M=8), in fp16 and bf16, both eager and compiled.Tests
tests/test_diffusion_frozen_int8_bwd_cache.py(CPU) covers:.to()keeps the owner;test_diffusion_frozen_fp8_bwd_cache.py,test_diffusion_frozen_int8.pyandtest_diffusion_gc_budget_replay.pystill pass.