Repository navigation
fix(kernels): pack strided inputs, bind devices, widen offsets, handle M=0 (#4042) - #4047
Merged
Merged
Conversation
…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.
This was referenced Nov 14, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 — isstrided.
reshape(-1, K)succeeds and returns a strided view; kernels that takedata_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;main)bitblas.py:865reshaped and passed the strided view'sdata_ptr()(bitblas.py:889-899).bitblas.py:875packs the operand; the dtype cast above already copies, so this is a no-op for bf16.exl3.py:135usedx.view(-1, in_features); the kernels assumed packed rows.exl3.py:139packs;hadamard.cu,hgemm.cu, andlibtorch/linear.cppnow reject a strided operand.machete.py:314/machete_awq.py:212passed the strided view.machete.py:317/machete_awq.py:215pack first.paroquant.py:593fed the strided view to the fused rotation.paroquant.py:595packs 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 --> HGGUF 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;The ggml CUDA bridge runs on its own stream and its backend calls
cudaSetDevice. It now synchronizes the caller's stream before copying theinput 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;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_Kfused matmuls, and the NVFP4 pack/decode kernels. EXL3's Hadamard row offset
uses
size_t.launch_linear_f32andlaunch_linear_fusedintt_blockfloat_cuda.cuchunk rows sogridDim.ystays 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;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"]N/ELEMENTS(GGUF wide-output restore),M(W4A_grouped_fp8_gemm), andM/PADDED_M(NVFP4) are runtime ints withdo_not_specialize.3. Failure and ambiguity contract
cuda:1, current device 0cuda:1through ggmlrows * K > 2^31gridDim.y > 65535invalid argument4. Change inventory
bitblas.py,machete.py,machete_awq.py,paroquant.py,exl3.pyhadamard.cu,hgemm.cu,libtorch/linear.cppgguf_triton.py,gguf_cpp.pyqqq_triton.py,w4a_triton.py,w4a_nvfp4_triton.py,gguf_triton.py,hadamard.cu,tt_blockfloat_cuda.cuhadamard.cpp,hadamard_utils.py,nf12.pygguf_triton.py,w4a_triton.py,w4a_nvfp4_triton.pydocs/kernel-input-contiguity.md,README.md, 6 test files5. Validation
Hardware: RTX 4090
GPU-d458708b-c760-bbf1-08fb-8b8803a2157d(nvidia-smiindex 3); a second RTX 4090
GPU-1ece7ec2…(index 1) only for the multi-GPUtest; AMD Radeon AI PRO R9700 with
HIP_VISIBLE_DEVICES=2. The RTX 5090 wasnever used.
ruff check gptqmodel docs/eora tests setup.py→ All checks passed!Fail-before / pass-after (checked against
origin/mainin a separate worktree)origin/main)CUDA error: invalid argument(0, 128)returnedRuntimeError: cannot reshape tensor of 0 elements(0, 256)returnedapply_online_hadamard, emptyhad_r_128stridedRuntimeError: requires a contiguous input-1)11.3125RuntimeError: rotation tensors must be contiguouscuda:1(Q4_K/Q5_K/Q6_K/Q1_0)ValueError: Pointer argument cannot be accessed from Tritoninvalid argumentExact commands and results
CUDA (
CUDA_VISIBLE_DEVICES=GPU-d458708b…):pytest -q tests/test_hadamard_empty_input.py→ 9 passedpytest -q tests/kernels/test_kernel_input_contiguity.py→ 2 passedpytest -q tests/kernels/test_triton_per_m_recompile.py→ 3 passedpytest -q tests/kernels/test_triton_int32_offsets.py→ 1 passedpytest -q tests/kernels/test_gguf_triton_multi_gpu.py(two GPUs) → 4 passedpytest -q tests/kernels/test_paroquant.py→ 48 passed, 1 skippedpytest -q tests/kernels/test_exllamav3_kernel.py tests/kernels/test_gguf_triton_bias_epilogue.py→ 45 passedpytest -q tests/test_tt_blockfloat_cuda.py tests/test_tt_blockfloat_out_axis.py→ 106 passedpytest -qon the existing GGUF Triton range/scale/empty suites → 137 passedpytest - streams:test_gguf_triton_cache_invalidation.py test_selection.py→ 133 passed, 39 skippedROCm (
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)6. Limitations / not live-tested here
llama-cpp-pythonggml bridge is not installed in this environment, sothe
gguf_cpp.pycurrent-device restore and stream-ordering changes aresource-reviewed and compile-checked but not executed live.
covered by stub-kernel contract tests rather than a live GEMM.
launch_linear_fused) chunking iscompile-checked; the fp32 path is tested at m=2,097,152.
tests/kernels/test_paroquant.py::test_paroquant_identity_forward_matches_awq_torchis order-dependent on unseeded RNG; it also fails on
origin/mainwhen runafter
tests/kernels/test_gguf_triton_bias_epilogue.py, so it is not causedby this change.