Repository navigation
NF4 decode on T4: use the bitsandbytes 4-bit GEMM above the GEMV row cap - #14386
Conversation
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.
|
@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: 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| elif ( | ||
| _BNB_GEMM_4BIT is not False | ||
| and bsz <= _BNB_GEMM_4BIT_MAX_ROWS | ||
| and _bnb_gemm_4bit_ok(X, W_quant) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…tize path [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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". |
[skip ci]
…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).
…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).
For 4-bit decode batches above the Triton GEMV row cap (
_GEMV_ROWS_BY_ARCH, 4 rows on T4),fast_linear_forwarddequantizes 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 throughbnb.matmul_4bit) that is 2x faster per linear on T4 for 5 to 16 rows.Change
bnb.matmul_4biton T4 (sm75) when bitsandbytes hasgemm_4bit(0.50+; 0.47 / 0.48 / 0.49 do not), under no_grad, outsidetorch.compile, with the packed weight on the activation's device, for NF4 / FP4 states thatmatmul_4bitaccepts. bf16 stays on the dequantize path: bitsandbytes only has fp16 MMA on sm75 and dequantizes bf16 batches of 8+ itself.matmul_4bitcosts 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).UNSLOTH_BNB_GEMM_4BIT=0keeps the dequantize path;=1uses the fused GEMM on any GPU and for bf16 too.Validation
tests/test_nf4_triton_gemv.py: 271 pass on B200 (new tests: rows above the cap take the fused GEMM and never dequantize, without=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:unsloth/Llama-3.2-1B-Instruct(16-bit) it ran 0 times and tok/s stayed within run-to-run spread.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).