Skip to content

T4: hand batch-4 NF4 decode to the bitsandbytes gemm_4bit where it runs - #15988

Merged
danielhanchen merged 4 commits into
mainfrom
t4-nf4-rows-cap
Oct 29, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
t4-nf4-rows-cap

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Summary

On T4, NF4 decode at batch 2 to 4 runs the Triton GEMV rows kernel (_GEMV_ROWS_BY_ARCH[(7, 5)] = 4); batch 5 to 16 already runs bitsandbytes' fused gemm_4bit. A re-measurement on Colab T4 finds the crossover is at batch 4, not 5:

  • Batch 4: bitsandbytes' gemm_4bit is 13-30% faster per decode token.
  • Batch 2: it is about 40% slower.
  • Batch 3: the two tie.

With this PR, T4 batch 4 steps out of the GEMV only when the bitsandbytes branch below it will run (_bnb_gemm_4bit_ok: inference, fp16, bitsandbytes >= 0.50, not compiling, a supported quant state). Everywhere else batch 4 keeps the GEMV exactly as before, so it never falls to dequantize + matmul:

  • Unchanged: compiled graphs, grad enabled, bf16, UNSLOTH_BNB_GEMM_4BIT=0, older bitsandbytes, list quant states, other nested blocksizes.
  • Caps: the GEMV cap table is unchanged; a new _GEMV_ROWS_BNB_FROM_BY_ARCH = {(7, 5): 4} names the handoff row. Other architectures are unaffected.
  • Setting the old behaviour back: UNSLOTH_GEMV_MAX_ROWS=4 keeps batch 4 on the GEMV, and the new test checks that.
  • Reproducibility: the choice is still fixed per architecture and call, not timed.
  • Inputs bitsandbytes' fused kernel cannot take: _bnb_gemm_4bit_ok now also declines a nested quant state with a list state2 or a non-tensor offset, and activations or weights that do not start on a 16-byte boundary. These crashed gemm_4bit (AttributeError, an Optional[Tensor] type error, CUDA error: misaligned address); batch 4 now keeps the GEMV for them, and batch 5 to 16 dequantizes as it does elsewhere.

Results

Real unsloth/Qwen3-4B-unsloth-bnb-4bit and unsloth/Llama-3.2-3B-Instruct-bnb-4bit, Colab T4 fp16, eager decode.

  • Timing setup: each value is ms per token, the median of 3 repeats, all arms in fresh processes on one VM.
  • Arms: A is the shipped GEMV rows path; B is the bitsandbytes branch.
  • Path check: calls per token confirmed which path each arm took.
model batch A (shipped) B (bitsandbytes) B vs A
Qwen3-4B 2 46.4 / 50.5 / 50.0 62.7 / 61.3 22-35% slower
Qwen3-4B 3 62.6 / 69.9 / 69.8 62.8 / 61.8 within the A/A spread
Qwen3-4B 4 80.1 / 89.5 / 89.3 63.3 / 62.5 21-30% faster
Llama-3.2-3B 2 34.5 / 33.6 / 35.2 / 35.0 48.7 / 49.1 / 50.1 / 49.6 ~40% slower
Llama-3.2-3B 3 48.4 / 44.7 / 48.7 / 48.4 48.1 / 49.4 / 50.7 / 49.6 within the A/A spread
Llama-3.2-3B 4 63.7 / 58.2 / 63.3 / 63.5 50.2 / 50.5 / 50.7 / 51.2 13-21% faster

Per projection (CUDA events, real Qwen3-4B shapes), the bitsandbytes kernel is faster at M = 2 to 4. End to end only batch 4 keeps that advantage on this host.

Accuracy

The two kernels round differently, so outputs are not bit-identical.

Per-token NLL. 8 real-text rows x 128 teacher-forced decode steps per batch size. Each arm's NLL is compared with a reference whose projections run in fp32:

model batch A mean |dNLL| B mean |dNLL| B - A, paired t greedy agreement with the reference, A / B
Llama-3.2-3B 4 0.00255 0.00257 +1.0% (t 0.30) 0.9980 / 0.9970
Qwen3-4B 4 0.00446 0.00447 +0.2% (t 0.04) 0.9980 / 0.9980

At batch 4 the two are equally close to the reference. At batch 2 and 3, which this PR does not change, B was 3-6% further from it, still within noise.

Per projection. Against an fp64 oracle (Qwen3-4B, real weights and activations), the median relative error is 2.1e-4 for the GEMV and 2.8e-4 for bitsandbytes at M = 4.

Tests

  • New tests/test_gemv_rows_cap_table.py (CPU): pins every architecture's cap and handoff row, checks that UNSLOTH_GEMV_MAX_ROWS keeps T4 batch 4 on the GEMV, and that batch 4 steps aside when the bitsandbytes branch applies. It fails before this change and passes with it.
  • tests/test_nf4_triton_gemv.py (GPU):
    • new test_t4_batch_4_leaves_the_gemv_only_for_a_bnb_gemm_that_runs: batch 4 leaves the GEMV only in the eligible case and keeps it with the switch off, grad, bf16, compiling, the env override, another architecture, a misaligned activation, a scalar nested offset and a list state2;
    • the bitsandbytes branch test now includes batch 4 and counts the matmul_4bit calls;
    • the batch 5+ skip test adds the misaligned, scalar offset and list state2 cases.
  • Colab T4: test_nf4_triton_gemv.py, test_bnb_nf4_override.py and test_gemv_rows_cap_table.py give 331 passed, 51 skipped (bf16 cases), 0 failed. With the previous utils.py the 6 new crash cases fail with the errors above.

Not covered

  • A faster-CPU T4 host (the crossover may move lower there), and decode with CUDA graphs.
  • Batch 5 to 16, which already used bitsandbytes and is unchanged.
  • Long-generation drift and downstream task scores; MoE and other model shapes.

Lower the sm75 Triton GEMV rows cap from 4 to 3. On Colab T4 eager decode
(Qwen3-4B and Llama-3.2-3B bnb-4bit), batch 4 is 15-30% faster per token
through bnb gemm_4bit, with per-token NLL deviation from an fp32 reference
within noise of the GEMV path. Batch 2 stays on the GEMV (bnb is ~40%
slower there) and batch 3 is a tie. Other architectures are unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 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-29T17:16:38.301246Z 8f7ea18 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

Copy link
Copy Markdown

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

Reviewed commit: 816c863c27

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

Keep the T4 GEMV cap at 4 and step aside at batch 4 only when _bnb_gemm_4bit_ok
allows the bitsandbytes branch, so compiled graphs, grad, bf16, bitsandbytes < 0.50
and UNSLOTH_BNB_GEMM_4BIT=0 keep the GEMV instead of dequantizing.
@danielhanchen danielhanchen changed the title T4: run batch-4 NF4 decode through bitsandbytes' fused gemm_4bit (13-30% faster per token) T4: hand batch-4 NF4 decode to the bitsandbytes gemm_4bit where it runs Oct 29, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: cf51d4ecbf

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

…fsets

Those inputs crash bitsandbytes' fused kernel; the GEMV (batch 2-4) or dequantize
(batch 5+) handles them as before. Tests fake the T4 capability only while the
routing cache fills, so Triton still compiles for the real GPU.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 8f7ea18022

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

[skip ci]
@danielhanchen
danielhanchen merged commit c97cd18 into main Oct 29, 2026
@danielhanchen
danielhanchen deleted the t4-nf4-rows-cap branch October 29, 2026 18:37
danielhanchen added a commit that referenced this pull request Oct 29, 2026
…follow the hoisted audio_base64 in the turn-scope check (#16023)

Two checks went red on main with #15889 (LFM3-Audio / LFM3-Omni on MLX).
They fail every PR's Backend CI `(Python 3.13, g-r)` shard and `Repo
tests (CPU, studio)` job, for example on #15988 and #15934.

## 1. The audio-input route's heal gate did not get the request's
contract


`test_passthrough_healing.py::test_every_post_decode_reinterpreter_is_handed_the_request_s_own_contract`
requires every `heal_gate` / `nudge_enabled` call to be handed the
request's `response_format`, so a constraining format withdraws
tool-call healing. #15889 added a new call in the audio-input branch of
`routes/inference.py` without that argument:

```
AssertionError: heal_gate/nudge_enabled not handed the contract at [30849]
```

The product side is where this belongs, not the test. Today the omission
is harmless: that branch only runs when the request carries
`audio_base64` and the model has audio input, and earlier in the handler
that same case refuses a constraining `response_format`. Forwarding
`_extract_response_format(payload)` keeps the site under the same rule
as the other nine. If that refusal is ever relaxed, the gate then does
the right thing without anyone remembering this site.

## 2. The turn-scope check read `audio_base64` as a literal


`test_multi_chat_prompt_queue_contract.py::test_a_media_turn_stays_legacy_and_its_attachments_stay_turn_scoped`
checks that `image_base64`, `audio_base64` and `video_base64` are
scanned from `currentTurnMessages`, never from thread history. #15889
hoisted the audio scan into `const turnAudioBase64 =
findLatestUserAudioBase64(currentTurnMessages, ...)` so it can also gate
`modalities`. The behaviour is unchanged, but the test matched the old
inline text.

Here the test was wrong. It now reads every request body site for each
field and follows a hoisted `const` to its definition. It then requires
the value to be a `findLatestUser*Base64(currentTurnMessages, ...)`
scan. A new test pins that reader on a hoisted value and on a history
scan.

## Verification

- Both tests fail on main and pass here. `test_passthrough_healing.py`
has 111 passed, `test_multi_chat_prompt_queue_contract.py` 17 passed.
- Sabotage, frontend: pointing `turnAudioBase64` at `messages` instead
of `currentTurnMessages` fails the media turn test and names the sent
expression.
- Sabotage, backend: restoring main's `routes/inference.py` fails the
contract test.
- The 15 backend test files that touch `audio_base64` or the heal gate:
2872 passed, 7 skipped.

---------

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