Repository navigation
Fused Triton NF4 dequant and GEMV: bit-exact, stream-safe, torch.compile traceable - #12113
Conversation
fast_dequantize and fast_gemv call a dequantize_nf4 / gemv_nf4 contract registered as torch.library ops, so matmul_lora and the fast_lora autograd functions compile with fullgraph=True and no graph breaks. The ctypes fallback (UNSLOTH_BNB_TRITON=0) reads the live stream instead of the import-time snapshot, the global buffer is kept per stream and skipped while compiling or capturing a CUDA graph, and FP4 states use their own codebook. nf4.py and nf4_gemv.py are bitsandbytes-backed stand-ins for the fused kernels.
Replace the bitsandbytes-backed stand-ins with one-launch Triton kernels: the dequant decodes the nested absmax (two roundings, as bitsandbytes does), adds the offset and applies the NF4 table in a single pass, and the batch-1 GEMV fuses the same decode into the dot product. On HIP the dequant ops are opaque custom ops so the eager launch keeps fp fusion disabled.
quant_state.code is bit-identical to the kernel's table and already lives on the device, so a compiled graph no longer rebuilds the table on every call.
… scratch, JIT fallback, float quant_storage
…le tests follow torch's own exactness
… the LoRA backward
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. |
…d a register table gather All knob combinations stay byte-identical to bitsandbytes (new test covers every one). On B200 the int32 loads plus tl.gather table are 1.2x to 1.4x faster than the previous config at Llama 8B / 70B shapes on Triton 3.6 and 3.7. Other GPUs keep the previous config until measured. tl.gather is only used on Triton >= 3.6 (it fails to compile on 3.3).
…cdiv from the hot path Triton's JIT launch rebuilds the argument binding and specialization key on every call, about 12 us of CPU against about 5 us for launching the compiled kernel. triton.cdiv is itself a JIT function on recent Triton and cost several microseconds per call. On fast GPUs a small QLoRA model is CPU bound, so both showed up in the step time.
…riton 3.7 With the direct launch, the int32 words GEMV beat bitsandbytes' in kernel time on T4, L4, A100, RTX PRO 6000 and B200 (1.1x to 2.2x, lower error) and in batch-1 decode, so eager decode no longer keeps bitsandbytes' GEMV before Triton 3.7 on CUDA. HIP keeps the old gate.
…t stays byte exact Inductor re-emits the GEMV Triton kernel and, for some Triton versions and launch configs, a partial sum rounds differently than the eager launch (one ulp in 5 to 16 of 40 seeds on Triton 3.6 and 3.7 with the byte kernel). The dequant has no reduction and stays exact.
Both multiplies use libdevice mul_rn on CUDA. It is never contracted into an FMA with the following + offset when torch.compile re-emits the kernel with fp fusion on, and it flushes subnormal products to zero like the bitsandbytes kernels, so the dequant now also matches bitsandbytes byte for byte when code * absmax underflows (the PTX mul.rn.f32 kept subnormals). TRITON_INTERPRET=1 takes the plain multiply route, since the interpreter has no libdevice. Tests: a fusion-on launch (the route torch.compile takes) and subnormal products, both of which fail with a plain multiply.
Inductor's FX graph cache keys a torch.library.triton_op call without the Triton source behind it. With a warm cache, an edited kernel was served as the previous kernel's compiled code (reproduced on torch 2.13 by swapping a mul_rn for a plain multiply: the compiled output stayed identical to the old kernel until the cache was cleared). Unsloth turns the FX graph cache on, so an upgrade could keep running an older kernel under torch.compile. Add a hash of each kernel file to torch.compiler.config.cache_key_tag.
On ROCm (gfx1151, AMD CI) the kernel has no libdevice.mul_rn, so a launch forced to fp fusion on contracts code2 * absmax2 + offset into an FMA and differs from bitsandbytes. That route never runs with fusion on: eager launches pass fp_fusion=False and compiled graphs keep the op opaque. Every other dequant, GEMV and compile test passed on gfx1151.
torch._C._cuda_getCurrentRawStream does not exist in CPU-only builds, so the module raised AttributeError at import (Backend CI Repo tests, CPU). Look it up with getattr and keep the fast path off without it.
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
Batch > 1 decode dequantizes every weight into the scratch buffer once per token and is CPU bound on typical hosts, so the per-call argument handling in fast_dequantize, dequantize_nf4 and the launch cache key cost more than the kernel. The first call per weight now plans the launch (triton_launch.relaunch) and later calls repeat it after checking the weight pointer, the absmax tensor and the dtype. The plan is dropped on copy and pickle. Batch 4 decode vs the merge base, Llama-3.2-1B / Qwen3-0.6B 4bit: A100 +17.8% / +17.9%, L4 +17.3% / +16.6%, RTX PRO 6000 +14.9% / +15.4%, T4 +11.3% / +20.4% (was -1.6% to -5.7%).
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
Batch-1 decode runs every weight once per token and is CPU bound, so fast_gemv now repeats the first launch per weight (gemv_nf4_planned) after checking the weight pointer, the absmax tensor, the activation dtype and its 16 byte alignment, as the batch > 1 dequant path already does. fast_gemv CPU per call: 13.3 to 9.3 us (2048x2048), against 24 us for main's bitsandbytes ctypes path. Batch-1 decode vs main: A100 Llama 3.2 1B +17.3%, Llama 3.1 8B +19.4%, Qwen3 0.6B +15.9%; L4 +18.1%, +17.2%, +14.0% (was +4% to +6%). Drop the T4 BLOCK_K 512 rule for large weights. Interleaved CUDA graph timing (T4 throttles, so the sweep that chose it was not) has BLOCK_K 2048 faster at 14336x4096 (261 vs 285 us), 4096x14336 (261 vs 297 us) and the vocab shape (1218 vs 1349 us).
Under torch.compile the accumulating addmm_ calls in the LoRA forward and backward became out-of-place addmm with a full copy of the accumulator, and the in-place SwiGLU backward kernel made Inductor copy the saved gate and up activations first. unsloth::addmm_ (a custom op mutating its output) keeps the accumulation in place, and the traced SwiGLU backward is plain torch math that Inductor fuses into one kernel reusing those buffers. On Triton 3.7, T4 and L4 run the Llama 8B MLP GEMV shapes faster at BLOCK_K 1024 and 2 warps, and T4 dequantizes 5% to 7% faster with 512 byte programs, 8 warps and word loads. Other GPUs keep their configs.
|
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". |
…n it T4 trains in fp16 (bf16 requests fall back), and Dynamo cannot trace the bf16 kernel launch there.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…ile traceable (unslothai#12113) * Route 4bit dequant and gemv through traceable NF4 ops on the live stream fast_dequantize and fast_gemv call a dequantize_nf4 / gemv_nf4 contract registered as torch.library ops, so matmul_lora and the fast_lora autograd functions compile with fullgraph=True and no graph breaks. The ctypes fallback (UNSLOTH_BNB_TRITON=0) reads the live stream instead of the import-time snapshot, the global buffer is kept per stream and skipped while compiling or capturing a CUDA graph, and FP4 states use their own codebook. nf4.py and nf4_gemv.py are bitsandbytes-backed stand-ins for the fused kernels. * Use fused Triton NF4 dequant and GEMV kernels behind the traceable ops Replace the bitsandbytes-backed stand-ins with one-launch Triton kernels: the dequant decodes the nested absmax (two roundings, as bitsandbytes does), adds the offset and applies the NF4 table in a single pass, and the batch-1 GEMV fuses the same decode into the dot product. On HIP the dequant ops are opaque custom ops so the eager launch keeps fp fusion disabled. * Pass the quant state's NF4 codebook to the fused dequant quant_state.code is bit-identical to the kernel's table and already lives on the device, so a compiled graph no longer rebuilds the table on every call. * Harden the NF4 kernels: gemv block alignment fallback, default-stream scratch, JIT fallback, float quant_storage * Keep the NF4 GEMV identical under torch.compile on older torch; compile tests follow torch's own exactness * Do not alias dX into X in the fast_lora backward while compiling * Keep bitsandbytes' GEMV for eager decode before Triton 3.7 * A Dynamo exception is never a kernel failure * Leaner bitsandbytes GEMV route for eager decode before Triton 3.7 * Compile tests: fp16 where Unsloth runs fp16, dense-weight control for the LoRA backward * Keep the LoRA Functions opaque to torch.compile before torch 2.11 * Use the SPDX license header on the new NF4 files * NF4 dequant: per-GPU launch table with int32 loads, eviction hints and a register table gather All knob combinations stay byte-identical to bitsandbytes (new test covers every one). On B200 the int32 loads plus tl.gather table are 1.2x to 1.4x faster than the previous config at Llama 8B / 70B shapes on Triton 3.6 and 3.7. Other GPUs keep the previous config until measured. tl.gather is only used on Triton >= 3.6 (it fails to compile on 3.3). * NF4 GEMV: int32 word kernel for Triton before 3.7, per-GPU configs, eager gate hook * Launch the cached NF4 kernels directly in eager mode and drop triton.cdiv from the hot path Triton's JIT launch rebuilds the argument binding and specialization key on every call, about 12 us of CPU against about 5 us for launching the compiled kernel. triton.cdiv is itself a JIT function on recent Triton and cost several microseconds per call. On fast GPUs a small QLoRA model is CPU bound, so both showed up in the step time. * Eager decode takes the Triton NF4 GEMV on CUDA, words kernel before Triton 3.7 With the direct launch, the int32 words GEMV beat bitsandbytes' in kernel time on T4, L4, A100, RTX PRO 6000 and B200 (1.1x to 2.2x, lower error) and in batch-1 decode, so eager decode no longer keeps bitsandbytes' GEMV before Triton 3.7 on CUDA. HIP keeps the old gate. * Compile test: the NF4 GEMV matches eager within tolerance, the dequant stays byte exact Inductor re-emits the GEMV Triton kernel and, for some Triton versions and launch configs, a partial sum rounds differently than the eager launch (one ulp in 5 to 16 of 40 seeds on Triton 3.6 and 3.7 with the byte kernel). The dequant has no reduction and stays exact. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * NF4 kernels: libdevice mul_rn instead of inline PTX Both multiplies use libdevice mul_rn on CUDA. It is never contracted into an FMA with the following + offset when torch.compile re-emits the kernel with fp fusion on, and it flushes subnormal products to zero like the bitsandbytes kernels, so the dequant now also matches bitsandbytes byte for byte when code * absmax underflows (the PTX mul.rn.f32 kept subnormals). TRITON_INTERPRET=1 takes the plain multiply route, since the interpreter has no libdevice. Tests: a fusion-on launch (the route torch.compile takes) and subnormal products, both of which fail with a plain multiply. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * NF4 kernels: key the torch.compile cache on the kernel source Inductor's FX graph cache keys a torch.library.triton_op call without the Triton source behind it. With a warm cache, an edited kernel was served as the previous kernel's compiled code (reproduced on torch 2.13 by swapping a mul_rn for a plain multiply: the compiled output stayed identical to the old kernel until the cache was cleared). Unsloth turns the FX graph cache on, so an upgrade could keep running an older kernel under torch.compile. Add a hash of each kernel file to torch.compiler.config.cache_key_tag. * NF4 tests: skip the forced fusion-on case where mul_rn is unavailable On ROCm (gfx1151, AMD CI) the kernel has no libdevice.mul_rn, so a launch forced to fp fusion on contracts code2 * absmax2 + offset into an FMA and differs from bitsandbytes. That route never runs with fusion on: eager launches pass fp_fusion=False and compiled graphs keep the op opaque. Every other dequant, GEMV and compile test passed on gfx1151. * Shorten comments * NF4: keep tl.gather out of the kernel body on Triton without it Triton 3.2 (torch 2.6) has no tl.gather, and its JIT resolves every attribute in a kernel body while hashing dependencies, dead constexpr branches included, so every NF4 dequant launch raised AttributeError there. The register-table gather now lives in a helper that falls back to the L1 table load. * Triton launch test: skip the cache check where Triton returns no packed_metadata Triton 3.2 (torch 2.6) returns a kernel without packed_metadata, so launch() never caches it and every call takes Triton's own path, which is correct; the cache assertion only applies where the fast path exists. * NF4: name the fake kernels (lint_duplicate_definitions flags two defs named _) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim comments * Triton launch: import on CPU-only torch torch._C._cuda_getCurrentRawStream does not exist in CPU-only builds, so the module raised AttributeError at import (Backend CI Repo tests, CPU). Look it up with getattr and keep the fast path off without it. * NF4 decode: repeat each weight's planned dequant launch Batch > 1 decode dequantizes every weight into the scratch buffer once per token and is CPU bound on typical hosts, so the per-call argument handling in fast_dequantize, dequantize_nf4 and the launch cache key cost more than the kernel. The first call per weight now plans the launch (triton_launch.relaunch) and later calls repeat it after checking the weight pointer, the absmax tensor and the dtype. The plan is dropped on copy and pickle. Batch 4 decode vs the merge base, Llama-3.2-1B / Qwen3-0.6B 4bit: A100 +17.8% / +17.9%, L4 +17.3% / +16.6%, RTX PRO 6000 +14.9% / +15.4%, T4 +11.3% / +20.4% (was -1.6% to -5.7%). * NF4 GEMV: plan each weight's batch-1 decode launch, one T4 config Batch-1 decode runs every weight once per token and is CPU bound, so fast_gemv now repeats the first launch per weight (gemv_nf4_planned) after checking the weight pointer, the absmax tensor, the activation dtype and its 16 byte alignment, as the batch > 1 dequant path already does. fast_gemv CPU per call: 13.3 to 9.3 us (2048x2048), against 24 us for main's bitsandbytes ctypes path. Batch-1 decode vs main: A100 Llama 3.2 1B +17.3%, Llama 3.1 8B +19.4%, Qwen3 0.6B +15.9%; L4 +18.1%, +17.2%, +14.0% (was +4% to +6%). Drop the T4 BLOCK_K 512 rule for large weights. Interleaved CUDA graph timing (T4 throttles, so the sweep that chose it was not) has BLOCK_K 2048 faster at 14336x4096 (261 vs 285 us), 4096x14336 (261 vs 297 us) and the vocab shape (1218 vs 1349 us). * Traced LoRA without copies; T4 / L4 configs on Triton 3.7 Under torch.compile the accumulating addmm_ calls in the LoRA forward and backward became out-of-place addmm with a full copy of the accumulator, and the in-place SwiGLU backward kernel made Inductor copy the saved gate and up activations first. unsloth::addmm_ (a custom op mutating its output) keeps the accumulation in place, and the traced SwiGLU backward is plain torch math that Inductor fuses into one kernel reusing those buffers. On Triton 3.7, T4 and L4 run the Llama 8B MLP GEMV shapes faster at BLOCK_K 1024 and 2 warps, and T4 dequantizes 5% to 7% faster with 512 byte programs, 8 warps and word loads. Other GPUs keep their configs. * Shorten comments * Traced SwiGLU test: fp16 everywhere, bf16 only where Unsloth trains in it T4 trains in fp16 (bf16 requests fall back), and Dynamo cannot trace the bf16 kernel launch there. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…gfx1151) (unslothai#14440) On ROCm, eager batch-1 NF4 decode (`fast_gemv` in `unsloth/kernels/utils.py`) still calls bitsandbytes' ctypes GEMV, which on gfx1151 is about 3x slower per call than Unsloth's own Triton NF4 GEMV on the large projections. The cause is the gate `triton_gemv_eager()` in `unsloth/kernels/nf4_gemv.py`: - It returns `torch.version.hip is None or triton >= 3.7`. It came in with unslothai#12113 ("keep bitsandbytes' GEMV for eager decode before Triton 3.7") for every device. - CUDA was switched back to the Triton GEMV once the int32 words kernel beat bitsandbytes there, but HIP kept the old gate and was never re-measured. - No correctness reason excludes HIP. The GEMV tests passed on gfx1151, and compiled code already takes the Triton GEMV on HIP. ## Change - On HIP with Triton 3.6+, eager batch-1 decode takes the Triton GEMV. Below 3.6 HIP keeps bitsandbytes (not measured there). Decode batches of 2+ on HIP still dequantize, as before. - New `UNSLOTH_TRITON_GEMV_EAGER`: `0` keeps bitsandbytes' GEMV, `1` takes the Triton GEMV on any GPU and Triton. Unset, CUDA routing is unchanged. - `test_planned_rows_are_reused_without_an_out` was previously skipped on HIP and now runs there. It skips when the direct launcher (`triton_launch`, CUDA only) is off: plans are only kept with it, and the multi-row path it forces is not taken on HIP. ## Validation `tests/test_nf4_triton_gemv.py` adds 38 cases; the 14 gate and routing cases fail on main: - the gate per platform, Triton version and switch value; - routing on a faked ROCm with Triton 3.6 (batch 1 takes the planned Triton GEMV with zero ctypes calls, the switch restores ctypes, rows still dequantize); - numerical checks of the route `fast_gemv` takes vs dequantize + fp32 matmul on Llama-8B / Qwen shapes, fp16 / bf16, nested and flat absmax. On B200, `test_nf4_triton_gemv.py` + `test_bnb_integration_compile.py` + `test_triton_fp_fusion.py`: 403 passed. AMD gfx1151 (Strix Halo, ROCm, torch 2.11, Triton 3.6), main vs this branch on the same runner, each also with `UNSLOTH_TRITON_GEMV_EAGER=0`. Every call took the Triton route on the branch and ctypes on main and with the switch off; parity vs fp64 is within the existing test tolerance. Decode loop over real layer shapes, ms per token (host time included): | model shapes | main | this PR | switch off | |---|---|---|---| | Llama-3-8B, 8 layers | 9.85 | 5.34 (1.84x) | 9.85 | | Llama-3.2-1B, 16 layers | 6.93 | 3.86 (1.80x) | 7.00 | Per call, ms (CUDA events, first of the two AMD runs): | shape (N x K) | main (ctypes) | this PR (Triton) | |---|---|---| | up 14336 x 4096 | 0.293 | 0.097 | | down 4096 x 14336 | 0.276 | 0.099 | | Qwen up | 0.244 | 0.082 | | q 4096 x 4096 | 0.085 | 0.033 | | kv 1024 x 4096 | 0.030 | 0.019 | | 256 x 256 | 0.014 | 0.019 | - The smallest shape is slower per call because HIP has no direct launcher, so each Triton call pays the full launch cost. That does not show at the decode-loop level. - The tests on the runner: main 326 passed / 35 skipped, this PR 385 passed / 14 skipped, 0 failed. Not covered: - Other AMD architectures (MI300 / gfx942, RDNA3), HIP with Triton below 3.6, and Windows ROCm. - `bnb.matmul_4bit` measured at or slightly below the Triton GEMV per call on gfx1151 (0.073 to 0.089 ms on the large shapes) but is not used here; routing HIP to it would be a separate change. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
Unsloth's 4bit path (
fast_dequantize,fast_gemv,matmul_lora,fast_linear_forwardand theLoRA_MLP/LoRA_QKV/LoRA_Wautograd functions) called the bitsandbytes C kernels through ctypes. That had three problems:absmax += offsetstep ran on the live stream. On any non-default stream (CUDA graph capture, vLLM, a side stream) the launches were unordered and could silently produce wrong weights.torch.compile(18 to 26 graph breaks per LoRA block,fullgraph=Truefails).This PR adds a fused Triton NF4 dequant (nested absmax decode, offset, NF4 lookup and scale in one launch) and a Triton batch-1 NF4 GEMV, registered with
torch.library.triton_op(CUDA) andcustom_op(HIP), so they launch on the current stream and are traceable.fast_dequantize/fast_gemvkeep their signatures.Accuracy
bitsandbytes.functional.dequantize_4bitand to the previousfast_dequantize(compared byte for byte, fp16 / bf16 / fp32, blocksize 64 / 128, nested and non-nested, odd and large shapes), eager and undertorch.compile. The nested absmax isfp32(code2[q] * absmax2) + offsetwith separate roundings. Both multiplies uselibdevice.mul_rn(no inline assembly): it is never contracted into an FMA when torch.compile re-emits the kernel with fp fusion on, and it flushes subnormal products to zero exactly like the bitsandbytes kernels, so the output matches even whencode * absmaxunderflows. HIP has nomul_rnand uses a plain multiply with fp fusion off.TRITON_INTERPRET=1works (plain multiply route).Kernels
unsloth/kernels/triton_launch.py). Triton's own launch path rebuilds the argument binding and specialization key on every call (about 12 us of CPU against about 5 us). The cache key covers every specialization Triton applies here (dtypes, 16 byte alignment, integers equal to 1 / divisible by 16 / int64, constexprs, launch options). It steps aside when a Triton launch hook is registered, andUNSLOTH_TRITON_FAST_LAUNCH=0turns it off.Dispatch and fallbacks
UNSLOTH_BNB_TRITON=0: the previous ctypes path, now on the live stream.torch.compiler.config.cache_key_tag. Inductor's FX graph cache keys atriton_opcall without the Triton source behind it, and Unsloth turns that cache on, so without the tag a warm cache served the previous kernel's compiled code after the kernel changed (reproduced on torch 2.13: an edited dequant kernel came back from the cache as the old one).torch.compile fixes in fast_lora
dXintoX. torch 2.11 rejects that mutation inside a compiled graph, so the aliasing is skipped while compiling. Eager still reuses the memory.LoRA_MLPbackward and the LoRA gradients can read stale memory (NaN). Before torch 2.11 the LoRA Functions stay opaque totorch.compile(a graph break, as before this PR). There is a regression test that fails without the guard on 2.10.out.addmm_(...)became an out-of-placeaddmmthat first copies the whole accumulator, and the in-place SwiGLU backward kernel made Inductor copy the saved gate / up activations before it ran.unsloth::addmm_(a custom op mutating its output, used only while compiling with grad disabled) keeps the accumulation in place, and while compiling the SwiGLU backward is the same math as torch ops, which Inductor fuses into one kernel that reuses those buffers. Eager is unchanged.Results
Base is main at the merge base, head is this branch. Same Colab VM per GPU, arms alternated in fresh processes. Colab and Kaggle images: torch 2.11.0+cu128, Triton 3.6.0, bitsandbytes 0.50.2, transformers 5.5.0. fp16 on T4 (no bf16), bf16 elsewhere, which is what Unsloth picks. SFT: QLoRA r=16 on all linear layers, bs 2, GA 3, length 512 (1B: 4 rounds x 40 steps, 8B: 2 rounds x 20 steps). Decode: batch 1, greedy, 128 new tokens.
Dequant and GEMV are per-call GPU time at Llama 8B shapes (4096x4096, 14336x4096, 4096x14336). Base SFT round-to-round spread was 0.7% to 4.5%. The Colab A100 VMs have slow host CPUs (1B SFT runs 0.63 s/step there, the same as L4, and 8B 1.3 s/step against 0.46 s/step on the RTX PRO 6000), so those runs are bound by Python overhead and the faster kernels do not show there. With CUDA graph timing, dequant followed by the training matmul (2048 tokens) is 1.02x to 1.24x faster than bitsandbytes' dequant followed by the same matmul on A100, 0.99x to 1.03x on L4, 1.00x to 1.04x on the RTX PRO 6000 and 1.02x to 1.05x on T4.
Decode at batch 1 and 4 against the merge base, with the launch plan (inference_ab: 5 repeats per arm in fresh processes, arms alternated, 128 new tokens, 4bit):
Prefill and peak memory are unchanged. Before the launch plan, batch 4 was 1.6% to 5.7% slower than main on the same GPUs. On T4, time to first token at batch 4 is bimodal on both arms (38 to 40 ms or 45 to 49 ms); over 10 repeats the means are 43.0 ms on main and 43.6 ms here.
Batch-1 decode with a launch plan per weight (the first call records the Triton launch, later tokens repeat it directly), 10 repeats per arm, against the merge base:
Every cell is within noise on prefill, time to first token and peak memory.
Greedy decode tokens can diverge from main after some steps because the GEMV sums in a different order than bitsandbytes' (both are within bf16 / fp16 rounding of the fp32 reference).
Compiled LoRA blocks (B200, torch 2.13, compiled main vs compiled head): dequant 4.1x to 5.5x, batch-1 GEMV 5.8x to 6.4x,
matmul_lora1.8x to 2.2x, LoRA MLP fwd + bwd 1.17x to 1.25x; graph breaks per block go from 18 to 26 on main to 0.Whole-model
torch.compileof the causal LM (QLoRA, no gradient checkpointing, length 1024, RTX PRO 6000, torch 2.11, 2 rounds per arm, ms per step):Eval loss after training stays within the run-to-run spread of main (8B: 1.1788 to 1.1795 across all arms, main alone 1.1788 / 1.1792).
Launch configs are per GPU only where it measured: on Triton 3.7, T4 and L4 run the Llama 8B MLP GEMV shapes at BLOCK_K 1024 and 2 warps (3% to 9% faster; on L4 the default trailed bitsandbytes at 4096x14336), and T4 dequantizes with 512 byte programs, 8 warps and word loads (5% to 7% faster). A100, B200 and the RTX PRO 6000 keep the defaults, which were best or within a few percent there; on Triton 3.6 every GPU keeps the defaults.
Memory
Local B200, torch 2.13, main vs this branch (MiB):
The cloud runs above give the same picture for SFT peak allocated (equal or up to 4 MiB lower).
Compared with plain PyTorch under Inductor and with torchao
code2 * absmax2 + offsetbecomes an FMA (80 mismatches at 14336x4096 in bf16, about 5% of the elements with fp32 output). It also reads each packed byte twice and decodes the absmax per element; it ran at 1.2x to 1.4x of bitsandbytes against 1.7x to 2.2x here (B200).combo_kernels=True(withcombo_kernel_per_subkernel_blocksandbenchmark_combo_kernel) only merges independent kernels: it fused the q / k / v dequants into one launch (1.1x of bitsandbytes against 2.5x here) and did not change a single dequant, GEMV or the LoRA backward.F.linear.Tests
New:
tests/test_nf4_triton_dequant.py,tests/test_nf4_triton_gemv.py,tests/test_bnb_integration_compile.py,tests/test_triton_launch.py(bit-identity for every launch config, side streams, CUDA graph capture and replay, 0 graph breaks andfullgraph=True, compiled vs eager, direct launch for every specialization and with launch hooks, fallbacks, the torch 2.10 stale memory case).UNSLOTH_BNB_TRITON=0compute-sanitizer --tool memcheckover every dequant launch config and both GEMV kernels on ragged shapes reports no memory errors.The focused suite also passed on each GPU in the table above before the
mul_rnchange (360 passed with the kernels, 313 passed withUNSLOTH_BNB_TRITON=0), and on a Kaggle 2x T4 box a weight on the second GPU dequantizes byte-identical to bitsandbytes.Tests at the final kernels (d971bc6, focused NF4 suite plus
test_fast_gemv_dispatch.py):UNSLOTH_BNB_TRITON=0test_triton_launch.pyCUDA_VISIBLE_DEVICES=0,1The one AMD failure was
test_exact_with_fp_fusion_on_or_off[fusion_on], which forces fp fusion on. ROCm has nolibdevice.mul_rn, so that forced launch contracts to an FMA; the HIP route never launches with fusion on (eager passesfp_fusion=False, compiled graphs keep the op opaque), and every other dequant, GEMV and compile test matched bitsandbytes there. The test now skips that case whenmul_rnis unavailable.torch 2.6 found two problems, both fixed here: Triton 3.2 has no
tl.gather, and its JIT resolves every attribute in a kernel body while hashing dependencies (dead constexpr branches included), so every NF4 launch raised; the register-table gather now lives in a helper that falls back to the L1 table load there. Triton 3.2 also returns compiled kernels withoutpacked_metadata, so the direct launch path stays off and every launch goes through Triton (correct, just not faster). The launch module also imports on CPU-only torch builds now (no CUDA stream binding there).Decode quality with the batch-1 Triton GEMV (it matches bitsandbytes to fp32 accumulation noise, not bitwise): teacher-forced decode NLL over 24 wikitext prompts x 80 tokens, every token a q_len=1 forward, main vs this PR paired: Llama 3.2 1B bnb-4bit 3.34510 vs 3.34512 (95% CI of the difference -0.0019 to +0.0020), Qwen3 0.6B 4bit 3.79589 vs 3.79151 (-0.0076 to -0.0013). Rerun on Colab at be01a89 (the per-weight GEMV launch plan repeats the same kernel, so the math is unchanged), main vs this PR: Llama 3.2 1B -0.0006 (-0.0030 to +0.0015) on the RTX PRO 6000; Qwen3 0.6B +0.0014 (-0.0012 to +0.0042) on the RTX PRO 6000, -0.0015 on L4, +0.0000 on A100, -0.0004 on T4.
Not covered: Intel XPU hardware (XPU keeps the previous code), torch 2.8 / 2.9, and Windows GPUs (no Windows GPU runner; TheRock ROCm on Windows ships no Triton, so it keeps the bitsandbytes path).