Skip to content

NVFP4 QAT: accept fp16 autocast and non-contiguous activations - #14780

Merged
danielhanchen merged 3 commits into
mainfrom
nvfp4-qat-fp16-autocast-strided-inputs
Oct 25, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
nvfp4-qat-fp16-autocast-strided-inputs

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

qat_scheme="nvfp4" checks the layer weights at prepare time (bf16 or fp32, a GPU with FP4 tensor cores), but torchao's NVFP4 quantizer also needs contiguous bf16 / fp32 activations. In torchao 0.17 / 0.18, nvfp4_quantize has:

assert data_hp.dtype in (torch.bfloat16, torch.float), f"{data_hp.dtype} not supported"
assert data_hp.is_contiguous(), "Only support contiguous data for now"

NVFP4FakeQuantizedLinear.forward passes the input through as is (its autograd function uses custom_fwd without cast_inputs), and our _nvfp4_any_rank_forward wrapper only flattened the rank. So a model that prepared fine could still fail on its first step:

  • fp16 autocast: an earlier full-precision Linear (or SDPA) returns fp16 activations, and the next NVFP4 layer raises AssertionError: torch.float16 not supported. Through the Unsloth trainers you get here by loading in float32 and passing fp16=True on a Blackwell GPU (a bf16 model with fp16=True is already refused). Plain torch.autocast(dtype=torch.float16) loops hit it too.
  • Non-contiguous input: a slice such as x[..., :64] or x[:, ::2]. A plain nn.Linear accepts it, the NVFP4 layer raises Only support contiguous data for now. For rank 3 and up, reshape(-1, K) can still return a strided view.

Change

_nvfp4_any_rank_forward now:

  • casts fp16 activations to the weight dtype (bf16 or fp32, the only dtypes prepare admits) when autocast is on, and casts the result back to fp16, so the layer returns what an autocast Linear would. This matches the MX wrapper next to it (_mx_autocast_forward), which also normalizes autocast activations before torchao's kernel. FP4 quantization is much coarser than the fp16 to bf16 rounding, and fp16 to fp32 is exact.
  • flattens every rank to 2-D and makes it contiguous. This is a no-op for the usual contiguous activations.

fp16 inputs without autocast are not touched. A plain nn.Linear would reject them too.

Tests

New CPU tests in tests/test_qat_microscaling_schemes.py. They use a stand-in forward that enforces torchao's input asserts:

  • test_nvfp4_accepts_strided_inputs: rank-2, rank-3 and rank-4 non-contiguous inputs give the same result as the reference matmul.
  • test_nvfp4_takes_float16_autocast_activations[bf16, fp32]: Sequential(Linear(63, 64), Linear(64, 128)) under fp16 autocast. The first layer stays plain (63 is not a multiple of 16), the second is NVFP4. Forward returns fp16 and backward reaches the input and the weight.
run (B200, torch 2.11, torchao 0.18) main this branch
new tests (3) 3 failed 3 passed
real NVFP4 layer, unmocked prepare, fp16 autocast, bf16 / fp32 weights AssertionError: torch.float16 not supported forward returns fp16, backward reaches input and weight, output finite
real NVFP4 layer, x[:, ::2] input, bf16 / fp32 weights AssertionError: Only support contiguous data for now bitwise equal to the contiguous input
controls: no autocast and bf16 autocast pass pass, same dtypes
test_qat_microscaling_schemes.py, test_qat_forward_fake_quant_fallback.py, test_qat_activation_fused_lora.py - 31 passed

Not covered

  • Only B200 (sm100) with torchao 0.18 and torch 2.11. RTX 50 (sm120) and older torchao were not run.
  • No full LoRA QAT training run with fp16=True. The layer-level repro covers forward and backward only.
  • Whole-model pickling of a prepared QAT model (per-instance forward patch) is a separate issue and is not changed here.

torchao's NVFP4 quantizer asserts contiguous bfloat16 / float32
activations, so a prepared model failed under fp16 autocast (an earlier
Linear emits fp16) or on a strided input. Cast fp16 autocast inputs to
the weight dtype and back, and flatten to a contiguous 2-D tensor.
@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-22T19:09:45.842181Z ebf7b69 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 70389b4412

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

Comment thread unsloth/models/_utils.py Outdated
out = NVFP4FakeQuantizedLinear.forward(self, x2)
if x.dim() != 2:
out = out.view(*x.shape[:-1], out.shape[-1])
return out if out.dtype == out_dtype else out.to(out_dtype)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Respect the configured autocast dtype

When a float16 activation reaches this layer inside a bfloat16 autocast context, the wrapper converts the input to the weight dtype but then forces the result back to float16. A regular autocast Linear would return the configured bfloat16 dtype, so this keeps subsequent QAT layers in float16 and can change training numerics or introduce fp16 overflows. Preserve torch.get_autocast_dtype(x.device.type) rather than the original input dtype when autocast is enabled.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed. The wrapper now only changes the output dtype when it cast a float16 activation, and then returns torch.get_autocast_dtype(device) like an autocast Linear, so a float16 activation inside a bfloat16 autocast region comes back as bfloat16. Outside that case the output is left as torchao returns it, as before this PR. Added test_nvfp4_float16_activations_under_bfloat16_autocast_return_bfloat16; the float16 autocast and strided input tests still pass.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: ebf7b694d0

ℹ️ 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 added a commit that referenced this pull request Oct 22, 2026
pre-commit.ci fails `ruff-format-with-kwargs` on every open PR (#14806,
#14805, #14803, #14790, #14785, #14781, #14780, #14777, #14776, #14775,
#14774, #14773, #14772, #14770, #14769, #14768, and others): "files were
modified by this hook". pre-commit.ci runs the hooks on all files, and
20 files on main (26 by the time this lands) are not in the formatter's
output, so every PR is reformatted outside its own diff. Where
pre-commit.ci can push, its autofix commit drags those unrelated files
into the PR (for example #14790's touches `tests/test_block_compile.py`,
`tests/test_bnb_integration_compile.py` and `unsloth/models/_utils.py`).

The drift came in with PRs merged today, among them #14702, #14751,
#14759, #14784, #14786, #14787, #14788, #14791 and the FP8 block decode,
GRPO routing replay, 4-bit decode, compiled blocks and MoE LoRA target
changes.

### Change

`python scripts/run_ruff_format.py` (the hook's own entry point,
`ruff==0.6.9` as pinned in `.pre-commit-config.yaml`) applied to those
20 files, plus 6 more from #14739, #14779 and #14806, which merged while
this was open. Formatting only.

### Verification

- Every changed file parses to an identical AST before and after.
- A second run of the hook over the same files changes nothing (fixed
point), and over all tracked Python files on this branch it changes
nothing.
- `ruff check` passes on the changed files;
`tests/test_formatter_fixed_point.py` passes (16).

Open PRs pick this up on their next pre-commit.ci run after merging
main.
@danielhanchen danielhanchen self-assigned this Oct 25, 2026
@danielhanchen
danielhanchen merged commit d08356c into main Oct 25, 2026
22 of 37 checks passed
@danielhanchen
danielhanchen deleted the nvfp4-qat-fp16-autocast-strided-inputs branch October 25, 2026 09:13
danielhanchen added a commit that referenced this pull request Oct 26, 2026
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.
danielhanchen added a commit that referenced this pull request Oct 27, 2026
)

## 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.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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