Skip to content

NVFP4 QAT: keep the fake-quantized linear out of compiled graphs - #14812

Merged
danielhanchen merged 7 commits into
mainfrom
fix-nvfp4-qat-compiled-grads
Oct 27, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fix-nvfp4-qat-compiled-grads

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

With full_finetuning=True, qat_scheme="nvfp4", the default compiled MLP (unsloth_compiled_module_*, Inductor, fullgraph=False, dynamic=True) runs torchao's NVFP4FakeQuantizedLinear inside Inductor. The compiled graph returns gate_proj / up_proj weight gradients about 19x too small. down_proj and attention are close, so the loss looks normal and nothing warns.

Tiny Llama (hidden 256, intermediate 512), one forward + backward, layer-0 grad norms on a B200 (torch 2.13, torchao 0.18, transformers 5.17), main 9a822f4:

run gate_proj dW up_proj dW down_proj dW
UNSLOTH_COMPILE_DISABLE=1 (eager), 2 runs 0.7209 / 0.7209 0.7720 / 0.7720 0.7444 / 0.7444
default (compiled MLP), 2 runs 0.0383 / 0.0383 0.0392 / 0.0392 0.7437 / 0.7437
default + this change 0.7189 0.7693 0.7448

It reproduces with plain torchao and no Unsloth: quantize_(mlp, QATConfig(NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel=False), step="prepare")), then torch.compile(mlp.forward) with Inductor gives about 99.8% relative error on the gate / up weight grads, while aot_eager is exact. LoRA QAT (frozen base) and qat_scheme="mxfp8" were not affected in the same runs.

Change

_nvfp4_any_rank_forward (the forward Unsloth installs on every NVFP4 QAT linear) is wrapped in torch.compiler.disable, so the NVFP4 fake-quantized matmul runs eagerly and the rest of the block stays compiled. The cost is one graph break per NVFP4 QAT linear, only when qat_scheme="nvfp4" is used.

Tests

tests/test_qat_microscaling_schemes.py:

  • test_nvfp4_qat_forward_stays_out_of_compiled_graphs (CPU): the NVFP4 QAT linear forward is a graph break under Dynamo. Fails on main, passes here.
  • test_nvfp4_qat_weight_grads_match_eager_under_compile (GPU with FP4 tensor cores): a gate / up / down MLP prepared with qat_scheme="nvfp4", compiled with Inductor, weight grads within 5% of eager. Fails on main, passes here.

Full file: main 1 failed (CPU), 2 failed (B200); this branch all passed.

Not covered: torch 2.10 to 2.12 and 2.14, other torchao releases, RTX 50 series (sm_120). The fp16 autocast assertion in the same forward is handled separately in #14780.

Inductor-compiled MLPs (torch 2.13, torchao 0.18) shrink the gate / up
weight gradients of NVFP4FakeQuantizedLinear about 19x in full finetuning.
Run the NVFP4 QAT forward eagerly.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T14:40:05.669230Z 8909a7d 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. Keep it up!

Reviewed commit: 6cd189e565

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

Conflicts in the NVFP4 QAT forward and its tests: keep main's autocast and
contiguity handling (#14780) under this branch's decorator, and both test sets.
…sabling compile

torch.compiler.disable on the patched forward fixed the compiled weight grads but
made fullgraph=True fail (Skip calling torch.compiler.disable()d function), for
training and for one-token decode.

The bad grads come from Inductor compiling torchao's traced fake quantization:
aot_eager is exact, Inductor returns the backward's dequantized activation about
2**-126 too small, so dW collapses (~100% relative error) while dX stays right.

Wrap torchao's NVFP4 QAT forward and backward as two torch.library custom ops
with fake impls and an autograd formula. Compile keeps them whole, so fullgraph
and dynamic shapes work and the numerics are torchao's eager ones (bitwise equal
to torchao's autograd Function; compiled == eager bitwise with
emulate_precision_casts). Packed activations are saved as before. CPU and
non-default activation configs keep torchao's own forward.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

The @torch.compiler.disable on _nvfp4_any_rank_forward fixes the compiled weight grads, but it also makes every NVFP4 QAT linear a compiler boundary. With torch.compile(fullgraph=True), training and one-token decode both fail with Unsupported: Skip calling torch.compiler.disable()d function (torch 2.13 and 2.14).

I looked for the actual cause of the bad grads. A single NVFP4 QAT linear (torchao 0.18, torch 2.13, B200) already shows it:

backend out dX dW
aot_eager 0 0 0
aot_eager_decomp_partition 0 0 0
inductor 0.0038 0 0.998

The numbers are relative errors against eager. Dynamo and AOTAutograd are fine, so the problem is in Inductor. The compiled backward dequantizes the saved activation about 2**-126 too small for every normal fp4 code (the 0.5 denormal code is exact), so dW collapses and dX stays correct. torch._inductor.compiler_bisector points at the Inductor lowerings.

The latest commit on this branch wraps torchao's NVFP4 QAT forward and backward in two torch.library custom ops (unsloth::nvfp4_qat_linear and unsloth::nvfp4_qat_linear_backward). Each op has a fake impl, and the forward has an autograd formula. Inductor no longer traces the quantization, so there is no graph break. The math is torchao's eager math:

  • The forward quantizes x and W, then runs _addmm_nvfp4_dispatch. It saves the packed activation (qdata, scales, per-tensor scale), as torchao does, so activation memory does not change.
  • The backward dequantizes the saved activation, requantizes W the same way, and does both matmuls. It runs the matmuls in the forward's autocast dtype, like torchao's custom_bwd.
  • CPU inputs and non-default activation configs (swizzled or Triton activation quantizer) still use torchao's own forward.
  • The branch also merges main, keeping the autocast and contiguity handling from NVFP4 QAT: accept fp16 autocast and non-contiguous activations #14780.

Tests on B200, torch 2.13.0, torchao 0.18.0 (tests/test_qat_microscaling_schemes.py, -k nvfp4_qat):

main this branch before this branch now
custom op vs torchao eager, bitwise, plus opcheck n/a n/a pass
MLP grads, compiled vs eager, default and fullgraph=True 0.998 rel err on gate/up fullgraph fails (Unsupported) pass (bitwise)
default Inductor, fullgraph=True, rel err < 0.05 0.998 fails (Unsupported) pass
fullgraph=True, dynamic=True, mark_dynamic batches 2/3/4/7, one graph fails fails (Unsupported) pass
one-token no-grad decode, fullgraph=True, bitwise not equal fails (Unsupported) pass
bf16 autocast with bf16 or fp32 weights, eager and fullgraph vs torchao not equal fails (Unsupported) pass
CPU: patched forward has 0 graph breaks pass fails pass

The bitwise checks set torch._inductor.config.emulate_precision_casts = True. Without it, Inductor keeps silu(gate) * up in fp32 before the bf16 round. That moves a few fp4 codes of down_proj's input, which shows up as about a 2% grad difference. With it, compiled and eager match bitwise. All 110 tests in the tests/test_*qat*.py files pass.

Not covered: torch 2.14 with this change (the bug itself reproduces there), torchao versions other than 0.18, GPUs other than B200 (no sm120 run), and long training runs.

Fixed in 37cb689.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 37cb689f39

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

…tizing it again, return the input dtype

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up in 8909a7d:

  • The backward op no longer quantizes the full weight again every step. The forward returns the weight's NVFP4 codes, block scales and per-tensor scale, and the backward dequantizes those. A 4096x4096 forward plus backward on B200 went from 3676 us back to the merge base's 2873 to 2930 us (shared card, indicative only). Eager and compiled results stay bitwise equal to torchao.
  • The forward casts its output to the input's dtype. On torchao 0.15 a float32 bias otherwise gave a NaN compiled bias grad, because the op's declared output dtype was bf16.

tests/test_qat_microscaling_schemes.py: 39 passed on B200 (torchao 0.18, torch 2.13, fresh compile cache). A correction to my previous comment: the tests/test_*qat*.py run was 106 passed and 4 deselected, not 110 passed.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 8909a7d731

ℹ️ 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 self-assigned this Oct 27, 2026
@danielhanchen
danielhanchen merged commit fda27b8 into main Oct 27, 2026
@danielhanchen
danielhanchen deleted the fix-nvfp4-qat-compiled-grads branch October 27, 2026 12:52
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