Skip to content

fix(kernels): pack strided inputs, bind devices, widen offsets, handle M=0 (#4042) - #4047

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4042
Nov 14, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4042

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4042

TL;DR

Kernel-correctness pass over the packed-row inference backends: non-contiguous
activations are packed before BitBLAS/EXL3/Machete/ParoQuant read them, Triton
launches bind the operand's device, ggml restores the process's current device
and orders with the caller's stream, row offsets are 64-bit, empty operands
short-circuit, and the token count is no longer a Triton compile-time constant.
Reference page: docs/kernel-input-contiguity.md
(linked from README.md).

1. The problem

hidden_states[:, -1:, :] with batch > 1 — every batched decode step — is
strided. reshape(-1, K) succeeds and returns a strided view; kernels that take
data_ptr() or compute dense offsets then read the wrong rows.

flowchart TD
    A["x: [B, 1, K] decode slice (strided)"] --> B["reshape(-1, K) returns a strided view"]
    B --> C{"backend"}
    C -- BitBLAS --> D["_invoke_bitblas_matmul passes data_ptr() to the prebuilt CUDA library"]
    C -- EXL3 --> E["had_r_128 / hgemm / bc read packed rows"]
    C -- Machete --> F["machete_mm reads packed rows"]
    C -- ParoQuant --> G["apply_paroquant_rotation launch config"]
    D --> X["silently wrong rows (rel err 1.30)"]
    E --> Y["silently wrong rows (rel err 1.36)"]
    F --> Z["silently wrong rows"]
    G --> W["RuntimeError: expects contiguous floating-point input"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class X,Y,Z,W failure;
Loading
Kernel path Before (main) Current
BitBLAS fp16 bitblas.py:865 reshaped and passed the strided view's data_ptr() (bitblas.py:889-899). bitblas.py:875 packs the operand; the dtype cast above already copies, so this is a no-op for bf16.
EXL3 fp16 exl3.py:135 used x.view(-1, in_features); the kernels assumed packed rows. exl3.py:139 packs; hadamard.cu, hgemm.cu, and libtorch/linear.cpp now reject a strided operand.
Machete machete.py:314 / machete_awq.py:212 passed the strided view. machete.py:317 / machete_awq.py:215 pack first.
ParoQuant paroquant.py:593 fed the strided view to the fused rotation. paroquant.py:595 packs first.

2. The new flow

flowchart TD
    A["x: [B, 1, K] decode slice (strided)"] --> B["reshape(-1, K).contiguous()"]
    B --> C{"backend"}
    C -- BitBLAS --> D["_invoke_bitblas_matmul: enter the module device, then data_ptr()"]
    C -- EXL3 --> E["had_r_128 / hgemm / bc + TORCH_CHECK(is_contiguous)"]
    C -- Machete --> F["machete_mm"]
    C -- ParoQuant --> G["fused rotation"]
    D --> H["correct output"]
    E --> H
    F --> H
    G --> H
Loading

GGUF multi-GPU and streams

flowchart TD
    A["GGUFTritonKernel.forward(x on cuda:1)"] --> B["_launch / _launch_with_meta"]
    B --> C{"with torch.cuda.device(x.device)"}
    C --> D["kernel launch in the operand's context"]
    D --> E["cast and restore kernels use the same guard"]
    E --> F["result on cuda:1"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    B -. "before: current device cuda:0" .-> X["ValueError: Pointer argument cannot be accessed from Triton"]
    class X failure;
Loading

The ggml CUDA bridge runs on its own stream and its backend calls
cudaSetDevice. It now synchronizes the caller's stream before copying the
input and restores the previous current device (gguf_cpp.py:708,
gguf_cpp.py:799).

64-bit offsets and launch limits

flowchart LR
    A["row = tl.program_id(0)"] --> B["int32 row * K"]
    B --> C{"rows * K > 2^31?"}
    C -- No --> D["correct"]
    C -- Yes --> X["wrapped address: wrong rows"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class X failure;
Loading

Row indices are cast before the multiply in QQQ _quantize_rows, W4A
_token_fp8_quant/_grouped_fp8_gemm, the GGUF cast kernel and Q4_K/Q6_K
fused matmuls, and the NVFP4 pack/decode kernels. EXL3's Hadamard row offset
uses size_t. launch_linear_f32 and launch_linear_fused in
tt_blockfloat_cuda.cu chunk rows so gridDim.y stays below 65535.

Empty operands and per-token recompiles

flowchart TD
    A["x.numel() == 0"] --> B{"where"}
    B -- native Hadamard --> C["return empty output before the launch"]
    B -- Torch butterfly --> D["return empty_like before reshape"]
    B -- apply_online_hadamard --> E["return x unchanged"]
    B -- NF12Linear --> F["empty_linear_output before the rotation"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    C -. "before: CUDA error invalid argument" .-> X["crash"]
    D -. "before: RuntimeError ambiguous reshape" .-> X
    class X failure;
Loading
flowchart TD
    A["forward with M tokens"] --> B{"M declared constexpr?"}
    B -- Yes --> C["compile a new kernel variant for this M"]
    C --> D["40-340 ms first call"]
    B -- No --> E["reuse one variant"]
    E --> F["2.3 ms warm"]
Loading

N/ELEMENTS (GGUF wide-output restore), M (W4A _grouped_fp8_gemm), and
M/PADDED_M (NVFP4) are runtime ints with do_not_specialize.

3. Failure and ambiguity contract

Situation Before After
Strided activation into a packed-row kernel wrong rows or launch error packed at the module boundary; native entry points fail closed
Layer on cuda:1, current device 0 Triton pointer error device guard
Forward on cuda:1 through ggml current device leaks to 1 saved and restored
ggml input produced on a non-default stream stale copy, wrong result caller stream synchronized before the copy
rows * K > 2^31 wrapped addresses 64-bit row offsets
gridDim.y > 65535 invalid argument row chunking
Zero-element Hadamard operand crash empty output
New token count full recompile one compiled variant

4. Change inventory

Area Files Purpose
Activation packing bitblas.py, machete.py, machete_awq.py, paroquant.py, exl3.py pack before packed-row kernels
Native checks hadamard.cu, hgemm.cu, libtorch/linear.cpp fail closed on strided operands
GGUF devices/streams gguf_triton.py, gguf_cpp.py device guard, current-device restore, stream ordering
Offsets/limits qqq_triton.py, w4a_triton.py, w4a_nvfp4_triton.py, gguf_triton.py, hadamard.cu, tt_blockfloat_cuda.cu 64-bit offsets, chunked grids
Empty inputs hadamard.cpp, hadamard_utils.py, nf12.py short-circuit before launch/rotation
Recompiles gguf_triton.py, w4a_triton.py, w4a_nvfp4_triton.py runtime token count
Docs/tests docs/kernel-input-contiguity.md, README.md, 6 test files contracts and regression coverage

5. Validation

Hardware: RTX 4090 GPU-d458708b-c760-bbf1-08fb-8b8803a2157d (nvidia-smi
index 3); a second RTX 4090 GPU-1ece7ec2… (index 1) only for the multi-GPU
test; AMD Radeon AI PRO R9700 with HIP_VISIBLE_DEVICES=2. The RTX 5090 was
never used.

ruff check gptqmodel docs/eora tests setup.py → All checks passed!

Fail-before / pass-after (checked against origin/main in a separate worktree)

Case Before (origin/main) After
native Hadamard, M=0 CUDA error: invalid argument (0, 128) returned
Torch butterfly, M=0 RuntimeError: cannot reshape tensor of 0 elements (0, 256) returned
apply_online_hadamard, empty same reshape error empty tensor
BitBLAS operand (stub kernel) strided operand contiguous
Machete operand (stub kernel) strided operand contiguous
EXL3 strided batch slice mismatch vs torch reference matches
EXL3 had_r_128 strided no error, wrong rows RuntimeError: requires a contiguous input
EXL3 Hadamard, rows·cols = 2^32 last row never written (sentinel -1) last row DC 11.3125
ParoQuant strided slice RuntimeError: rotation tensors must be contiguous matches contiguous
GGUF Triton on cuda:1 (Q4_K/Q5_K/Q6_K/Q1_0) ValueError: Pointer argument cannot be accessed from Triton matches FP64 oracle
QQQ, rows·K = 2^31 + 2048 last row wrong codes exact match
block-float fp32, m=2,097,152 invalid argument matches reference
GGUF restore compile count over M∈{16,17,33,64} 4 variants 1
W4A FP8 GEMM compile count 4 variants 1
NVFP4 pack compile count 4 variants 1

Exact commands and results

CUDA (CUDA_VISIBLE_DEVICES=GPU-d458708b…):

  • pytest -q tests/test_hadamard_empty_input.py → 9 passed
  • pytest -q tests/kernels/test_kernel_input_contiguity.py → 2 passed
  • pytest -q tests/kernels/test_triton_per_m_recompile.py → 3 passed
  • pytest -q tests/kernels/test_triton_int32_offsets.py → 1 passed
  • pytest -q tests/kernels/test_gguf_triton_multi_gpu.py (two GPUs) → 4 passed
  • pytest -q tests/kernels/test_paroquant.py → 48 passed, 1 skipped
  • pytest -q tests/kernels/test_exllamav3_kernel.py tests/kernels/test_gguf_triton_bias_epilogue.py → 45 passed
  • pytest -q tests/test_tt_blockfloat_cuda.py tests/test_tt_blockfloat_out_axis.py → 106 passed
  • pytest -q on the existing GGUF Triton range/scale/empty suites → 137 passed
  • pytest - streams: test_gguf_triton_cache_invalidation.py test_selection.py → 133 passed, 39 skipped

ROCm (HIP_VISIBLE_DEVICES=2):

  • pytest -q tests/test_hadamard_empty_input.py tests/kernels/test_kernel_input_contiguity.py tests/kernels/test_triton_int32_offsets.py tests/kernels/test_triton_per_m_recompile.py → 13 passed, 2 skipped (W4A FP8/NVFP4 are CUDA-only)
  • EXL3 Hadamard check + ParoQuant strided test → 2 passed, 2 skipped

6. Limitations / not live-tested here

  • The llama-cpp-python ggml bridge is not installed in this environment, so
    the gguf_cpp.py current-device restore and stream-ordering changes are
    source-reviewed and compile-checked but not executed live.
  • BitBLAS and Machete are not installed (no SM90 here), so their packing fix is
    covered by stub-kernel contract tests rather than a live GEMM.
  • The block-float fused fallback (launch_linear_fused) chunking is
    compile-checked; the fp32 path is tested at m=2,097,152.
  • tests/kernels/test_paroquant.py::test_paroquant_identity_forward_matches_awq_torch
    is order-dependent on unseeded RNG; it also fails on origin/main when run
    after tests/kernels/test_gguf_triton_bias_epilogue.py, so it is not caused
    by this change.

…handle M=0 (#4042)

Kernel-correctness pass over the packed-row inference backends:

- Pack the activation before BitBLAS, EXL3, Machete and ParoQuant consume it.
  `reshape(-1, K)` returns a strided view for `hidden_states[:, -1:, :]`, which
  those kernels interpreted as packed rows (silent wrong output or a launch
  error). Add `TORCH_CHECK(is_contiguous())` to the EXL3 Hadamard/hgemm/bc
  entry points so a future caller fails closed.
- Enter the operand's device for every GGUF Triton launch (cast, restore, and
  the fused matmuls) and save/restore the process's current device around the
  ggml CUDA path. Synchronize the caller's stream before ggml copies the input
  from `data_ptr()`.
- Compute Triton row offsets in 64-bit (QQQ, W4A, GGUF, NVFP4), use `size_t`
  for the EXL3 Hadamard row offset, and chunk rows for the block-float fp32 and
  fused launches so `gridDim.y` stays below 65535.
- Short-circuit zero-element Hadamard operands in the native bindings, the
  Torch butterfly and `apply_online_hadamard`, and check empty rows before
  NF12's online rotation.
- Make the token count a runtime Triton argument (with `do_not_specialize`)
  for the GGUF wide-output restore kernel, the W4A FP8 GEMM, and the NVFP4
  pack/decode/accumulate kernels instead of recompiling per M.

Adds regression tests with fail-before/pass-after evidence, a reference page
(docs/kernel-input-contiguity.md) linked from README, and Mermaid flows.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant