Skip to content

NVFP4 QAT: skip unrequested grads in the custom backward - #18864

Merged
danielhanchen merged 4 commits into
mainfrom
r5-c106-nvfp4-skip-dw
Nov 23, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
r5-c106-nvfp4-skip-dw

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

With qat_scheme = "nvfp4" and LoRA, every base Linear runs through the unsloth::nvfp4_qat_linear custom op. Its backward always dequantized both saved NVFP4 payloads and ran both GEMMs, grad @ W and grad.T @ x, and setup_context saved the activation payload. ctx.needs_input_grad was only checked for the bias. With LoRA the base weight is frozen, so the dW GEMM (as many FLOPs as the dX GEMM), the activation dequant and the saved activation payload were all wasted.

Change (unsloth/models/_utils.py, _nvfp4_qat_linear_op)

  • setup_context reads ctx.needs_input_grad[0] / [1] and passes need_x / need_w to the backward op.
  • The backward op dequantizes and multiplies only for the grads that were requested. An unrequested output comes back as an empty tensor, because custom op outputs cannot be None, and the autograd formula returns None for it. The fake impl branches on the same constant flags.
  • The activation payload is saved only when the weight needs a grad, and the weight payload only when the input does. The forward op and its schema are unchanged.
  • The op is renamed unsloth::nvfp4_qat_linear_v2. Inductor's FX graph cache and the AOTAutograd cache key on the op name, not on its body, so a warm cache would otherwise replay the old 13-argument backward call. unsloth/precision/engage.py (LOWP_GEMM_CUSTOM_OPS) and tests/test_precision_registry.py follow the rename.
  • The opaque custom op boundary stays in place, since Inductor still miscompiles the traced fake quantization.

Exactness (RTX PRO 6000 Blackwell, sm_120, torch 2.14.1+cu130, torchao 0.18.0, transformers 4.57.6)

Both arms ran in one process, and each arm's op was loaded from its own tree.

  • Single layer, through _nvfp4_any_rank_forward: 144 cases, all bitwise equal to main for the output and every requested grad. The cases cover 2-D and 3-D inputs; bf16 and fp32 weights; with and without bias, trainable and frozen; frozen weight + dX (LoRA), dW + dX (full fine-tuning) and dW only; autocast on and off; eager and torch.compile(fullgraph = True). Grads that were not requested stay None.
  • QAT + LoRA training step, unsloth/Qwen2.5-0.5B-Instruct, r = 16, all 7 projections, bs 8 x 1024 tokens, bf16 autocast, deterministic algorithms, math SDPA:
    • use_gradient_checkpointing = False: loss and all 336 LoRA grads are bitwise equal to main. The A/A run of main against itself is also bitwise equal.
    • use_gradient_checkpointing = "unsloth": main is not bitwise reproducible against itself here (162 of 336 LoRA grads differ, max relative diff 2.7%, loss equal). The head stays inside the same envelope: loss equal, max relative diff 2.6-2.9%.
  • Engagement, one step under the profiler: 168 backward op calls, all with a frozen weight. aten::mm calls drop by exactly 168 (1364 to 1196 without checkpointing, 1700 to 1532 with it), one dW GEMM per base Linear.

Speed and memory (same VM, interleaved arms, 4 rounds each, median of 10 steps per round)

The step is forward + backward + AdamW on the LoRA parameters, Qwen2.5-0.5B, bs 8 x 1024.

gradient checkpointing main step main A/A this PR step change main peak this PR peak change
"unsloth" 688.9 ms 688.8 ms 560.2 ms -18.7% 2778.9 MiB 2755.3 MiB -0.8%
False 453.7 ms 453.7 ms 326.8 ms -28.0% 11581.7 MiB 10523.0 MiB -9.1%

Across rounds the spread is under 0.3% for both main arms, apart from the first round with checkpointing, which was 1.7% slower (warm-up).

Single layer forward + backward, bf16 autocast. The shapes are the Qwen2.5 0.5B / 1.5B / 3B projections at M = 2048 and 8192 tokens:

  • frozen weight: 0.63x to 0.90x of main (for example 4864 -> 896 at M = 8192: 8.53 to 5.35 ms).
  • full fine-tuning (both grads requested): 0.999x to 1.002x at the larger shapes. At the smallest launch-bound shapes (about 1.2 ms per call) it is up to +1-2%, inside the A/A spread of those shapes.

Tests

tests/test_nvfp4_qat_backward_skip.py runs on CPU. It registers a CPU kernel that uses a dequantized matmul for the forward, and runs the real autograd formula and backward op. It checks:

  • the number of torch.mm and NVFP4Tensor.dequantize calls in the backward for each (need_x, need_w) pair;
  • bitwise grads against the full backward;
  • that fewer bytes are saved when a grad is skipped;
  • eager against aot_eager fullgraph compile;
  • the fake impl's output shapes.

5 of these 10 tests fail on main. tests/test_qat_microscaling_schemes.py and tests/test_precision_registry.py pass on CPU.

Strict determinism check

With torch.use_deterministic_algorithms(True), CUBLAS_WORKSPACE_CONFIG=:4096:8 and math SDPA forced around both the forward and loss.backward() (so the checkpoint recompute in backward is deterministic too), this PR is bitwise equal to its merge base on a Colab RTX PRO 6000 (torch 2.14.1, transformers 5.17.0, Qwen2.5-0.5B-Instruct, one bs 8 x 1024 batch, lora_B seeded nonzero):

mode gradient checkpointing loss LoRA grads differing, base vs base / base vs head NVFP4 backward calls (base / head) aten::mm in backward (base / head)
bf16 LoRA "unsloth" and True 12.611871719360352 0/336 / 0/336 0 / 0 960 / 960
QLoRA "unsloth" and True 12.460752487182617 0/336 / 0/336 0 / 0 960 / 960
NVFP4 QAT + LoRA "unsloth" and True 12.613188743591309 0/336 / 0/336 168 / 168 1344 / 1176

The QAT rows run the changed backward 168 times and do 168 fewer matrix multiplies with identical grads. Without the determinism controls the same comparison finds 324/336 grads differing between two runs of the same arm, so the earlier run-to-run differences under checkpointing came from FlashAttention's backward, not from this change.

Update (43a3f73): review fixes

  • When neither gradient is requested, each omitted gradient gets its own empty tensor (the eager backward used to return one tensor in both slots, which PyTorch rejects as aliased outputs).
  • The fake backward reads only the payload for each requested gradient, so FakeTensor tracing with the activation payload omitted works.
  • The op is still dispatched as unsloth::nvfp4_qat_linear_v2, but the engagement counter keeps the public key unsloth::nvfp4_qat_linear.
  • Full fine-tuning keeps the merge-base order (both dequantizations before the GEMMs) and drops the dense weight before the dW GEMM. CPU live-bytes peak inside the backward with both gradients requested: 480 / 520 / 480 MiB (base / previous head / now) at 4096x1024x4096 bf16, 480 / 536 / 480 MiB with fp32 inputs, and equal to base on the wide-output shapes. Outputs are bitwise equal across all three in every case.
  • The backward no longer materialises zero gradients for the six non-differentiable payload outputs.
  • Tests: 5 of the new tests fail on the previous head (aliasing RuntimeError, IndexError in the fake backward, KeyError on the counter key, the GEMM-before-dequant order, zero-fill ops) and pass now. The three PR test files give 90 passed, 10 skipped (FP4 GPU only).

With LoRA the base weight is frozen, yet the NVFP4 QAT custom op backward
always dequantized the saved activation and ran the dW GEMM. Pass the
requested grads into the backward op, skip the dequant + GEMM of each
unrequested grad, and do not save the activation payload when no weight
grad is needed. Bump the op name to _v2 since compile caches key on it.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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-23T02:17:53.117664Z bd1c2ca 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: d02bb2b168

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

…counter key, base dequant order

- Each omitted grad is its own empty tensor (custom op outputs must not alias), and the fake kernel reads
  a payload only for its own requested grad.
- Count the versioned op under the public key unsloth::nvfp4_qat_linear.
- Dequantize activation then weight before any GEMM and cast after, as before the skip, and drop the dense
  weight before the dW GEMM, so full fine-tuning peaks no higher than before.
- Do not materialize zero grads for the six non-differentiable payload outputs.
- Tests: fixture skips only on the torchao import and binds the CPU kernel to the op object; fresh scale
  placeholders; direct-dispatch, all-false fake, bias-only, dequant order and no-zeros cases.

[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. You're on a roll.

Reviewed commit: 43a3f73d77

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

…s, restore the CPU test kernel

torch.export archives and compile caches store the qualified op name, so the _v2 bump made
previously saved graphs fail to load. Register unsloth::nvfp4_qat_linear and its _backward
under their original schemas, forwarding to the v2 kernels with the pre-bump autograd.

LOWP_GEMM_CUSTOM_OPS lists the public counter key again; the v2 dispatch name is counted
under it, so enumerating the tuple against the counter no longer raises KeyError.

The CPU test kernel is registered from a test-owned library destroyed on fixture teardown.

[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. Hooray!

Reviewed commit: bd1c2caab0

ℹ️ 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 d49fe36 into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the r5-c106-nvfp4-skip-dw branch November 23, 2026 03:24
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`).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant