Repository navigation
MXFP4 packed Linear: bound the below-sm_80 weight decode by free memory - #14784
Conversation
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.
|
@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: 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if out is not None and out.dtype == dtype and out.is_contiguous() and out.numel() == M * N: | ||
| y = out.view(M, N) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
@codex review |
|
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". |
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.
…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>
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-tensorsmxfp4-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_availableand notmxfp4_gemm_available),mxfp4_packed_matmulnow:[out, in / 2]weight into one reused buffer and writesy[..., 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 byset_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.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.compilethis 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_t4_decode_fits_in_64mib_headroom(1 fp16 row x 14336 x 4096)test_compiled_forward_is_bounded_without_graph_breaks(fullgraph=True, then 64 MiB headroom)test_row_chunks_match_the_single_shot_decode(24 cases: fp16 / bf16, 1 / 7 / 64 rows, bias, 2D / 3D,out=)test_weight_that_fits_keeps_the_single_shot_decodetest_no_room_for_a_chunk_takes_the_tile_kernel,test_budget_is_retried_after_a_whileExisting tests (
tests/test_mxfp4_compressed_linear.py,tests/test_k3_mxfp4_stacked_experts.pyand the new file), main vs this PR on the same host:test_zoo_kernel_and_torch_path_agree), 84 passed, 22 skipped. This PR: 1 failed (the sametest_zoo_kernel_and_torch_path_agree, which fails on main too), 88 passed, 22 skipped.Graph breaks, compiled
Mxfp4PackedLinearforward 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 withUNSLOTH_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.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).