Skip to content

NF4 bitsandbytes GEMM gate: return before its lazy setup under torch.compile - #14608

Merged
danielhanchen merged 2 commits into
mainfrom
nf4-bnb-gemm-compile-guard
Oct 22, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
nf4-bnb-gemm-compile-guard

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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

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

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

Loading
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