Skip to content

Fused Triton NF4 dequant and GEMV: bit-exact, stream-safe, torch.compile traceable - #12113

Merged
danielhanchen merged 35 commits into
mainfrom
nf4-triton-kernels
Oct 2, 2026
Merged

danielhanchen merged 35 commits into
mainfrom
nf4-triton-kernels

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Unsloth's 4bit path (fast_dequantize, fast_gemv, matmul_lora, fast_linear_forward and the LoRA_MLP / LoRA_QKV / LoRA_W autograd functions) called the bitsandbytes C kernels through ctypes. That had three problems:

  1. It passed an import-time stream snapshot to the C kernels while the absmax += offset step 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.
  2. ctypes is a hard graph break, so none of it could be traced by torch.compile (18 to 26 graph breaks per LoRA block, fullgraph=True fails).
  3. A double quantized dequant took three launches plus Python overhead per call.

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) and custom_op (HIP), so they launch on the current stream and are traceable. fast_dequantize / fast_gemv keep their signatures.

Accuracy

  • The dequant is bit-identical to bitsandbytes.functional.dequantize_4bit and to the previous fast_dequantize (compared byte for byte, fp16 / bf16 / fp32, blocksize 64 / 128, nested and non-nested, odd and large shapes), eager and under torch.compile. The nested absmax is fp32(code2[q] * absmax2) + offset with separate roundings. Both multiplies use libdevice.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 when code * absmax underflows. HIP has no mul_rn and uses a plain multiply with fp fusion off. TRITON_INTERPRET=1 works (plain multiply route).
  • The GEMV reduces per quantization block before scaling. It is checked against an fp32 reference and has lower error than bitsandbytes' GEMV at every measured shape.
  • QLoRA training losses are bit-identical to main on every GPU below (1B and 8B).

Kernels

  • Dequant: one launch, int32 loads of the packed bytes, a register or L1 codebook lookup, per GPU launch configs.
  • GEMV: an int32 word kernel before Triton 3.7 (one row per program), a byte kernel from Triton 3.7 on. Eager decode now takes the Triton GEMV on CUDA; HIP keeps bitsandbytes' GEMV before Triton 3.7.
  • Eager launches go straight to the cached compiled kernel (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, and UNSLOTH_TRITON_FAST_LAUNCH=0 turns it off.
  • Batch > 1 decode dequantizes every weight into the scratch buffer once per token, and on typical hosts it is CPU bound. The first call per weight plans the launch; later calls repeat it after checking the weight pointer, the absmax tensor and the dtype (13 us of CPU per call against 36 us for main's ctypes path). The plan is dropped on deepcopy and pickling.

Dispatch and fallbacks

  • XPU, no Triton, FP4, or UNSLOTH_BNB_TRITON=0: the previous ctypes path, now on the live stream.
  • A Triton JIT failure falls back to ctypes for the process, except while compiling, on OOM, or on a Dynamo exception.
  • The global scratch buffer is only used on the default stream and never while compiling or capturing.
  • The kernel files' hashes go into torch.compiler.config.cache_key_tag. Inductor's FX graph cache keys a triton_op call 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

  • The MLP / QKV backward wrote dX into X. torch 2.11 rejects that mutation inside a compiled graph, so the aliasing is skipped while compiling. Eager still reuses the memory.
  • On torch 2.10 Inductor miscompiles the traced LoRA_MLP backward and the LoRA gradients can read stale memory (NaN). Before torch 2.11 the LoRA Functions stay opaque to torch.compile (a graph break, as before this PR). There is a regression test that fails without the guard on 2.10.
  • Once the dequant stops breaking the graph, the LoRA Functions are traced, and two in-place steps turned into copies: out.addmm_(...) became an out-of-place addmm that 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.

GPU Dequant GEMV SFT 1B SFT 8B Decode 1B Decode 8B
T4 (Colab, high RAM) 1.07x to 1.65x 1.00x to 1.22x 1.022x 1.077x 1.047x 1.127x
L4 1.02x to 1.75x 1.10x to 1.25x 0.971x 1.055x 1.048x 1.061x
A100 40GB 0.97x to 1.21x 0.94x to 1.26x 0.980x 0.991x 1.066x 1.093x
A100 80GB 1.10x to 1.33x 1.07x to 1.25x 0.996x 0.973x 1.045x 1.082x
RTX PRO 6000 (Colab G4) 1.04x to 1.34x 1.32x to 1.45x 0.995x 1.017x 1.081x 1.090x
B200 (shared, noisy) 1.37x to 1.90x 1.19x to 1.36x 1.001x 1.066x 1.080x

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):

GPU Llama 3.2 1B b1 Llama 3.2 1B b4 Qwen3 0.6B b1 Qwen3 0.6B b4
T4 +5.3% +11.3% +4.6% +20.4%
L4 +5.8% +17.3% +1.6% +16.6%
A100 40GB +4.6% +17.8% +3.2% +17.9%
RTX PRO 6000 +7.7% +14.9% +5.2% +15.4%

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:

GPU Llama 3.1 8B b1 Llama 3.2 1B b1 Llama 3.2 1B b4
T4 +24.7% (+27.1% rerun) +16.2% +14.1% (+16.5% rerun)
L4 +17.2% +18.1% +18.2%
A100 +19.4% +17.3% +17.5%
RTX PRO 6000 +18.5% +17.6% +15.3%

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_lora 1.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.compile of the causal LM (QLoRA, no gradient checkpointing, length 1024, RTX PRO 6000, torch 2.11, 2 rounds per arm, ms per step):

Model main this PR before the copy fix this PR
Llama 3.2 1B 84.5 57.8 56.8 (1.49x)
Llama 3.1 8B 256.4 260.5 250.8 (1.022x)

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):

Run Peak allocated Peak reserved Dequant scratch buffers
SFT 1B 1698 / 1697 1728 / 1726 33.0 / 32.0
SFT 8B 6590 / 6586 6648 / 6648 115.5 / 112.0
Decode 1B 1098 / 1098 1118 / 1118 0 / 0
Decode 8B 5724 / 5724 5738 / 5736 0 / 0

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

  • A plain PyTorch NF4 dequant written in bitsandbytes' order compiles to one fused Inductor kernel, but it is not bit-exact: Inductor compiles with FP fusion on, so code2 * absmax2 + offset becomes 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 (with combo_kernel_per_subkernel_blocks and benchmark_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.
  • torchao's NF4 is a different format (4 decimal codebook, linear int8 scale quantization, bf16 math) and pure PyTorch; compiled, it reached about bitsandbytes' dequant speed and 0.27x to 0.53x for 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 and fullgraph=True, compiled vs eager, direct launch for every specialization and with launch hooks, fallbacks, the torch 2.10 stale memory case).

torch Triton kernels on UNSLOTH_BNB_TRITON=0
2.6.0 (transformers 4.57.6, TRL 0.22.2, PEFT 0.18.0, Colab L4) 3.2.0 295 passed, 1 skipped (focused suite)
2.7.1 (bitsandbytes 0.45.5, transformers 4.57.6) 3.3.1 389 passed 342 passed
2.10 (Kaggle pins) 3.6.0 390 passed 343 passed
2.11 3.6.0 390 passed 343 passed
2.12.1 3.7.1 390 passed 343 passed
2.13 3.7.1 390 passed 343 passed
2.14 3.8.0 390 passed 343 passed

compute-sanitizer --tool memcheck over 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_rn change (360 passed with the kernels, 313 passed with UNSLOTH_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):

GPU kernels on UNSLOTH_BNB_TRITON=0 with test_triton_launch.py
T4 (Colab) 332 passed 285 passed, 47 skipped 365 passed
2x T4 (Kaggle), one GPU and CUDA_VISIBLE_DEVICES=0,1 332 passed, 332 passed 285 passed, 47 skipped 365 passed, 365 passed
L4 332 passed 285 passed, 47 skipped 365 passed
A100 332 passed 285 passed, 47 skipped 365 passed
RTX PRO 6000 (Colab G4) 332 passed 285 passed, 47 skipped 365 passed
AMD Radeon 8060S (gfx1151, ROCm, AMD CI) 292 passed, 4 skipped, 1 failed
AMD Radeon 8060S at 9ccca04 (head and merged with main) 327 passed, 10 skipped, 0 failed

The one AMD failure was test_exact_with_fp_fusion_on_or_off[fusion_on], which forces fp fusion on. ROCm has no libdevice.mul_rn, so that forced launch contracts to an FMA; the HIP route never launches with fusion on (eager passes fp_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 when mul_rn is 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 without packed_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).

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 27, 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-02T12:07:14.666865Z 4595b29 Manual request
🔒 Security Review ✅ Completed 2026-09-28T13:53:54.085506Z 86d965c 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.

…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.
danielhanchen and others added 4 commits September 27, 2026 10:47
…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.
@mahiatlinux
mahiatlinux self-requested a review September 28, 2026 20:26
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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: be01a8949d

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

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%).
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: c851d92c8c

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

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9ccca047e3

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

…n it

T4 trains in fp16 (bf16 requests fall back), and Dynamo cannot trace the
bf16 kernel launch there.
@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. You're on a roll.

Reviewed commit: 4595b29737

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

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 2, 2026
@danielhanchen
danielhanchen merged commit 338d23f into main Oct 2, 2026
@danielhanchen
danielhanchen deleted the nf4-triton-kernels branch October 2, 2026 13:32
JoshuaL3000 pushed a commit to JoshuaL3000/unsloth that referenced this pull request Oct 4, 2026
…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>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 21, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants