Skip to content

mxfp4_packed_matmul: exact gradients for grad-requiring inputs - #15060

Merged
danielhanchen merged 3 commits into
mainfrom
fix/mxfp4-packed-matmul-autograd
Oct 24, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fix/mxfp4-packed-matmul-autograd

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

mxfp4_packed_matmul returns 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's F.linear saves a view of that buffer, so backward only sees the last chunk.

Two other paths fail outright instead:

  • Tile kernel: the zoo kernel has no autograd, so its output carries no grad at all.
  • Under torch.compile: backward through the new unsloth.mxfp4_bounded_dense_matmul op raises "no autograd formula was registered".

The standard Mxfp4PackedLinear training 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

  • New Function: when grad is enabled and x (or a used bias) requires grad, mxfp4_packed_matmul goes through _Mxfp4PackedMatmulFunction.
    • Its backward is the packed transpose matmul, the same math as _Mxfp4PackedLinearFunction.
    • out= is still honoured.
  • Every other call is unchanged: inference, decode, and the calls made inside the existing Functions run the same body as before, now _mxfp4_packed_matmul. The only addition is a torch.is_grad_enabled() check.

Tests

New tests in tests/test_mxfp4_packed_low_memory.py, run under the existing sm_75 fixture:

  • Paths covered: helper backward on the chunk, tile and single-shot paths, with and without bias; the transpose backward; and a compiled fullgraph = True backward.
  • Reference: each is checked against an fp64 oracle.
  • Size of the bug on main: the chunked input gradient has relative L2 error 1.8.

test_mxfp4_packed_low_memory.py, test_mxfp4_compressed_linear.py and test_k3_mxfp4_stacked_experts.py on GPU, torch 2.14.1:

main this PR
5 failed, 103 passed, 13 skipped 108 passed, 13 skipped
  • Failing on main: the chunk and tile cases with and without bias, plus the compiled backward.
  • torch 2.10: the same new tests fail on main and pass here. Two other tests fail on both sides in that environment, so they are not caused by this change.

Not covered

  • Real hardware: sm_75 was emulated by the existing fixture rather than run on a T4.

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T01:43:39.272938Z fb8b130 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: 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)

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 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 👍 / 👎.

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.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: fb8b1305d3

ℹ️ 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 merged commit b60f1a1 into main Oct 24, 2026
4 of 29 checks passed
@danielhanchen
danielhanchen deleted the fix/mxfp4-packed-matmul-autograd branch October 24, 2026 01:48
danielhanchen added a commit that referenced this pull request Oct 27, 2026
…#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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant