Skip to content

fix(marlin): keep the checkpoint bias out of the tile layout and the output dtype - #4657

Merged
Qubitium merged 1 commit into
mainfrom
fix/awq-marlin-bias-epilogue
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/awq-marlin-bias-epilogue

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

TL;DR

MarlinLinear and AwqMarlinLinear rewrote their non-quantized bias twice
(padded/permuted in post_init, narrowed to the activation dtype in forward).
The native kernel adds the bias to its FP32 accumulator, so both writes only
destroyed checkpoint state. The kernel now stages the bias as FP32 and the
registered buffer stays the checkpoint tensor; net diff is one commit, 9 files.

1. The problem

flowchart TD
    A["checkpoint bias FP32 -65536"] --> B["loader: MODEL_DTYPE_BUFFERS = (bias,)"]
    B --> C["bias narrowed to FP16 = -inf"]
    C --> D["post_init: padded + permuted in place"]
    D --> E["forward: self.bias.data = to(x.dtype)"]
    E --> F["kernel stages half, adds num2float(...) to the FP32 accumulator"]
    F --> G["single visible cast"]
    D -. "state_dict() / save()" .-> H["publishes the runtime tile layout"]:::fail
    classDef fail fill:#ffdddd,stroke:#cc0000,color:#660000
Loading
Mechanism (before) Location
bias stored in the scale/compute dtype, then permuted in place marlin_awq.py:352, marlin.py:478
forward assigned self.bias.data = ...to(x.dtype) marlin_awq.py:388, marlin.py:511
inherited MODEL_DTYPE_BUFFERS = ("bias",) narrowed a wide checkpoint nn_modules/qlinear/__init__.py
kernel staged b_bias as scalar_t marlin_template.h (sh_bias, FragS frag_bias)

2. The new flow

flowchart TD
    A["checkpoint bias, source dtype"] --> B["Marlin: MODEL_DTYPE_BUFFERS = ()"]
    B --> C["post_init records _marlin_bias_padding"]
    C --> D["self.bias keeps checkpoint order and dtype"]
    D --> E["_kernel_bias: widen to FP32, pad, permute (call-local)"]
    E --> F["gptq_marlin_gemm(bias=FP32)"]
    F --> G["kernel: FP32 stage, add to FP32 accumulator"]
    G --> H["one round to the visible dtype"]
    D -. "state_dict() / save()" .-> I["still the checkpoint tensor"]:::ok
    classDef ok fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

3. Kernel change

Stage Before After
sh_bias_size thread_n_blocks * 16 / 8 int4 thread_n_blocks * 16 / 4 int4
fetch one cp_async4 per 8-column group two cp_async4 of four FP32 columns
fragment FragS frag_bias[2][4] (half2) Vec<float, 2> frag_bias[2][4]
epilogue Dtype::num2float(scalar_t) FP32 value directly

gptq_marlin.cu widens a 16-bit b_bias to FP32 per call and records the
temporary on the stream, so existing callers keep their ABI.

4. Fusion

A fused Marlin executor concatenates whole aligned N tiles. _FusionGroup
now pads each source bias to its own tile width before concatenating and
records _marlin_bias_padding = (numel, numel); _share_operands publishes
already-padded slices, and remove() restores the checkpoint-order buffer with
the padded width so the next standalone launch pads exactly once.

5. Failure and ambiguity contract

Situation Before After
FP32 -65536, FP16 forward buffer becomes -inf, output -inf finite cancellation
FP32 65520 / -1e-45 inf / 0 preserved
save after a forward runtime tile layout checkpoint tensor
tile-misaligned N padding baked into the buffer padding only in the launch operand

Out of scope: Machete/Swordfish add the bias after the kernel rounds the product
and intentionally keep the activation width.

6. Change inventory

Area File Purpose
kernel gptqmodel_ext/marlin/marlin_template.h FP32 bias stage and epilogue
kernel host gptqmodel_ext/marlin/gptq_marlin.cu widen/validate the operand, stream lifetime
modules nn_modules/qlinear/marlin.py, marlin_awq.py MODEL_DTYPE_BUFFERS = (), _kernel_bias, no in-place rewrite
fusion models/fusion.py per-source padding, restore on remove()
docs docs/marlin-bias-epilogue.md + README.md, docs/README.md reference page
tests tests/kernels/test_marlin_bias_epilogue.py, tests/test_marlin_jit.py regression and schema updates

7. Tests / guarantees

Test Invariant
test_marlin_post_init_keeps_checkpoint_bias storage keeps source dtype, order and value; padding is metadata only
test_marlin_forward_cancels_wide_bias finite cancellation in FP16, buffer bit-identical after two forwards
test_marlin_bias_columns_follow_marlin_order launch operand equals the padded Marlin permutation
test_marlin_padded_bias_operand_is_the_tile_permutation padding appears only in the launch operand
test_marlin_bias_derivation_is_call_local nothing widened/permuted is retained
tests/test_marlin_jit.py storage and launch dtypes stay in step

8. Validation

cd tests
python -m pytest kernels/test_marlin_bias_epilogue.py -q
# 42 passed

python -m pytest test_marlin_jit.py module_tree/test_fusion_kernel_backends.py -q
# 221 passed, 34 skipped (excluding two pre-existing failures below)

python -m pytest kernels/test_awq_machete_marlin.py kernels/test_marlin_fp32_schedule.py \
  kernels/test_marlin_quant_dtype_boundaries.py test_kernel_dispatch_caching.py -q
# 203 passed

Red evidence on unmodified main (959334876): the new
test_marlin_bias_epilogue.py fails at the intended assertions (for example
post_init returns torch.float16 -inf for an FP32 -65536 source). The
JIT extension rebuilds and loads on the tested CUDA host.

Pre-existing failures reproduced on unmodified main and unrelated to this
change: test_marlin_cuda_smoke_build_and_forward (RuntimeError: For act_order, num_groups must be > 1) and
test_every_registered_gptq_awq_kernel_has_an_explicit_fusion_contract
(AwqGEMVTorchLinear has no fusion spec).

The AWQ/GPTQ Marlin launch paths are validated on one NVIDIA CUDA host; ROCm
does not build this extension, so no ROCm claim is made.

9. Reviewer notes

  • The FP32 stage doubles the bias shared-memory footprint per tile
    (thread_n_blocks * 16 / 8 → /4 int4). It is covered by the existing
    sh_size_b_red_min/max selection and the get_kernel_cache_size formula,
    which already reserves tb_n * 2 bytes.
  • A 16-bit b_bias still allocates one FP32 temporary per call. Callers inside
    the repo now pass FP32, so that path only serves external ABI users.

…output dtype

AwqMarlinLinear and MarlinLinear rewrote their non-quantized bias twice.
post_init replaced the registered buffer with the padded, Marlin-permuted
copy, so a save published a runtime layout instead of the checkpoint tensor,
and forward assigned the buffer to the activation dtype, so the first FP16
forward turned a finite FP32 -65536 into -inf permanently. Both classes also
inherited MODEL_DTYPE_BUFFERS = ("bias",), which narrowed a wide checkpoint
bias in the loader before any forward ran. The native kernel always added the
bias to its FP32 accumulator, so neither conversion was ever needed.

The kernel now stages the bias as FP32 (two int4 slots per 8-column group
instead of one) and adds it directly to the accumulator before the single
visible cast. A half/bfloat16 caller is widened once per call on the stream,
so existing callers keep working. post_init only records the tile padding;
the padded, permuted FP32 operand is derived per launch and never retained.
Fusion pads each source term before concatenating, and remove() restores the
checkpoint-order buffer so a later standalone forward pads exactly once.

Covers FP32 and BF16 sources at +-65504, +-65520, +-65536, +-100000, -1e-45
and 0 for post_init storage, forward cancellation against an independent FP64
oracle, storage dtype and order, aligned and tile-misaligned shapes, and
call-local derivation, for both the GPTQ and AWQ Marlin layers.
@Qubitium
Qubitium merged commit bf5adeb into main Nov 17, 2026
9 checks passed
@Qubitium
Qubitium deleted the fix/awq-marlin-bias-epilogue branch November 17, 2026 08:57
Qubitium added a commit that referenced this pull request Nov 17, 2026
Fix the test-side fallout of #4716, #4657, #4627 and #4508. Only entries
that fail on this sm_80 host (PG506) and whose stated reasoning reproduces
were changed; the rest are recorded with their outcome.

1. 8587f0b (#4716, native FP8 GEMM for a wide bias)
   - tests/kernels/test_fp8_kernel.py::test_fp8_default_forward_is_w8a16
     REPRODUCED on sm_80: 6 bf16 cases failed with 1-ulp (0.0078125) diffs
     against rtol/atol 2e-3. The oracle now narrows the decoded weight to
     the activation dtype, matching the native path; the bound is the
     half-ulp at unity (2^-9 ~= 2e-3). FIXED.
   - tests/test_fp8_bias_range.py::test_fp8_gpu_dequant_fallback_keeps_bias_wide
     REPRODUCED on sm_80 (fp16: actual 0.0 vs oracle 0.0078125). Renamed to
     test_fp8_gpu_native_gemm_keeps_bias_wide and rewritten for the #3737
     intent: finite output, FP32 bias, residual bounded by one activation-
     dtype ulp of |x.w|. FIXED.

2. bf5adeb (#4657, Marlin bias kept in checkpoint order)
   - tests/test_marlin_scratch_cuda.py 288/200 cases REPRODUCED on sm_80:
     8 failed with "b_bias.size(0) != size_n". scripts/marlin_scratch_fixture.py
     now passes layer._kernel_bias(a) (padded, tile-ordered FP32) instead of
     the checkpoint-order layer.bias. FIXED (8 failed -> 68 passed, 2 skipped).

3. 60376e9 (#4714, default placement in one capability group)
   - tests/test_tenstorrent_support.py already passes on current main: the
     monkeypatched _record accepts **kwargs (fixed upstream by 50f1752).
     ALREADY PASSES on sm_80.

4. 34672a7 (#4585, modules snapshot the kernel policy)
   - tests/kernels/test_bitsandbytes_rocm_triton.py triton cases SKIP on
     sm_80 (no tuned bitsandbytes tile for this family). DEFERRED: the
     stated failure cannot be reproduced here.

5. dfa180d (#4627, GGUF path chosen from static gates)
   - both tests REPRODUCED on sm_80 with AttributeError
     _benchmark_forward_runner. The removed timing hook is no longer patched;
     each test asserts the hook stays absent. FIXED.

6. fd8d524 (#4599, AwqGEMVTorchLinear CPU reader)
   - both kernel-registry contract tests already pass on current main
     (AwqGEMVTorchLinear is in EXCLUDED and the ROCm audit table; fixed
     upstream by ab151fe). ALREADY PASSES on sm_80.

7. d2a0508 (#4283, dense-module adapters)
   - tests/kernels/test_gptq.py::TestKernelOutput errors on sm_80 before the
     adapter path: this host's flash_attn_2_cuda has an undefined symbol, so
     the stated Lora assertion is never reached. DEFERRED: blocked by the
     pre-existing host flash_attn failure; the fix cannot be verified here.

8. f201837 (#4508, activation-quantization wording)
   - both tests REPRODUCED on sm_80. The refusal still fires; the regex now
     matches "activation quantized|activation scales". FIXED.

9. b225a43 (#4727, static-cache compile test)
   - ROCm-only failure. On sm_80 the CUDA leg runs and fails earlier on the
     host flash_attn symbol, so the ROCm gate cannot be reproduced.
     DEFERRED.

Test run (GPU 4):
  tests/kernels/test_fp8_kernel.py tests/test_fp8_bias_range.py
  tests/test_marlin_scratch_cuda.py tests/test_marlin_scratch_benchmark.py
  tests/kernels/test_gguf_cpp_activation_quantization.py
  tests/kernels/test_gguf_cpp_path_selection.py tests/test_auto_module_decoder.py
  => 254 passed, 35 skipped, 1 failed.
The single failure is the pre-existing sm_80
test_fp8_w8a8_forward_is_batch_invariant (native torch._scaled_mm needs
sm_89+); it fails identically on origin/main.
Qubitium added a commit that referenced this pull request Nov 18, 2026
…ces (#4735) (#5058)

#4657 widened the Marlin bias stage to FP32 (thread_n_blocks * 16 / 4 int4)
and #4819 fixed the host-side model to match it. The regression test that
landed with #4819 only compares source *strings*; it never recomputes the
extent the kernel declares, so it cannot show that the host budget covers the
whole layout (B/reduce union, FP32 bias, g_idx, zero points, scales, A) for
the configs is_valid_config() accepts.

Add a derived check that translates the real declarations in
marlin_template.h and gptq_marlin.cu into Python, evaluates them over the
real thread-config matrix (4 thread configs x thread_m_blocks 1..4 x bits
{4,8} x group {128,64,32,-1} x act_order x zero-point modes, 2880 cases), and
asserts host dynamic shared memory >= the kernel requirement. It also pins
that the FP32 bias sits after the union (span == union + bias) and that the
bias and g_idx regions match byte for byte.

A second test replays the pre-#4657 tb_n * 2 bias term through the same
model and asserts it under-counts, so the invariant cannot be satisfied by
two models that agree on the wrong number.

On 0d9396e^ (pre-fix) the new invariant test fails with
``assert 512 == 1024`` for the FP32 bias stage; on current main all four
static checks pass.
sLaffey pushed a commit to sLaffey/GPTQModel that referenced this pull request Nov 18, 2026
ModelCloud#4735) (ModelCloud#4819)

ModelCloud#4657 widened the Marlin bias epilogue stage to FP32: the kernel now reserves
thread_n_blocks * 16 / 4 int4 (tb_n * 4 bytes) instead of / 8, and the wider
stage was placed at sh + sh_size_b_red_min, inside the B/reduce union. The
host-side shared-memory model was not updated: get_kernel_cache_size() still
counted tb_n * 2 bytes for the bias and only reserved max(sh_b, sh_red) for
the union. A thread config the host accepts can therefore need more dynamic
shared memory than the launch reserves, and the FP32 bias copy shares memory
with the split-K reduction. The g_idx stage was also budgeted as tb_k / 4
bytes although the kernel allocates tb_k / 4 int4.

Fix the budget model and the layout together:
- get_kernel_cache_size(): sh_bias_size = tb_n * 4 bytes and
  tmp_size = max(sh_b_size, sh_red_size) + sh_bias_size.
- get_kernel_cache_size(): sh_g_idx_size = stages * tb_k * 4 bytes.
- marlin_template.h: place the bias stage after the union
  (sh + sh_size_b_red_max), so it can never overlap a reduction write.
- marlin_template.h: read the staged FP32 bias from shared memory in the
  epilogue instead of preloading a Vec<float, 2> fragment array, so a launch
  without a bias does not reserve the widened registers.

Measurement host: 8x NVIDIA PG506 (sm_80, 124 SMs), torch
2.15.0.dev20260928+cu130, Triton 3.8.0.

Tests (CUDA_VISIBLE_DEVICES=4, real JIT kernel):
- tests/kernels/test_marlin_tile_determinism_4735.py: 12 passed.
- Marlin suites (tests/kernels/test_marlin*.py, tests/test_marlin*.py):
  396 passed, 2 skipped, 10 failed. The 10 failures are pre-existing on this
  host and reproduce identically on unmodified main:
  test_marlin_g_idx.py::test_marlin_decodes_noncontiguous_g_idx,
  test_marlin_jit.py::test_marlin_cuda_smoke_build_and_forward, and the eight
  test_marlin_scratch_cuda.py N=200 padded cases (b_bias.size(0) != size_n).
- tests/kernels/test_kernel_input_contiguity.py and
  test_kernel_compile_levels_gptq.py: 10 passed, 3 skipped.

The reported wrong/nondeterministic tiles are architecture-specific: on the
sm_80 measurement host 6000+ real-kernel launches over the issue shapes were
deterministic before and after the change, so the numerical failure could not
be reproduced here. The deterministic defects the new test pins on sm_80 are
the host/kernel bias-size disagreement and the bias/reduction overlap; the
same file also carries the issue's 30-launch bitwise + FP64-oracle
determinism sweep for the sm_89/sm_120 GPTQ bf16 and AWQ fp16 cases.
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.

2 participants