Skip to content

Run bitsandbytes NF4 Linear4bit through Unsloth's NF4 kernels - #12739

Merged
danielhanchen merged 5 commits into
mainfrom
bnb-nf4-override
Oct 5, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
bnb-nf4-override

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

FastModel and zoo's compiled PEFT LoRA forwards reach bitsandbytes NF4 layers through self.base_layer(x), which goes to bnb.matmul_4bit and never uses Unsloth's NF4 kernels. This PR replaces bitsandbytes.nn.Linear4bit.forward for NF4 weights so those calls use the Triton dequantize, plus the Triton GEMV for a single decode row. Training losses are bit-identical to bitsandbytes on every GPU tested. With bitsandbytes 0.45.5 and per-layer compile, training is 0.58x the time and decode is 2.19x faster on B200.

Why

The FastLlamaModel fast path already calls fast_dequantize / fast_gemv itself. The generic path (FastModel, Gemma 3, vision models, zoo's compiled LoRA modules) only calls the bitsandbytes module. Before bitsandbytes 0.50, that means bitsandbytes' dequantize + F.linear on every call, and with 0.45.5 several ctypes graph breaks per layer under torch.compile.

What changed

New unsloth/kernels/bnb_override.py, installed at the end of FastLlamaModel.from_pretrained and FastBaseModel.from_pretrained:

  • NF4 weights (uint8 storage, K % blocksize == 0, CUDA, compute dtype equal to the quant state dtype) run the Triton dequantize + F.linear. A single decode row runs fast_gemv.
  • The backward recomputes the dequantized weight for dX the same way bitsandbytes does, so dX is bit for bit bitsandbytes'.
  • bitsandbytes >= 0.50 has its own fused 4-bit GEMM, which it picks per GPU and shape for 2..1536 rows. The override asks that same heuristic and leaves those calls to bitsandbytes. It only takes the shapes where bitsandbytes would dequantize + F.linear anyway (same bits, faster dequantize), plus the single decode row. Eager answers are cached per layer and element count. Traced code leaves the whole 2..1536 range to bitsandbytes.
  • Everything else runs the forward that was installed before it (zoo's patched one): fp4, packed storage, misaligned K, mismatched compute dtype, trainable bias, autocast to another dtype, and fp32 below 8 rows.
  • Compiled: traced from torch 2.11, and bf16 is traced only when every GPU is sm80+. On older torch, compiled code keeps bitsandbytes' forward when it traces (>= 0.46). On 0.45.5 the override runs as one opaque call, which gives fewer graph breaks than bitsandbytes' own ctypes calls.
  • nf4_gemv: the weight sizes are specialized before the cached config lookup. Under torch.compile(dynamic=True) they arrived as SymInts, and Dynamo skipped fast_gemv and broke on its eager helpers.

Default:

  • On for every CUDA GPU sm75+ with bitsandbytes < 0.50.
  • With bitsandbytes 0.50+, on only when every GPU is sm100 or sm120. On A100 and T4, batched decode with 2 to 8 rows still ran 2-3% slower end to end with the override installed, even though bitsandbytes handles those calls. Single-row decode there was 6-8% faster, so UNSLOTH_BNB_NF4_LINEAR=1 is worth setting for batch-1 serving.
  • Off on ROCm.
  • UNSLOTH_BNB_NF4_LINEAR=1 / 0 forces it on or off. UNSLOTH_BNB_TRITON=0 still turns off every Unsloth NF4 kernel.

Results

gemma-3-1b-it NF4, LoRA r16, FastModel defaults (compiled LoRA modules). "Train" is step time PR / base, so lower is faster. "Decode" is tok/s PR / base, so higher is faster. Every arm has an A/A base repeat. Loss is bit-identical in every row, and the teacher-forced NLL deltas (32 prompts, full prefill and token-by-token) all have a 95% CI spanning 0.

Training and batch-1 decode, override forced on:

GPU torch bitsandbytes train (A/A) decode bs1 (A/A)
B200 2.7.1 0.45.5, per-layer compile 0.58x (1.03) 2.19x (1.00)
B200 2.7.1 0.45.5, eager 0.88x (1.10) 1.12x (0.99)
B200 2.13 0.49.2, eager 0.95x (1.00) 1.18x (1.00)
B200 2.13 0.50.2, eager 0.90x (0.97) 1.06x (1.02)
B200 2.13 0.50.2, FastModel compile 0.96x (1.02) 1.04x (busy host)
A100 2.11 0.50.2 0.98x (1.00) 1.04x (1.00)
L4 2.11 0.50.2 0.99x (0.99) 1.06x (0.99)
RTX PRO 6000 (G4) 2.11 0.50.2 0.97x (1.00) 1.02x (1.00)
T4 2.11 0.50.2, fp16 1.00x (1.00) 1.04x (1.00)

Batched decode on bitsandbytes 0.50.2, torch 2.11, one fresh process per measurement in base, pr, pr, base, base, pr order, tok/s PR / base (base spread across its 3 processes in brackets):

GPU bs1 bs2 bs4 bs8
A100 1.065 (1.3%) 0.971 (1.4%) 0.973 (1.0%) 0.979 (0.6%)
T4 1.076 (1.6%) 0.977 (1.2%) 0.975 (0.8%) 0.977 (0.6%)
RTX PRO 6000 (G4) 1.005 (0.7%) 0.988 (1.3%) 1.000 (0.8%) 1.005 (0.6%)

That table is why the 0.50+ default is limited to sm100 / sm120.

Every NF4 layer of the model called once at M rows (no_grad), speed PR / base, A/A within 1%:

GPU M=1 M=2..8 M=16 M=64 M=256 M=1024
A100 1.39x 0.96-0.97x (bitsandbytes kernel, same bits) 0.97x 1.07x 1.27x 1.37x
T4 1.44x 0.97-0.98x (same) 0.97x 1.01x 1.16x 1.06x
RTX PRO 6000 1.15x 0.98-1.01x (same) 1.04x 1.33x 1.33x 1.14x

If dequantize + cuBLAS is forced on the 2..8 row calls that bitsandbytes 0.50 fuses, they run at 0.57-0.77x. That is why those calls are left to bitsandbytes.

Tests

New tests/test_bnb_nf4_override.py:

  • Forward and dX bit-exact against bitsandbytes for bf16 / fp16 / fp32, nested and plain absmax, with and without bias.
  • Single-row GEMV error at most bitsandbytes' own GEMV error against fp64, over 16 seeds.
  • Every unsupported case falls back to the original forward.
  • Compiled: 0 graph breaks, and outputs bit-exact against eager for bf16 / fp16. For fp32 with a bias feeding a pointwise op, Inductor rewrites addmm into mm + a fused bias add (unfuse_bias_add_to_pointwise, fp32 only). cuBLAS rounds that differently from the bias-epilogue addmm on A100, T4 and RTX PRO 6000. Plain PyTorch F.linear with no bitsandbytes at all drifts the same way, and TF32 has no effect on it. So the fp32 case is checked bit-exact against the same F.linear compiled.
  • dynamic=True decode through a module: 0 graph breaks.
  • With bitsandbytes 0.50's fused GEMM present, its fused shapes are routed to bitsandbytes, and the heuristic is asked once per layer and shape.
  • Default gate, env switches, kill switch.

Results:

  • torch 2.13 + bitsandbytes 0.50.2: 44 passed.
  • torch 2.14 + bitsandbytes 0.50.2: 44 passed.
  • torch 2.7.1 + bitsandbytes 0.45.5: 37 passed, 7 skipped (traced-only and 0.50-only cases).
  • torch 2.11 on A100 and RTX PRO 6000: 44 passed.
  • torch 2.11 on T4: 42 passed, 2 skipped (bf16 compile below sm80).

FastModel and zoo's compiled PEFT LoRA forwards call self.base_layer(x), which
lands in bnb.matmul_4bit. unsloth/kernels/bnb_override.py replaces
Linear4bit.forward for NF4 weights (uint8 storage, K % blocksize == 0, CUDA,
compute dtype == quant state dtype) with the Triton dequantize + F.linear, the
Triton GEMV for a single decode row, and an autograd Function that recomputes
the dequantized weight for dX. Everything else runs the forward installed
before it (zoo's patched one), including fp32 below 8 rows.

- dX is bit for bit bitsandbytes'; the forward equals bitsandbytes wherever
  bitsandbytes dequantizes + F.linear itself.
- bitsandbytes >= 0.50 picks a fused 4-bit GEMM per GPU and shape for 2..1536
  rows. The override asks that same heuristic and leaves those calls to
  bitsandbytes (dequantize + cuBLAS was 0.56x at 4 rows on B200), taking only
  the shapes where bitsandbytes would dequantize, plus the single decode row.
  Traced code leaves the whole 2..1536 range to bitsandbytes; eager answers are
  cached per layer and element count.
- Traced from torch 2.11 (bf16 only when every GPU is sm80+). Below that,
  compiled code keeps bitsandbytes' forward when it traces (>= 0.46), else one
  opaque call (fewer breaks than 0.45.5's ctypes calls).
- On by default for every CUDA GPU sm75+ with bitsandbytes < 0.50; with
  0.50+ only when every GPU is sm100 or sm120. On A100 and T4 with 0.50,
  batched decode (2-8 rows, all left to bitsandbytes) still ran 2-3% slower
  end to end with the override installed, so those stay opt-in. Off on ROCm.
  UNSLOTH_BNB_NF4_LINEAR=1/0 forces it; UNSLOTH_BNB_TRITON=0 keeps the global
  kill switch.
- Installed at the end of FastLlamaModel / FastBaseModel from_pretrained.

nf4_gemv: specialize the weight sizes before the cached config lookup. Under
torch.compile(dynamic=True) they arrive as SymInts, and the unhashable SymInt
made Dynamo skip fast_gemv and break on its eager helpers.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 5, 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-05T13:18:46.537379Z 2017fba New commits
ℹ️ 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 5, 2026
@chatgpt-codex-connector

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-05T11:09:26.606920Z 2fbabd5 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.

@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: 2fbabd509c

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

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