Skip to content

perf(sinq): reuse the Torch fused decode paths - #6619

Merged
Qubitium merged 1 commit into
mainfrom
perf/sinq-torch-fastpath
Dec 1, 2026
Merged

Qubitium merged 1 commit into
mainfrom
perf/sinq-torch-fastpath

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Summary

SINQ's uniform affine forward reconstructed a dense FP32 weight on every
token, so decode on ROCm ran 1.85x slower than RTN on the same model and
backend. This change routes the 1D uniform path through TorchLinear._forward
and passes sinq_scale into the shared GPTQ kernels, so decode reuses the
fused GEMV, small-M GEMM and streaming tile decoder with the fused-bias
epilogue. On Qwen2.5-0.5B (4-bit, group 128, FP16, 64 greedy tokens), SINQ
decode is now 0.837-0.877x the RTN wall time instead of 1.848x.

2D tiling (#6614, merged) stores one column scale per output-row block, which
the per-input-channel kernel argument cannot represent, so
tiling_mode="2d" keeps the existing dense wide reduction. NF4/NF3 keep the
Torch gather.

Related: #6614 (merged, 2D tiling), #6615 (open, A-SINQ). This PR does not
implement A-SINQ or 2D tiling and does not change their quantizer code. It
does touch docs/sinq.md, tests/test_sinq.py and tests/test_sinq_gpu.py,
which #6615 also edits.

What Changed

  • gptqmodel/nn_modules/qlinear/torch.py
    • New TorchLinear._input_channel_scale() hook (default None).
    • _forward_eager passes input_scale to gptq_gemv/gptq_gemm; the
      dense fallback decodes FP32, folds the scale with unsqueeze(-1), and
      uses linear_wide_bias.
    • _forward_streaming/_stream_dequantize_tile fold the scale into the
      FP32 tile before the activation-dtype cast and record it on the dequant
      stream.
  • gptqmodel/nn_modules/triton_utils/gptq_gemv.py
    • New input_scale_ptr argument and has_input_scale: tl.constexpr; the
      kernel scales the FP32 activation, which is safe for large Sinkhorn
      column factors.
  • gptqmodel/nn_modules/triton_utils/gptq_gemm.py
    • Same arguments; folds the scale into the FP32 weight in both uniform and
      non-uniform branches before the single activation-dtype cast.
  • gptqmodel/nn_modules/qlinear/sinq.py
    • post_init sets eval because the Triton and streaming gates are
      eval-only paths.
    • clear_weight_cache also clears the scaled-range and dispatch caches.
    • _input_channel_scale returns sinq_scale only for the 1D uniform path.
    • _decoded_weight_fits adds the scaled-weight bound
      max|scales| * maxq * max|sinq_scale| <= finfo(dtype).max.
    • _fused_dispatch caches the GEMV/GEMM decision per activation
      signature; codebook and 2D scales return (False, False).
    • _forward skips the identity rotation and routes codebook/2D inputs to
      the dense wide reduction; forward validates the input and scale once.
  • Tests: scaled-kernel oracles for GEMV/GEMM, ROCm fused-path selection and
    parity tests, streaming parity, a 2D dense-path guard, and a scaled-range
    overflow test.
  • scripts/benchmark_sinq_decode.py: parameterized SINQ-vs-RTN decode
    benchmark.
  • docs/sinq.md: inference-dispatch diagram, before/after table, 2D
    behavior, limitations and validation.

No public API changes. TorchLinear subclasses that do not override
_input_channel_scale keep the previous behavior because the default is
None, and the new kernel argument is optional and keyword-only.

Tests

Exact commands and results on the final rebased tree:

python -m pytest tests/test_sinq.py tests/test_torch_weight_storage.py \
    tests/test_pack_tails.py tests/kernels/test_torch_wide_bias_fallback.py \
    tests/test_rocm_kernel_contracts.py -q
# 915 passed

python -m pytest tests/test_sinq_gpu.py -q
# 23 passed

python -m pytest tests/kernels/test_gptq_rocm_gemv.py \
    tests/kernels/test_gptq_rocm_gemm.py -q
# 129 passed, 92 skipped

./format/check.sh
# All checks passed (ruff 0.14.2)

The 92 skips are kernel cases gated to an architecture that is not present on
the test host; they are not counted as validation. No test failed.

New regression tests:

  • tests/test_sinq.py::test_sinq_scaled_decode_range_gate_rejects_activation_overflow
  • tests/test_sinq_gpu.py::test_sinq_device_rocm_decode_uses_fused_gemv
  • tests/test_sinq_gpu.py::test_sinq_device_rocm_small_m_gemm_and_streaming
  • tests/test_sinq_gpu.py::test_sinq_device_2d_tiling_keeps_dense_wide_path
  • tests/kernels/test_gptq_rocm_gemv.py::test_gptq_gemv_applies_input_channel_scale
  • tests/kernels/test_gptq_rocm_gemm.py::test_gptq_gemm_applies_input_channel_scale

Measured Impact

4-bit, group_size=128, FP16, 64 greedy tokens, median of 5 runs, same model
and backend. The metric is SINQ decode wall time divided by RTN decode wall
time, so lower is better.

Metric Before After Change
Qwen2.5-0.5B decode, SINQ/RTN wall time 1.848x 0.837-0.877x -54.7%
Qwen2.5-1.5B decode, SINQ/RTN wall time not measured 0.845-0.877x —
K=N=4096, M=1 GEMV, SINQ vs RTN not measured 59.7 us vs 73.1 us (0.817x) —

The 1.5B before measurement was not collected. The after range covers five
0.5B runs and three 1.5B runs. The microbenchmark compares the fused GEMV
against RTN's decode kernel at the same shape.

Benchmark command:

python scripts/benchmark_sinq_decode.py \
    --model Qwen/Qwen2.5-0.5B-Instruct --tokens 64 --repeats 5

The before number used the same quantize and greedy-decode loop on the base
revision. The benchmark script is new in this PR, so the base run used an
equivalent local script rather than this file.

Model Support / Module Plan

Not applicable: no model, alias, definition, module-plan or fusion change.

AWQ onboarding safety

Not applicable: no AWQ grouping, search, replay or folding change.

Logic Flow Documentation

  • This change alters dispatch and the required diagrams and docs page are
    included below.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol
    names.
  • The removed/replaced mechanism is shown with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct from
    success.
  • A reference page under docs/ repeats the diagrams, titled for the
    mechanism, and is linked from README.md.

Removed mechanism: the base SinqLinear.forward rebuilt the dense effective
weight and called linear_wide_bias on every forward
(gptqmodel/nn_modules/qlinear/sinq.py, base revision line 519).

flowchart LR
    A["SinqLinear.forward"] --> B["effective_weight: dense FP32 decode per token"]
    B --> C["multiply by sinq_scale"]
    C --> D["linear_wide_bias"]
Loading

New flow:

flowchart TD
    A["SinqLinear.forward"] --> B{"sinq_scale present and width matches?"}
    B -- "no" --> E["ValueError"]
    B -- "yes" --> C{"codebook or 2D scale?"}
    C -- "nf4/nf3" --> D["effective_weight gather times sinq_scale"]
    C -- "2d" --> D2["effective_weight: per-block column scale"]
    D --> W["linear_wide_bias: FP32 reduction, bias, one round"]
    D2 --> W
    C -- "uniform 1D" --> F["TorchLinear._forward, identity rotation skipped"]
    F --> G{"streaming enabled and gate passes?"}
    G -- "yes" --> H["_forward_streaming: fold sinq_scale into each FP32 tile before the cast"]
    G -- "no" --> I["_forward_eager"]
    I --> J{"fused GEMV gate"}
    J -- "M=1" --> K["gptq_gemv scales the FP32 activation"]
    J -- "no" --> L{"fused small-M GEMM gate"}
    L -- "yes" --> M["gptq_gemm folds sinq_scale into the FP32 weight"]
    L -- "no" --> N["dense FP32 weight times sinq_scale, linear_wide_bias"]
    K --> O["fused bias epilogue, one output round"]
    M --> O
    H --> P["tile addmm and bias, one output round"]
    N --> P
Loading

Shipped symbols: SinqLinear.forward and SinqLinear._forward
(gptqmodel/nn_modules/qlinear/sinq.py:636 and :578),
TorchLinear._input_channel_scale (gptqmodel/nn_modules/qlinear/torch.py:771),
_forward_eager (:781), _forward_streaming (:1030), and the kernel
scale argument at gptqmodel/nn_modules/triton_utils/gptq_gemv.py:155 and
gptq_gemm.py:269.

Decision Before After
1D uniform affine forward Dense FP32 weight reconstruction per forward Shared fused GEMV, small-M GEMM or streaming decoder
Column-scale application Multiply the dense weight per forward GEMV scales the FP32 activation; GEMM and streaming fold it into the FP32 weight before the single cast
Range guard No fused gate; the dense path always reduced wide Fused and streaming gates require the scaled-weight bound to fit the activation dtype; otherwise the wide dense fallback
Dispatch cost Full gate list per token Cached per activation signature; invalidated by clear_weight_cache
Codebook forward Torch gather Unchanged Torch gather
2D tiling forward Dense FP32 weight reconstruction per forward Unchanged dense wide path with one column scale per output-row block
Fresh module mode Constructor training mode until the loader calls eval() post_init sets eval

Failure paths are explicit: a missing or wrong-length sinq_scale raises
ValueError/RuntimeError, a scaled weight outside the activation dtype's
finite range keeps the wide dense reduction, and codebook/2D inputs never
enter the affine fused kernels.

Reference page: docs/sinq.md, section 5 "Inference dispatch", linked from
README.md.

Review Requirements

Open the PR as a draft. Mark it ready only after review and after GitHub
confirms the pushed head has no conflicts with the current remote base.

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

  • For kernel-related changes, accuracy drift was measured against an
    applicable independent Torch FP32/FP64 oracle, or the reason this is not
    applicable is documented.
  • Fusion support changes preserve AUTO's native class and add actual-device
    FP16/BF16 tests where supported, native shape/workspace/descriptor
    checks, mutation, direct source calls, exact restoration and
    packed-storage checks.
  • The complete kernel inventory/device report lists unavailable
    dependencies, architecture restrictions and unqualified formats; skips
    are not validation.

The scaled GEMV and GEMM tests compare against FP64 oracles: the GEMV oracle
applies the multiplier to the activation, and the GEMM oracle applies it to
the decoded weight before the one activation-dtype rounding. No fusion
support declarations changed.

Notes

  • 2D tiling keeps the dense wide path because its column scale varies per
    output-row block. Extending the kernels to per-block scales is a possible
    follow-up, not part of this PR.
  • The BF16 small-M GEMM decision on one ROCm family remains on the existing
    split path by the measured dtype gate; this PR does not change that gate.
  • The new kernel argument is None by default. The has_input_scale
    constexpr removes the extra load for ordinary GPTQ calls.

Route the uniform affine SinqLinear forward through TorchLinear._forward so ROCm decode uses the shared GPTQ fused GEMV, small-M GEMM and streaming tile decoder instead of reconstructing a dense weight per token. Pass sinq_scale into the kernels: GEMV scales the FP32 activation, GEMM and streaming fold it into the FP32 weight before the single cast.

Add the scaled-weight range gate, per-signature dispatch caching, eval mode at post_init, and the codebook/wide fallbacks. Extend the ROCm kernel and SINQ device tests with scaled-kernel oracles and fused-path selection checks.
@Qubitium
Qubitium marked this pull request as ready for review December 1, 2026 08:41
@Qubitium
Qubitium merged commit 5d0365a into main Dec 1, 2026
6 checks passed
@Qubitium
Qubitium deleted the perf/sinq-torch-fastpath branch December 1, 2026 08:41
Qubitium pushed a commit that referenced this pull request Dec 1, 2026
The scaled dense fallback always decoded and folded in FP32, even when
the scaled weight fits the module's activation dtype. Pick the decode
dtype from the scaled range answer and reuse the shared dense epilogue,
so a fitting weight decodes and folds in the activation dtype while an
overflowing one keeps the FP32/FP64 wide reduction.

This is the remaining non-fused path after #6619; the fused GEMV, GEMM
and streaming branches are unchanged.
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