Repository navigation
NVFP4 QAT: accept fp16 autocast and non-contiguous activations - #14780
Conversation
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.
|
@codex review |
Codex Review SummaryThis 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. |
There was a problem hiding this comment.
💡 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
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.
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.
) ## 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>
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_quantizehas:NVFP4FakeQuantizedLinear.forwardpasses the input through as is (its autograd function usescustom_fwdwithoutcast_inputs), and our_nvfp4_any_rank_forwardwrapper only flattened the rank. So a model that prepared fine could still fail on its first step:AssertionError: torch.float16 not supported. Through the Unsloth trainers you get here by loading in float32 and passingfp16=Trueon a Blackwell GPU (a bf16 model withfp16=Trueis already refused). Plaintorch.autocast(dtype=torch.float16)loops hit it too.x[..., :64]orx[:, ::2]. A plainnn.Linearaccepts it, the NVFP4 layer raisesOnly support contiguous data for now. For rank 3 and up,reshape(-1, K)can still return a strided view.Change
_nvfp4_any_rank_forwardnow:_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.fp16 inputs without autocast are not touched. A plain
nn.Linearwould 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.AssertionError: torch.float16 not supportedx[:, ::2]input, bf16 / fp32 weightsAssertionError: Only support contiguous data for nowtest_qat_microscaling_schemes.py,test_qat_forward_fake_quant_fallback.py,test_qat_activation_fused_lora.pyNot covered
fp16=True. The layer-level repro covers forward and backward only.