Repository navigation
Decode small 4bit batches with the NF4 GEMV instead of dequantizing every token - #13642
Conversation
…very token Batched decode (q_len 1, 2+ rows) of a bitsandbytes 4bit model fell off the GEMV path and dequantized every weight to 16bit on every token, so batch 2 decoded slower in total than batch 1 (Llama-3.3-70B on RTX PRO 6000: 8.4 tok/s at batch 2 vs 19.8 at batch 1). The NF4 GEMV kernels now take M activation rows, one program per (row, weight tile), each row bit-identical to the batch-1 kernel. fast_linear_forward sends 2 to 4 decode rows to it where it times at least 10% faster than dequantize + matmul on the GPU, decided once per weight shape and row count, with a planned relaunch afterwards. Fixes #2798
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. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d9da858a2c
ℹ️ 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".
| if win is not None or _is_compiling() or torch.cuda.is_current_stream_capturing(): | ||
| return bool(win) |
There was a problem hiding this comment.
Preserve the row GEMV on cold compiled calls
When the first invocation for a shape occurs under torch.compile, the cache has no entry, so this condition returns False and tracing permanently selects the dequantize-plus-matmul branch. Thus compiled small-batch decoding still dequantizes every weight each token unless an eager call happened to benchmark the same shape first; the compile test masks this by explicitly running fn(X) before compiling it. A compile-first production flow therefore misses the optimization introduced by this change.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not a correctness issue: a compile-first call for a new shape keeps the existing dequantize path, exactly what main does today, and Unsloth's decode loop runs eager, so the first eager step records the choice for later compiled calls.
| key = (X.device.index, int(shape[0]), int(shape[1]), X.dtype, X.shape[0]) | ||
| win = _GEMV_ROWS_WINS.get(key) |
There was a problem hiding this comment.
Specialize the row count before using it as a cache key
With torch.compile(dynamic=True), X.shape[0] can remain a symbolic SymInt, but this tuple is immediately used in a Python dictionary lookup. Hashing such a symbolic value can cause a graph break (and an error under fullgraph=True) before the later _is_compiling() fallback is reached; the other symbolic dimensions in this key are explicitly converted to int, but the row count is not. Specialize the row count as well so dynamically compiled small-batch forwards remain traceable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Could not reproduce: torch.compile(fullgraph=True, dynamic=True) over fast_linear_forward traces with no error at batch 2 and 3, both after an eager call (cache hit, output bit-identical to eager) and cold (no entry, dequantize path), on torch 2.13; Dynamo specializes the row count here.
|
Codex Review: Didn't find any major issues. Bravo. 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". |
…o decode is reproducible
Rows above the cap (A100 batch 4) still unpacked the quant state and could copy a strided X before the cap sent them to dequantize, costing A100 batch-4 decode about 10% against main. The cap is now the first check, so those rows pay one dict lookup.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 843757691c
ℹ️ 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".
| and out.dtype is X.dtype | ||
| and out.data_ptr() & 15 == 0 | ||
| and out.stride(0) == plan[4] |
There was a problem hiding this comment.
Validate the output element stride before reusing a plan
When a fast-launch plan has been cached, a later call with an aligned output having the same row stride but out.stride(-1) != 1 satisfies this predicate and bypasses the fallback validation below. The planned kernel always stores OUT + rows as contiguous elements, so a valid non-contiguous view—such as an every-other-element view backed by rows with the same wide stride as the original output—receives incorrect values. Include the innermost stride in the reuse predicate so these outputs reach the dequantize/matmul path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e2186b0: the planned relaunch now also requires out.stride(-1) == 1, so a strided out falls through to the checks below and dequantizes. Added test_planned_rows_skip_a_strided_out, which fails without the check.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e2186b08df
ℹ️ 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".
| plan = False, | ||
| ): | ||
| nested = code2 is not None | ||
| M = out.shape[0] |
There was a problem hiding this comment.
Derive the row count from the activation
When an explicit output is a capacity buffer or otherwise has a larger leading dimension than X, this sets M from the output and launches that many row programs. For example, batch-1 gemv_nf4(X, ..., out=buffer_for_four_rows) makes rows 1–3 read beyond X via (pid % M) * K, potentially producing a CUDA illegal-memory-access instead of writing the single activation row. Derive M from X.shape[0] and validate or slice the output to the expected (M, 1, N) shape.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5ecc3a7: _launch now takes the row count from X (X.numel() // K), so an out with spare rows only gets X's rows written. test_one_row_into_a_taller_out_writes_only_that_row covers it.
| plan | ||
| and out is not None |
There was a problem hiding this comment.
Reuse plans when no output buffer is supplied
When callers omit out, this condition always rejects an existing plan, even though the code immediately allocates a correctly shaped output and creates another plan below. Decode paths such as fast_geglu_inference call the gate and up projections without output buffers, so every token rebuilds the launch arguments and replaces an unused plan for two projections per layer rather than taking the intended low-overhead relaunch path. Allocate the result buffer before this check and validate it against the cached plan as the batch-1 path does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5ecc3a7: the rows plan now records N, and with out = None it allocates (M, 1, N) and relaunches when the plan was made for an unstrided out. test_planned_rows_are_reused_without_an_out checks the second call does not replan.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5ecc3a79d8
ℹ️ 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".
| if out is not None and (out.dtype != X.dtype or out.stride(-1) != 1): | ||
| return None |
There was a problem hiding this comment.
Reject undersized multi-row output buffers
When an explicit out has the correct dtype and unit inner stride but fewer than shape[0] elements per row, this check accepts it and the Triton kernel still stores all N = shape[0] outputs at each out.stride(0) offset. For example, out=torch.empty((M, 1, N - 1), ...) causes adjacent rows to overlap and the final row to write beyond the allocation, potentially producing incorrect output or a CUDA illegal-memory-access instead of the prior matmul path's output-shape handling. Validate that every row has capacity for N elements, including in the cached-plan predicate, before launching.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a01b484: both the planned relaunch and the first launch now require out to have M rows, shape[-1] == N and a row stride of at least N, otherwise the rows go to dequantize + matmul. test_rows_gemv_rejects_an_out_it_cannot_fill covers a short row, too few rows and overlapping rows.
| elif ( | ||
| bsz <= _GEMV_MAX_ROWS |
There was a problem hiding this comment.
Keep empty batches on the matmul path
For an input shaped (0, 1, K), the preceding batch-1 branch is skipped but 0 <= _GEMV_MAX_ROWS selects this branch. _gemv_rows then reaches _launch with M == 0, which constructs a zero-sized Triton launch grid (and the kernel's row mapping contains % M) rather than returning the valid empty result that the previous dequantize-plus-matmul path produced. Require bsz >= 2 before selecting the multi-row GEMV.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a01b484: fast_linear_forward requires 2 <= bsz, and _gemv_rows returns None outside 2..cap, so an empty batch keeps the matmul path. test_empty_decode_batch_keeps_the_matmul_path asserts the rows GEMV is not entered.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5ecc3a79d8
ℹ️ 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".
| out.dtype is X.dtype | ||
| and out.data_ptr() & 15 == 0 | ||
| and out.stride(0) == plan[4] | ||
| and out.stride(-1) == 1 |
There was a problem hiding this comment.
Reject output buffers on a different device
When out has the expected dtype and strides but resides on the CPU or another GPU, both this planned-relaunch predicate and the first-launch validation below accept it. The Triton kernel is launched on X.device and receives the foreign allocation's pointer, which can cause an illegal memory access or an unintended peer-device write instead of the device-mismatch error produced by the previous matmul path; require out.device == X.device in both checks.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5c486c3: both the planned relaunch and the first launch now require out.device == X.device, otherwise the rows dequantize. Covered in test_rows_gemv_rejects_an_out_it_cannot_fill (CPU out).
|
|
||
| def _gemv_rows(X, W, quant_state, out): | ||
| """One gemv_nf4_rows launch for 2.._GEMV_MAX_ROWS decode rows (#2798); None = dequantize.""" | ||
| M = X.shape[0] |
There was a problem hiding this comment.
Validate the activation width before launching
When a small-batch caller supplies an activation whose last dimension differs from the quantized weight's K, this still uses X.shape[0] as the plan key while _launch derives its row count with X.numel() // K and advances rows by exactly K. For example, an (2, 1, K - 1) input launches only one row and returns an output whose second row was never initialized, whereas the previous matmul path raised a dimension-mismatch error; reject the row kernel unless X.shape[-1] == shape[1] before consulting a cached plan.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5c486c3: the first launch requires X.numel() == M * K, and the plan records K so a relaunch requires the same; a 4095 / 4097 wide activation now dequantizes. Covered in test_rows_gemv_rejects_an_out_it_cannot_fill.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5c486c38a3
ℹ️ 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".
| or out.shape[0] != M | ||
| or out.shape[-1] != shape[0] | ||
| or out.stride(0) < shape[0] |
There was a problem hiding this comment.
Require the singleton output dimension
When an explicit buffer has shape (M, 0, N) or (M, 2, N), these checks still pass because only the first and last dimensions are validated and a contiguous buffer has unit inner stride and row stride at least N. The kernel nevertheless writes exactly one contiguous N-element slice per row; the former case can write through a zero-sized allocation and trigger an illegal CUDA access, while the latter returns a partially unwritten tensor of the wrong shape. Fresh evidence beyond the earlier undersized-buffer fix is that the unchecked middle dimension permits these buffers despite the new row and width checks; require the expected (M, 1, N) shape in both initial and cached-plan validation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 261f184: both the planned relaunch and the first launch now require out.shape == (M, 1, N), so (M, 0, N) and (M, 2, N) buffers dequantize. Added both to test_rows_gemv_rejects_an_out_it_cannot_fill. Every in-tree caller passes a (bsz, 1, N) buffer.
| 2 <= bsz <= _GEMV_MAX_ROWS | ||
| and _USE_NF4_KERNELS | ||
| and _TRITON_GEMV_EAGER | ||
| and _quant_state_dtype(W_quant) != torch_float32 |
There was a problem hiding this comment.
Let the row override bypass the eager-policy gate
When UNSLOTH_GEMV_MAX_ROWS is explicitly set on ROCm with Triton older than 3.7, triton_gemv_eager() makes _TRITON_GEMV_EAGER false, so this predicate rejects every batched GEMV before _gemv_rows_cap() can apply the documented per-GPU override. The kernels remain available in this configuration—the false value is only the default performance policy—so users cannot force the row path as the new override promises, and compiled calls are blocked as well. Treat an explicit override as sufficient to enter _gemv_rows, while retaining this gate for default selection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Intended: the rows GEMV sits behind the same eager Triton GEMV policy as the batch-1 GEMV, so ROCm with Triton < 3.7 keeps bitsandbytes / dequantize for both, and compiled calls keep today's path as before this PR. UNSLOTH_GEMV_MAX_ROWS only sets the row cap where that GEMV runs. Reworded the comment and the PR description in 261f184 to say so.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 261f1849d1
ℹ️ 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".
| if ( | ||
| shape[1] % blocksize != 0 | ||
| or X.dtype not in (torch.float16, torch.bfloat16) | ||
| or X.numel() != M * shape[1] | ||
| ): |
There was a problem hiding this comment.
Reject weights and quant state on another GPU
For a supported 2–4-row call where X is on a different GPU from W or its quantization tensors, these checks pass and gemv_nf4_rows launches the raw Triton kernel on X.device with foreign-device pointers. Without peer access this can cause an illegal memory access, while the previous dequantize-plus-matmul path reported a device mismatch. Validate that W, absmax, code, and the optional nested-state tensors are on X.device before either reusing a plan or launching.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8ac6ca6: _gemv_rows returns None up front when W is not on X.device (so a plan is never reused across devices), and the first launch also requires absmax, code and the nested state on X.device. test_rows_gemv_needs_the_weight_on_the_activation_device asserts no launch is attempted in either case.
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
…ers (unslothai#13829) Follow-up to unslothai#13642. ## Change `unsloth/kernels/nf4_gemv.py`, bytes kernel only (the default on Triton 3.7+, and for weights that are not word aligned): - `EVEN_K` constexpr, set on the host as `K % BLOCK_K == 0`: drops the K masks on the weight, X and absmax loads. Every Llama-sized K takes it. - The NF4 table is read through `nf4._nf4_lut` with mode 2 (a register `tl.gather` of the 16 entries) when `tl.gather` is available (Triton 3.6+), else mode 0 (the same L1 table load as before). The table still comes from the quant state's `code` pointer, so FP4 states stay correct. The words kernel (Triton below 3.7) is unchanged. ## Why not constexpr N / K / M / OUT_STRIDE, or literal NF4 constants Both were measured first (CUDA graph replay, 5 Llama shapes x 1 / 2 / 4 rows, weights cycled past L2): - Constexpr K + M compiles 8 to 12 kernel variants per model instead of 2 to 4 (about +1.8 s first call on a T4), is mixed on the words kernel (A100 -13.7%, T4 +2.7%), slower on the bytes kernel (+13% to +26%), and not bitwise on the bytes kernel. All four constexpr compiles 35 variants. - Hard-coding the 16 NF4 values as literals (a select tree on constants) is 64% to 172% slower than a table load. ## Performance Public `gemv_nf4` / `gemv_nf4_rows` API, Colab, Triton 3.7.1, fresh process per arm, interleaved base / head / head / base, Llama 8B shapes (4096 x 4096, 1024 x 4096, 14336 x 4096, 4096 x 14336, 128256 x 4096) at 1, 2 and 4 rows: | GPU | geomean vs main | range over cases | |---|---|---| | A100 | -22.4% | -8.9% to -31.0% | | L4 | -18.7% | -1.1% to -26.3% | | T4 | -25.6% | -22.3% to -31.8% | Every case was faster; the A/A spread was under 0.5% on A100 and up to 4% on L4 / T4. Kernel-only sweep: `EVEN_K` alone is -7.8% to -23.9%, the register gather adds the rest except on T4. ## Correctness - Bitwise identical to main for 84 cases (7 shapes including K = 11008 and K = 192, nested and plain absmax, bf16 and fp16, 1 / 2 / 4 rows) on torch 2.14 / Triton 3.8 and on torch 2.7.1 / Triton 3.3 (where the table load path is kept). - `tests/test_nf4_triton_gemv.py` + `tests/test_bnb_integration_compile.py`: 251 passed on both stacks (with `-o addopts=""`). Not measured: H100, RTX PRO 6000 and B200 timing. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Fixes #2798
Problem
Batched generation with a bitsandbytes 4bit model (
FastLanguageModel.for_inference+model.generatewith 2 or more prompts) decodes slower in total than generating one prompt at a time. Batch 1 decode goes through the fused NF4 GEMV, but any batch of 2+ rows infast_linear_forwardfalls tofast_dequantize+ matmul, which writes and rereads every weight in 16bit on every token. On bandwidth-limited GPUs that costs 4.8x a batch-1 GEMV per linear on A100, 6.6x on L4 and 11x on T4.Llama-3.3-70B 4bit + LoRA r=64 on an RTX PRO 6000, main:
so batch 2 decodes 2.4x slower in total than batch 1, matching the report.
Change
unsloth/kernels/nf4_gemv.py: the two NF4 GEMV kernels takeMactivation rows. One program per (row, weight tile), the rows of a tile launched next to each other; each row's sums are the batch-1 kernel's, so every row is bit-identical to running it alone.M == 1is specialized away by Triton (and the launch cache), so batch-1 decode is unchanged. Addsgemv_nf4_rows, its planned relaunch, and anunsloth::gemv_nf4_rowstriton_op for compiled code.unsloth/kernels/utils.py:fast_linear_forwardsends decode batches of 2 up to a per-GPU row cap togemv_nf4_rows. The cap is fixed per compute capability from end-to-end decode A/Bs: T4 (sm75), L4 (sm89) and RTX PRO 6000 (sm120) up to 4 rows, A100 (sm80) only 2. H100, B200, ROCm and any GPU not measured keep today's dequantize path. The cap is fixed rather than timed so the same prompt always decodes to the same tokens.UNSLOTH_GEMV_MAX_ROWSoverrides the cap wherever the Triton GEMV runs eagerly, as for batch 1 (1turns the batched GEMV off). The cap is checked before anything else, so batches above it cost the dequantize path nothing. Later decode steps reuse a planned launch, like batch 1. Batches above 4 always dequantize as before.At 8 rows the GEMV still won kernel time on T4 / L4 / RTX PRO 6000 but lost 2% to 7% end to end on A100 and on an 8B model on RTX PRO 6000, so the maximum is 4.
Results
Decode tok/s summed over the batch, Llama-3.1-8B-Instruct bnb-4bit, greedy, 128 new tokens, Colab. Base = this PR's merge base, head = this PR, each arm a fresh process, interleaved head / base / head / base; both runs shown.
Generated tokens are identical between the two head runs on every GPU and batch size, and identical to base wherever both take the same path. Where the GEMV replaces dequantize + matmul (L4 batch 4) the greedy tokens can differ from base, since the sums are accumulated in a different order. Peak memory is unchanged.
Earlier runs (4bit + LoRA r=64, 200-token prompt, 256 new tokens) on an RTX PRO 6000: Llama-3.3-70B batch 2 8.36 -> 22.12 tok/s (2.6x), batch 4 18.15 -> 34.85 (1.9x); Llama-3.1-8B batch 2 76.9 -> 110.6 (+44%), batch 4 151.9 -> 174.3 (+15%); batch 1 unchanged.
Kernel time per 70B MLP linear (28672x8192), batch 2, CUDA graph replay: A100 830 -> 335 us, L4 4299 -> 1056 us, T4 13901 -> 2220 us. Batch-1 GEMV kernel time is unchanged on A100 / L4 / T4 (Triton 3.6) and B200 (Triton 3.7).
Accuracy: against an fp32 oracle (fp32 dequantize, fp32 matmul) the batched GEMV has 0.166% relative error versus 0.233% for the dequantize path it replaces (Llama-3.1-8B layers, bf16).
Tests
tests/test_nf4_triton_gemv.py: every row ofgemv_nf4_rowsequalsgemv_nf4on that row, bit for bit, across the bytes / words / narrow kernel configs, nested and flat absmax, odd shapes, into a stridedout(asfast_swiglu_inferencepasses); 2 to 4 row decode takes the GEMV and not the dequantize; 5+ rows and 0 rows still dequantize; the row cap per compute capability, the env override, and ROCm never taking it by default; rows above the cap never unpack the quant state; planned reruns match the first launch and are reused with and without anout; anoutthe GEMV cannot fill (short rows, too few rows, overlapping rows, non-unit element stride) falls back; one row into a talleroutwrites only that row; copies of the quant state drop the cache.tests/test_bnb_integration_compile.py:fast_linear_forwardcompiles fullgraph with no graph breaks and matches eager at batch 1, 2, 8 and 9.