Skip to content

NF4 decode on T4: use the bitsandbytes 4-bit GEMM above the GEMV row cap - #14386

Merged
danielhanchen merged 6 commits into
mainfrom
nf4-decode-rows-bnb-gemm-4bit
Oct 20, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
nf4-decode-rows-bnb-gemm-4bit

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

For 4-bit decode batches above the Triton GEMV row cap (_GEMV_ROWS_BY_ARCH, 4 rows on T4), fast_linear_forward dequantizes the whole weight and runs a matmul for every linear on every step. bitsandbytes 0.50 added a fused 4-bit GEMM (torch.ops.bitsandbytes.gemm_4bit, reached through bnb.matmul_4bit) that is 2x faster per linear on T4 for 5 to 16 rows.

Change

  • Batches of 5 to 16 fp16 decode rows (above the GEMV cap) use bnb.matmul_4bit on T4 (sm75) when bitsandbytes has gemm_4bit (0.50+; 0.47 / 0.48 / 0.49 do not), under no_grad, outside torch.compile, with the packed weight on the activation's device, for NF4 / FP4 states that matmul_4bit accepts. bf16 stays on the dequantize path: bitsandbytes only has fp16 MMA on sm75 and dequantizes bf16 batches of 8+ itself.
  • Every other GPU keeps the dequantize path. The fused GEMM is faster per linear on A100 and RTX PRO 6000 too, but slower end to end there: decode on those cards is bound by launches, and matmul_4bit costs more on the host than our direct dequantize call (A100: -15% at batch 4, -27% at 8 and 16; RTX PRO 6000: -10% at 8, -25 to -30% at 16).
  • The decision is made once per process, so on GPUs outside the table the decode loop pays one global compare per linear. UNSLOTH_BNB_GEMM_4BIT=0 keeps the dequantize path; =1 uses the fused GEMM on any GPU and for bf16 too.
  • Training, batch 1 to 4 decode, ROCm and bitsandbytes before 0.50 are unchanged.

Validation

tests/test_nf4_triton_gemv.py: 271 pass on B200 (new tests: rows above the cap take the fused GEMM and never dequantize, with out= reuse; the switch, an unlisted GPU, 17 rows, grad mode and bf16 all dequantize, and a weight on another device is refused; the per-process decision follows the arch table and the switch).

Colab T4 (fp16), unsloth/Llama-3.2-3B-Instruct-bnb-4bit, batched greedy decode of 64 tokens, arms interleaved in one VM (main, branch, main, branch), tok/s per run:

torch / transformers batch main this PR tokens vs main
2.12.1 / 4.57.6 1 28.5, 28.5, 27.9, 28.2 28.0, 29.0, 27.7, 28.5 identical
2.12.1 / 4.57.6 4 58.1, 57.5, 55.4, 54.1 53.2, 52.1, 54.9, 54.1 identical
2.12.1 / 4.57.6 8 98.1, 97.1, 89.0, 86.3 118.2, 118.4, 121.3, 119.5 identical
2.12.1 / 4.57.6 16 163.2, 157.1, 146.6, 150.3 204.8, 204.6, 200.5, 201.0 one row diverges (fp16 order)
2.14.1 / 5.17.0 1 27.1, 27.3, 27.9, 28.2 27.8, 27.9, 28.1, 28.4 identical
2.14.1 / 5.17.0 4 58.0, 57.2, 57.2, 56.4 57.6, 56.9, 58.3, 57.3 identical
2.14.1 / 5.17.0 8 96.8, 95.6, 94.4, 92.1 135.0, 134.9, 135.3, 133.1 identical
2.14.1 / 5.17.0 16 172.2, 173.4, 172.8, 179.3 250.2, 243.5, 252.5, 246.4 identical
  • Batch 8 / 16: +28% / +32% on torch 2.12, +42% / +43% on torch 2.14. Batch 1 and 4 do not take the new path (same code as main).
  • The fused GEMM ran 52136 times per generate on this branch and 0 times on main; on unsloth/Llama-3.2-1B-Instruct (16-bit) it ran 0 times and tok/s stayed within run-to-run spread.
  • An earlier T4 run on torch 2.10 / 2.14 (transformers 5.17) gave +23% / +26 to 30% at batch 8 / 16.

Colab A100 with this branch (torch 2.14.1, same model, bf16): the fused GEMM ran 0 times, tokens identical to main at every batch, tok/s main vs branch: batch 1 28.5-29.4 vs 28.4-29.3, batch 4 87.1-89.1 vs 86.9-88.7, batch 8 180.2-182.0 vs 177.0-179.5, batch 16 352.2-359.1 vs 352.6-356.5.

Per linear on T4 (us, NF4 with nested absmax, main vs this PR, same VM, torch 2.14.1): gate_up (28672 x 4096) 2438 / 2550 vs 1230 / 1246 at 8 rows; down (4096 x 14336) 1259 / 1324 vs 754 / 752 at 8 rows; qkv (6144 x 4096) 630 / 600 vs 592 / 591. Rows above 16 are unchanged.

Not covered: L4 (no Colab capacity on either account), H100, ROCm (path disabled there).

bitsandbytes 0.50 fuses dequantize + matmul (torch.ops.bitsandbytes.gemm_4bit).
For decode batches above the Triton GEMV row cap (up to 16 rows) on sm75 it is
2x faster per linear than dequantize + matmul and gives +23-30% decode tok/s at
batch 8-16. On A100 / RTX PRO 6000 it is slower end to end, so it is enabled per
arch. UNSLOTH_BNB_GEMM_4BIT=0 keeps the dequantize path, =1 forces it.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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 ⚠️ Failed 2026-10-20T19:40:12.876011Z f09ddab New commits
🔒 Security Review ⚠️ Failed 2026-10-20T18:26:04.506494Z 72a2c35 PR opened
ℹ️ 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: 72a2c352b0

ℹ️ 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 thread unsloth/kernels/utils.py
and bsz <= _BNB_GEMM_4BIT_MAX_ROWS
and _bnb_gemm_4bit_ok(X, W_quant)
):
out = bnb.matmul_4bit(X, W.t(), quant_state = W_quant, out = out)

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 Avoid the bnb fallback for BF16 T4 batches of 8+

On a T4 with BF16 activations and 8–16 decode rows—the primary scenario enabled here—bitsandbytes 0.50 does not select its fused kernel: _gemm_4bit_use_custom_cuda returns M < 8 for SM75 when the dtype is not FP16, after which it allocates a fully dequantized weight and calls F.linear (dispatch, fallback). Consequently this branch bypasses Unsloth's reusable global dequantization buffer and allocates the full weight on every decode projection, so the advertised fused T4 path is absent for the tested BF16 batch sizes and can regress latency and allocation pressure. Gate this route according to bitsandbytes' actual fused-kernel predicate, or retain the existing dequantization path when it would fall back.

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.

Fixed in 9a56c77: sm75 only has fp16 MMA in bitsandbytes 0.50 (_gemm_4bit_use_custom_cuda returns M < 8 otherwise), so the route now takes fp16 activations only; bf16 is allowed only with UNSLOTH_BNB_GEMM_4BIT=1. The T4 numbers in the description are fp16.

Comment thread unsloth/kernels/utils.py Outdated
elif (
_BNB_GEMM_4BIT is not False
and bsz <= _BNB_GEMM_4BIT_MAX_ROWS
and _bnb_gemm_4bit_ok(X, W_quant)

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 Require the packed weight to share the activation device

When an offloaded or model-parallel projection reaches this path with X on a T4 but W still on CPU or another GPU, _gemv_rows correctly declines because the devices differ, but this eligibility check ignores W and immediately calls bitsandbytes. Its CUDA implementation enters the activation's device context and passes B.data_ptr() directly to the native kernel without validating that device (implementation), which can cause an illegal memory access rather than the prior dequantize/matmul path's device error. Include the packed weight—and ideally its quantization tensors—in the same-device predicate before selecting this native path.

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.

Fixed in 9a56c77: the route now requires the packed weight and its absmax on the activation's device, same as _gemv_rows, so an offloaded weight keeps the dequantize path.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 9a56c77b18

ℹ️ 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 thread unsloth/kernels/utils.py
Comment on lines +1541 to +1543
and getattr(quant_state, "quant_type", None) in ("nf4", "fp4")
# matmul_4bit raises for any other nested blocksize.
and (not quant_state.nested or quant_state.state2.blocksize == 256)

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 unaligned weights on the reusable dequantize path

When an FP16 T4 projection has an input dimension that is not divisible by quant_state.blocksize (for example, K=3420 with blocksize 64), this predicate still selects bnb.matmul_4bit. bitsandbytes 0.50 explicitly sends that case to its dequantize-plus-linear fallback and emits a warning on every invocation (dispatch); that fallback allocates a full dequantized weight rather than using Unsloth's reusable global buffer. Require quant_state.shape[1] % quant_state.blocksize == 0 here so these decode projections retain the existing allocation behavior and do not flood users with warnings.

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.

Fixed in 4c99569: the route now also requires K to be a multiple of the blocksize (bitsandbytes 0.50 dequantizes and warns otherwise), so those projections keep the reusable dequantize buffer. Test added.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 4c99569212

ℹ️ 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 9731b3a into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the nf4-decode-rows-bnb-gemm-4bit branch October 20, 2026 20:11
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 22, 2026
…compile (unslothai#14608)

unslothai#14386 added `_bnb_gemm_4bit_ok`, the gate that sends 4-bit decode with
2 to 16 rows to bitsandbytes' GEMM on T4. On the first call its lazy
setup runs `torch.cuda.device_count()` and the capability checks, and
only then checks `_is_compiling()`. Dynamo cannot trace
`torch.cuda.device_count()`, so a cold compiled decode call fails with
`fullgraph=True`:

```
torch._dynamo.exc.Unsupported: torch.* op returned non-Tensor
```

Without fullgraph it becomes a graph break. This happens on every GPU,
not only T4, because the setup runs before the arch check. The existing
compile test warms the function up eagerly first, which sets the gate up
outside tracing and hides the failure.

Repro (fresh process):

```python
import unsloth
import torch, bitsandbytes as bnb
from unsloth.kernels.utils import fast_linear_forward

p = bnb.nn.Linear4bit(256, 128, bias=False, compute_dtype=torch.float16, quant_type="nf4").half().cuda()
x = torch.randn(8, 1, 256, device="cuda", dtype=torch.float16)
with torch.no_grad():
    torch.compile(lambda a: fast_linear_forward(p, a), fullgraph=True, backend="aot_eager")(x)
```

## Change
- `_bnb_gemm_4bit_ok` now returns False under `torch.compile` or with
grad enabled before the lazy setup.
- The same two checks are dropped from the end of the condition, where
they no longer did anything.
- Compiled and training calls take the same path as before unslothai#14386. Eager
no-grad decode is unchanged.

## Validation
- New `test_fast_linear_forward_cold_compile_fullgraph` (bsz 8 and 16)
compiles `fast_linear_forward` with `fullgraph=True` from the gate's
cold state, with no eager warmup, and compares the result with eager.
  - Without this change: 2 failed (the error above).
  - With it: 2 passed.
- `tests/test_bnb_integration_compile.py` +
`tests/test_nf4_triton_gemv.py`: 401 passed on torch 2.14.1 and on torch
2.10.0 (B200), incl. the eager bitsandbytes GEMM routing tests.

Not covered: T4 hardware (the routing tests fake the arch); torch 2.11
to 2.13 (the change only moves existing Python checks).
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
…er autocast, refresh the cached LoRA cast (unslothai#14754)

Three fixes in `fast_linear_forward` (4-bit decode): a recompile from
the bitsandbytes 4-bit GEMM gate added in unslothai#14386, the output dtype under
a different autocast dtype, and the cached LoRA weight cast.

## 1. No recompile when an eager call sets the gate up

`fast_linear_forward` read the lazily set global `_BNB_GEMM_4BIT` before
`_bnb_gemm_4bit_ok` checked `_is_compiling()`. Reading the global while
tracing makes Dynamo guard on its value. A graph captured while it was
still `None` is invalidated as soon as any eager call sets it to `True`
or `False`, so every compiled region that goes through
`fast_linear_forward` recompiles once.

The fix checks `not _is_compiling()` first, so the global is never read
while tracing. Under compile the gate already returned `False`, so
compiled code takes the same path as before; only the guard goes away.

## 2. One output dtype under a different autocast dtype

`bitsandbytes` `gemm_4bit` returns `X.dtype`, while the `torch.matmul`
paths (dequantize fallback, dense) return the autocast dtype when called
under a different one (fp16 activations under bf16 autocast, or the
reverse). The output dtype therefore depended on the batch size and
quant path, and with a LoRA adapter the in-place `addmv_` / `addmm_`
update failed: its `torch.mv` / `torch.mm` operand follows autocast
while the base output and LoRA factors do not (`mat1 and mat2 must have
the same dtype`). On main this fails on both the fused GEMM and the
fallback path.

Now the base result is cast back to `X.dtype` when it differs, and the
LoRA `mv` / `mm` result is cast to `X.dtype` before the in-place update,
so every path returns `X.dtype` (the activation dtype every decode
caller allocates its buffers in). Without autocast, or with a matching
autocast dtype, nothing changes.

## 3. The cached LoRA cast follows weight updates

`fast_linear_forward` cast the LoRA factors to the activation dtype once
and stored the copy on the weight as `_fast_lora`, never refreshing it.
When the dtypes differ, which is the default for float16 models (LoRA
kept in float32 for mixed precision, so T4), every later decode reused
the factors from the first decode: after more training steps (GRPO
generation without vLLM, or SFT then generate then more SFT) decode ran
with stale adapters. The cache is now keyed on both weights' `_version`
and `data_ptr()` and the dtype, so an optimizer step or a replaced
tensor recasts. Matching dtypes skip the cache entirely (the cast is a
no-op). Inference tensors (a LoRA model built under
`torch.inference_mode()`) have no version counter, so for them the key
is the storage and dtype only. While tracing, the cast is done inline
instead of setting an attribute, which was the second source of a guard
on the eager setup.

## Tests

`tests/test_bnb_integration_compile.py`:
- `test_fast_linear_forward_eager_setup_does_not_recompile`: compile
cold, run eager once, call the compiled function again, assert one frame
compiled (`torch._dynamo.testing.CompileCounter`) and identical outputs.
- `test_fast_linear_forward_sees_lora_updates`: float32 adapters,
float16 decode, update `lora_B` in place, the next decode must match a
freshly cast one bitwise.
-
`test_fast_linear_forward_lora_under_a_different_autocast_dtype[True|False]`:
fp16 activations with LoRA under bf16 autocast, through the bitsandbytes
GEMM (calls counted) and the dequantize fallback; output must be fp16
and match the no-autocast result.
- `test_fast_linear_forward_lora_cast_with_inference_tensors`: LoRA
model built under `torch.inference_mode()`, float32 adapters, fp16
decode twice.

New tests on B200:

| torch | main | this PR |
|---|---|---|
| 2.10.0 | 4 failed, 7 passed | 11 passed |
| 2.14.0 | 4 failed, 7 passed | 11 passed |

(`-k` over every `fast_linear_forward` test in the file; the
inference-tensor test passes on main too, it guards the new cache key.)

The 10 test files that exercise `fast_linear_forward` or its LoRA cast
(bnb integration / compile, NF4 GEMV, float32 LoRA fallback, GPTQ, NVFP4
and MXFP4 LoRA, non-LoRA PEFT inference, multiple active adapters,
compressed-tensors FP8 route, LoRA dropout), torch 2.14 on B200: main 5
failed / 538 passed / 20 skipped, this branch 545 passed / 20 skipped
(current head; 543 passed on the first revision). Three of main's
failures are the new tests; the other two
(`test_compiled_lora_mlp_backward_never_reads_stale_memory[swiglu|geglu_approx]`)
timed out on both sides when rerun alone on this loaded host, so they
are not claimed either way. The torch 2.10 run of the same 10 files did
not finish within 50 minutes on either side on this shared host.

Not covered: no T4 / L4 run (the GEMM gate's target arch list); the
change does not touch the arch list or the kernel call, only the gate
condition, the output casts and the LoRA cast above. ROCm is unaffected
(`torch.version.hip` already disables the path).
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