Skip to content

MXFP4 packed Linear: bound the below-sm_80 weight decode by free memory - #14784

Merged
danielhanchen merged 2 commits into
mainfrom
mxfp4-t4-memory-fallback
Oct 22, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
mxfp4-t4-memory-fallback

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

MXFP4 packed Linear: bound the below-sm_80 weight decode by free memory

Since unsloth-zoo #1899 the fused MXFP4 tile GEMM is off below sm_80. A T4 forward through Mxfp4PackedLinear (compressed-tensors mxfp4-pack-quantized) with up to 64 rows therefore decodes the whole 16-bit weight and calls cuBLAS. That is about 8 to 24x faster there. But it holds the full weight: 112 MiB for a 14336 x 4096 fp16 weight, where the tile kernel needed 28 KiB. With less free memory than one dequantized weight, the forward now runs out of memory.

Change

Below sm_80, when the tile kernel passed its self-check but is arch-gated (mxfp4_grouped_gemv_available and not mxfp4_gemm_available), mxfp4_packed_matmul now:

  1. Allocates the whole 16-bit weight first, decodes into it and makes one cuBLAS call. This is the current behaviour, same kernels and same output.
  2. If that allocation fails, it decodes row chunks of the packed [out, in / 2] weight into one reused buffer and writes y[..., r0:r1]. Each output column comes from one chunk, so nothing is summed across chunks. The chunk size is half of what the allocator can still hand out: driver free memory, capped by set_per_process_memory_fraction, plus cached free blocks. It is measured once after the failed allocation and kept per GPU, and the whole weight is retried after 1024 calls.
  3. If not even 128 rows fit, it runs the tile kernel, which needs only its output.

The memory queries cost about 100 us, so they run only after an allocation has failed. A forward that fits pays nothing extra. Under torch.compile this path is a custom op (unsloth::mxfp4_bounded_dense_matmul, with a fake impl). The allocation fallbacks therefore run at call time instead of being traced once, with no new graph break. sm_80+ and ROCm (tile kernel), dX, and inputs over 64 rows are unchanged. With an older unsloth-zoo that has no sm_80 floor, the new branch is never reached.

Validation

New tests/test_mxfp4_packed_low_memory.py. The sm_75 policy is applied on any GPU, kernels are real, and the allocator is capped to allocated + N MiB.

test main this PR
test_t4_decode_fits_in_64mib_headroom (1 fp16 row x 14336 x 4096) OOM (112 MiB) pass, peak under 64 MiB, no second OOM
test_compiled_forward_is_bounded_without_graph_breaks (fullgraph=True, then 64 MiB headroom) OOM pass, 0 graph breaks
test_row_chunks_match_the_single_shot_decode (24 cases: fp16 / bf16, 1 / 7 / 64 rows, bias, 2D / 3D, out=) pass (no chunking) pass, within 1 ulp of the single-shot output
test_weight_that_fits_keeps_the_single_shot_decode pass pass, bitwise equal
test_no_room_for_a_chunk_takes_the_tile_kernel, test_budget_is_retried_after_a_while fail (no fallback) pass

Existing tests (tests/test_mxfp4_compressed_linear.py, tests/test_k3_mxfp4_stacked_experts.py and the new file), main vs this PR on the same host:

  • torch 2.14.1 / transformers 4.57.6: main 4 failed (the 4 flips above), 93 passed, 13 skipped. This PR: 97 passed, 13 skipped.
  • torch 2.10.0 / transformers 5.17.0: main 5 failed (the 4 flips, plus test_zoo_kernel_and_torch_path_agree), 84 passed, 22 skipped. This PR: 1 failed (the same test_zoo_kernel_and_torch_path_agree, which fails on main too), 88 passed, 22 skipped.

Graph breaks, compiled Mxfp4PackedLinear forward under the sm_75 policy (1 and 8 rows, torch._dynamo.utils.counters): main 0, this PR 0. Each has one graph and the outputs equal eager.

On a real Colab T4, torch 2.10.0 and 2.14.1, fp16, mxfp4_packed_matmul. Arms are main, main with UNSLOTH_MXFP4_FUSED_GEMM=1 (the pre-#1899 tile kernel), and this PR, run in 3 fresh processes per arm in rotating order. Times are median us.

torch weight (out x in) rows main tile this PR peak extra, main / tile / this PR 64 MiB headroom, main / tile / this PR
2.10 14336 x 4096 1 1970 16466 1984 112 / 0.03 / 112 MiB OOM / pass / pass (36 MiB, 1716 us)
2.10 14336 x 4096 64 2146 48134 2158 114 / 1.8 / 114 MiB OOM / pass / pass (40 MiB, 2001 us)
2.10 4096 x 14336 1 1734 15204 1756 112 / 0.01 / 112 MiB OOM / pass / pass (36 MiB, 1664 us)
2.10 4096 x 14336 64 1875 37915 1904 113 / 0.5 / 113 MiB OOM / pass / pass (37 MiB, 2608 us)
2.14 14336 x 4096 1 1981 16037 1989 112 / 0.03 / 112 MiB OOM / pass / pass (36 MiB, 1705 us)
2.14 14336 x 4096 64 2181 51055 2182 114 / 1.8 / 114 MiB OOM / pass / pass (40 MiB, 1993 us)
2.14 4096 x 14336 1 1738 15318 1748 112 / 0.01 / 112 MiB OOM / pass / pass (36 MiB, 1663 us)
2.14 4096 x 14336 64 1905 41490 1897 113 / 0.5 / 113 MiB OOM / pass / pass (37 MiB, 3369 us)

Prefill (512 and 2048 rows) does not reach the changed code. There this PR / main is 1.00 to 1.06, inside main's own repeat spread. Outputs are identical to main on every shape. Under 64 MiB of headroom this PR stays 8 to 24x faster than the tile kernel and needs at most 40 MiB more.

Needs the matching unsloth-zoo change for the stacked experts (separate PR). This change works with the current unsloth-zoo on its own.

Not covered: ROCm and Windows (unchanged by construction: the branch requires the arch-gated CUDA path), multi-GPU device_map (the budget is kept per device index), a real compressed-tensors MXFP4 checkpoint end to end, and CUDA graph capture of the fallback (an allocation failure during capture is not handled).

Since unsloth-zoo #1899 the fused tile GEMM is off below sm_80, so a T4
forward of up to 64 rows decodes the whole 16-bit weight for cuBLAS. That is
much faster there, but needs the full weight in memory: 112 MiB for a
14336 x 4096 fp16 weight, where the tile kernel needed 28 KiB. With less
headroom than that the forward now ran out of memory.

Below sm_80 (tile kernel self-checked but arch-gated) the forward now:
- decodes the whole weight into a buffer it allocates first, then one
  cuBLAS call, exactly as before when it fits;
- else decodes row chunks of the packed [out, in / 2] weight into one
  reused buffer and writes y[..., r0:r1] (no sums across chunks), sized
  from the free memory (driver free, per-process memory fraction, allocator
  cached blocks) measured once after the failed allocation and kept per GPU
  (whole weight retried after 1024 calls);
- else, when not even 128 rows fit, runs the tile kernel, which needs only
  its output.

Under torch.compile the bounded path is a custom op
(unsloth::mxfp4_bounded_dense_matmul), so the allocation fallbacks run at
call time and the trace has no new graph break. sm_80+, ROCm, dX and inputs
over 64 rows are unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T21:03:51.834705Z 377c2b5 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: d74f2bc56a

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

Comment on lines +198 to +200
weight = _try_empty((N, K), dtype, device)
if weight is not None:
return _linear(x, dequantize_mxfp4_packed(packed, scale, dtype, out = weight), out, bias)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Retry when the complete dense operation runs out of memory

When available headroom is sufficient for the decoded (N, K) weight but insufficient for the subsequent dequantization work, output tensor, or cuBLAS workspace, _try_empty succeeds and the later OOM escapes from this return expression, so the chunk/tile fallback is never reached. This leaves a realistic narrow-memory range—especially with up to 64 output rows—where the new bounded path still fails; guard the entire dense attempt and release the weight before retrying, or reserve the other required allocations first.

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 377c2b5. Only the weight allocation was guarded, so an OOM in the decode scratch, the output or the cuBLAS workspace escaped past the fallback. The whole dense attempt is now one guarded block that drops the weight before recording the budget, and a chunk that runs out of memory halves and retries. A new test injects an OOM after the weight allocates and checks that the chunked result matches.

Comment on lines +205 to +206
if out is not None and out.dtype == dtype and out.is_contiguous() and out.numel() == M * N:
y = out.view(M, N)

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 out behavior consistent when bias is present

When callers pass both bias and a compatible out, the normal full-weight path goes through _linear and deliberately returns a new tensor without modifying out, but after an allocation failure this branch reuses and overwrites out; the compiled branch similarly copies into it. Consequently the same call has different return identity and side effects depending on memory pressure or compilation. Either exclude out reuse when bias is not None to preserve the existing dense behavior, or make the full-weight path honor out as well.

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 377c2b5. With a bias the full-weight path returns a new tensor and leaves out untouched, so the fallbacks now do the same: the chunk path only reuses out when there is no bias, and the compiled branch only copies into out in that case. A test covers the eager and compiled branches and checks that out is unchanged.

… write out with a bias

An OOM in the decode scratch, the output or the cuBLAS workspace after the
16-bit weight allocated now falls back to row chunks (and a chunk OOM halves
the chunk) instead of escaping. With a bias the fallbacks return a new tensor
and leave out untouched, matching the full-weight path.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 377c2b55db

ℹ️ 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 4077567 into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the mxfp4-t4-memory-fallback branch October 22, 2026 21:24
danielhanchen added a commit that referenced this pull request Oct 22, 2026
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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 24, 2026
…thai#15060)

`mxfp4_packed_matmul` returns wrong input gradients when it is called
directly with an input that requires grad. Since unslothai#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.

---------

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