Repository navigation
mxfp4_packed_matmul: exact gradients for grad-requiring inputs - #15060
Conversation
…g input Below sm_80 the bounded dense path decodes row chunks into one reused buffer; each chunk's F.linear saved a view of it, so backward read only the last chunk (input grad = 4x the last chunk's contribution, rel L2 1.84 vs an fp64 oracle). The tile kernel output had no grad at all, and the compiled path backpropagated into the custom op, which has no autograd formula. A grad-requiring call now goes through an autograd Function whose backward is the packed transpose matmul, the same as Mxfp4PackedLinear. Inference, no-grad and Mxfp4PackedLinear calls (grad disabled inside its Function) are unchanged.
|
@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: 4310a3da09
ℹ️ 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".
| x.requires_grad or (bias is not None and not transpose and bias.requires_grad) | ||
| ): | ||
| y = _Mxfp4PackedMatmulFunction.apply(x, packed, scale, transpose, bias) | ||
| return y if out is None else out.copy_(y) |
There was a problem hiding this comment.
Preserve the non-mutating out behavior when bias is supplied
When transpose=False, bias and out are supplied, and either x or bias requires gradients, this unconditional copy now overwrites out and returns it. Previously, _linear ignored out whenever bias was present, a contract explicitly preserved by the bounded implementations and test_bias_never_writes_out_whatever_the_memory. Consequently, merely enabling gradients can corrupt a caller's otherwise untouched buffer; if that buffer is a grad-requiring leaf, the copy also raises an in-place-operation error where the previous biased call succeeded. Return y without copying when a forward bias is present, and extend the existing buffer-preservation test to cover grad-requiring inputs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fb8b130: with grad, a used bias now returns a new tensor and leaves out untouched, the same as the no-grad path; without a bias out is still filled. Covered by test_direct_helper_with_grad_keeps_the_out_contract.
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
…#15376) Follow up to #15060. ## Problem Below sm_80 (and wherever the fused tile GEMM is turned off) `mxfp4_packed_matmul` runs a skinny forward through `_bounded_dense_matmul`: the whole 16-bit weight when it allocates, otherwise row chunks, otherwise the tile kernel. The backward of that forward is `dY @ W` (`transpose=True`), which skipped that route and always decoded the whole weight. So a forward that fits in a small headroom can OOM in its own backward. With a 14336 x 4096 fp16 weight, 128-row chunks and 64 MiB of headroom, the forward succeeds and the backward tries to allocate the 112 MiB dense weight: ``` torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 112.00 MiB ... 157.76 MiB allowed ``` ## Fix `_bounded_dense_matmul_t` is the transpose twin of `_bounded_dense_matmul`, sharing its per-GPU budget: 1. The whole weight when it allocates (one decode, one cuBLAS call, same as before). 2. Otherwise row chunks of W, each `dY[:, r0:r1] @ W[r0:r1]` summed into an fp32 accumulator (the rows are only up to `UNSLOTH_MXFP4_FUSED_MAX_ROWS`, so the accumulator is tiny). 3. Otherwise the tile kernel with `trans=True`. Under `torch.compile` it goes through a new opaque custom op `unsloth::mxfp4_bounded_dense_matmul_t`, the same way the forward does, so the allocation fallbacks run at call time. The existing `unsloth::mxfp4_bounded_dense_matmul` op is unchanged. The route only changes where the forward already used the bounded path (rows up to the fused threshold, fused tile GEMM unavailable, grouped GEMV self-checked). sm_80+ with the fused GEMM keeps decode plus cuBLAS for dX exactly as before. ## Related zoo change A cold `torch.compile(fullgraph=True)` backward through this helper also failed with `Unsupported: aten.equal.default` (and a cold forward with `An opaque object was created in the middle of the program`), because the zoo kernel self-checks ran for the first time inside the trace. That is fixed in unsloth-zoo (`dh/s7-rc-mxfp4bwd`, skip the self-checks while tracing and decide on the first eager call). The new `test_cold_compiled_direct_helper_backward` here needs that zoo change. ## Tests `tests/test_mxfp4_packed_low_memory.py`, on B200 with the sm_75 policy forced (torch 2.13): | | main | this PR | |---|---|---| | `test_t4_backward_fits_in_64mib_headroom` (new) | fails, OOM | passes | | `test_cold_compiled_direct_helper_backward` (new, fresh process) | fails | passes with the zoo fix | | whole file | 42 passed, 2 failed | 44 passed | `tests/test_mxfp4_compressed_linear.py`: 51 passed on both sides; the same 5 tests fail on both because they need Hub files that are not cached on this host. Not covered here: a real T4, torch versions other than 2.13, and an OOM fallback for dX on sm_80+ (that path still decodes the whole weight, as before). --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
mxfp4_packed_matmulreturns wrong input gradients when it is called directly with an input that requires grad. Since #14784, small inputs below sm_80 decode the weight in row chunks into one reused buffer. Each chunk'sF.linearsaves a view of that buffer, so backward only sees the last chunk.Two other paths fail outright instead:
torch.compile: backward through the newunsloth.mxfp4_bounded_dense_matmulop raises "no autograd formula was registered".The standard
Mxfp4PackedLineartraining path already goes through its own autograd Function and is not affected. No in-tree caller passes a grad-requiring input to the helper, but it is exported in__all__.Change
x(or a usedbias) requires grad,mxfp4_packed_matmulgoes through_Mxfp4PackedMatmulFunction._Mxfp4PackedLinearFunction.out=is still honoured._mxfp4_packed_matmul. The only addition is atorch.is_grad_enabled()check.Tests
New tests in
tests/test_mxfp4_packed_low_memory.py, run under the existing sm_75 fixture:fullgraph = Truebackward.test_mxfp4_packed_low_memory.py,test_mxfp4_compressed_linear.pyandtest_k3_mxfp4_stacked_experts.pyon GPU, torch 2.14.1:Not covered