Skip to content

MXFP4 packed matmul: bound the dX decode like the forward below sm_80 - #15376

Merged
danielhanchen merged 4 commits into
mainfrom
dh/s7-rc-mxfp4bwd
Oct 27, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
dh/s7-rc-mxfp4bwd

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T17:57:12.734639Z 195f948 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

Needs unslothai/unsloth-zoo#2113 for the cold compiled backward test (the zoo self-checks are skipped while tracing there); merge that one first.

@codex review

@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: 25d5c311fb

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

weight = dequantize_mxfp4_packed(
packed[r0:r1], scale[r0:r1], dtype, out = buffer[: r1 - r0]
)
acc += torch.matmul(x2[:, r0:r1], weight)

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 Keep chunk products in FP32 before accumulating

When the bounded backward uses FP16 row chunks, torch.matmul returns an FP16 partial result before adding it to acc; the FP32 accumulator therefore cannot prevent intermediate overflow. For example, with 256 weight rows all decoding to 6, 128-row chunks, and upstream gradients of +100 for the first chunk and -100 for the second, the correct dX is zero, but the chunk products become +inf and -inf, producing NaN gradients. This can corrupt training with loss-scaled gradients even when the complete reduction is representable. Compute each chunk's product with an FP32 output before accumulating, and cast only after the complete reduction.

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 in f2e389c: each chunk's product is now computed in fp32 (acc.addmm_(x_chunk.float(), w_chunk.float())) and cast once after the full reduction. New test_chunked_dx_does_not_overflow_in_a_16bit_chunk_product uses your example (256 rows decoding to 6.0, 128-row chunks, dY = +100 then -100): the result is exactly zero and finite.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: f2e389cbda

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

Copy link
Copy Markdown
Member Author

Follow-up in 195f948: the bounded dX sized each chunk by its 16-bit decode only, but each chunk also makes the fp32 copy the fp32 chunk product reads, so a chunk used about 3x its budget and the path leaned on out-of-memory retries (3 on a T4 instead of 1). Each chunk row now counts its decode plus the fp32 copy (row_bytes + K * 4). New test_chunked_dx_stays_inside_its_own_budget (CUDA) fails on the previous head (first chunk attempt OOMs, 48 MiB peak against a 32 MiB budget) and passes now; the overflow test's budget is updated so it still runs two chunks instead of falling back to the tile kernel. test_mxfp4_packed_low_memory.py + test_mxfp4_compressed_linear.py: 102 passed on B200 with unsloth-zoo#2113 (merged).

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 195f948483

ℹ️ 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 feef4b7 into main Oct 27, 2026
34 of 38 checks passed
@danielhanchen
danielhanchen deleted the dh/s7-rc-mxfp4bwd branch October 27, 2026 05:34
danielhanchen added a commit that referenced this pull request Oct 27, 2026
… device (#15516)

`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`
fails on main (`Repo tests (CPU, studio)`, e.g. job 122034866848 on
#15505):

```
these skip guards read a probe tests/_zoo_aggressive_cuda_spoof.py patches to True process-wide ...
    test_mxfp4_packed_low_memory.py:428: torch.cuda.is_available()
```

#15376 added `test_chunked_dx_stays_inside_its_own_budget` with
`@pytest.mark.skipif(not torch.cuda.is_available(), ...)`. That probe is
the one the CUDA spoof patches to True, so the guard can un-skip on a
CPU-only runner when the test shares a session with
`tests/version_compat` or `tests/vllm_compat`. The rest of the file
already gates on `has_real_cuda()` through its module `pytestmark`; this
switches the new test's guard to the same probe. The guard test is right
and the kernel change is unaffected; only the new test's skip condition
was wrong.

Verification (local):
- `tests/python/test_accelerator_skip_guards.py`: main 1 failed, 23
passed; this branch 24 passed.
- `tests/test_mxfp4_packed_low_memory.py` on a CPU-only box: all 46
skip, including the new test.
- On a real GPU `has_real_cuda()` is True, so the test still runs where
it is meant to.
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