Repository navigation
NVFP4 QAT: skip unrequested grads in the custom backward - #18864
Conversation
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.
|
@codex review |
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. |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
…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]
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…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]
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…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`).
With
qat_scheme = "nvfp4"and LoRA, every base Linear runs through theunsloth::nvfp4_qat_linearcustom op. Its backward always dequantized both saved NVFP4 payloads and ran both GEMMs,grad @ Wandgrad.T @ x, andsetup_contextsaved the activation payload.ctx.needs_input_gradwas 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_contextreadsctx.needs_input_grad[0]/[1]and passesneed_x/need_wto the backward op.None, and the autograd formula returnsNonefor it. The fake impl branches on the same constant flags.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) andtests/test_precision_registry.pyfollow the rename.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.
_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 andtorch.compile(fullgraph = True). Grads that were not requested stayNone.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%.aten::mmcalls 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.
"unsloth"FalseAcross 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:
Tests
tests/test_nvfp4_qat_backward_skip.pyruns 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:torch.mmandNVFP4Tensor.dequantizecalls in the backward for each(need_x, need_w)pair;aot_eagerfullgraph compile;5 of these 10 tests fail on main.
tests/test_qat_microscaling_schemes.pyandtests/test_precision_registry.pypass on CPU.Strict determinism check
With
torch.use_deterministic_algorithms(True),CUBLAS_WORKSPACE_CONFIG=:4096:8and math SDPA forced around both the forward andloss.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_Bseeded nonzero):aten::mmin backward (base / head)"unsloth"andTrue"unsloth"andTrue"unsloth"andTrueThe 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
unsloth::nvfp4_qat_linear_v2, but the engagement counter keeps the public keyunsloth::nvfp4_qat_linear.