Skip to content

perf(marlin): take whole output tiles before striping K (hybrid schedule) - #5222

Merged
Qubitium merged 5 commits into
mainfrom
perf/marlin-hybrid-schedule
Nov 18, 2026
Merged

Qubitium merged 5 commits into
mainfrom
perf/marlin-hybrid-schedule

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Do not merge until there is a clean A/B benchmark. This PR passes the
full correctness bar below. Its performance is unmeasured: the only
run of this variant overlapped other sessions' jobs on the benchmark GPU
and is contaminated. See Performance.

Port the hybrid work schedule from vLLM's Marlin kernel (the scheduling part
of vllm-project/vllm#24722). With more output tiles than threadblocks, each
block first takes part1_mn_iters rounds of whole output tiles: all of K,
slice_count == 1, no lock and no global reduction. Only the remaining
part2_mn_tiles are striped along K as before. Before, every tile was
striped, so many large-M tiles were split across two blocks and paid a lock
wait and a global reduction.

Depends on #5188 (the #4913 scale-slot race fix). This branch carries that
commit (5c0de4772) and should be rebased once #5188 lands.

Net diff: marlin_template.h +96/-37, plus a test and a docs page.

Correctness evidence (summary):

What Changed

Not ported from #24722, deliberately:

Tests

  • Unit tests have been executed and passed.
  • I added a new simple/fast unit test for this change.

CUDA_DEVICE_ORDER=PCI_BUS_ID, TORCH_CUDA_ARCH_LIST=8.9 on GPU 0
(RTX 4090) and 12.0 on GPU 2 (RTX 5090), each with its own JIT build root:

python -m pytest -q -rs tests/kernels/test_marlin_hybrid_schedule.py \
  tests/kernels/test_marlin_scale_slot_race_4913.py tests/kernels/test_marlin_tile_determinism_4735.py \
  tests/kernels/test_awq_marlin_determinism_4683.py tests/kernels/test_marlin_bias_epilogue.py \
  tests/kernels/test_marlin_fp32_schedule.py tests/kernels/test_marlin_quant_dtype_boundaries.py \
  tests/kernels/test_marlin_strided_activation_4563.py tests/kernels/test_awq_marlin_stream_4683.py \
  tests/kernels/test_awq_machete_marlin.py
# sm_89 : 248 passed, 2 skipped in 247.87s
# sm_120: 248 passed, 2 skipped in 52.95s
python -m pytest -q tests/test_marlin_jit.py   # separate process
# sm_89 : 65 passed;  sm_120: 65 passed
/root/venv/bin/ruff check gptqmodel docs/eora tests setup.py   # All checks passed!

Red/green: the new test is green on baseline too. This is a scheduling
change; the baseline has no part-1 → part-2 transition to break. As red
evidence that the test covers the new path, I removed the re-init line
a_gl_rd += a_gl_rd_delta_o * slice_row; and re-ran on sm_120:
24 failed in 201.53s. The source was then restored and re-verified.

The source-parsing tests in test_marlin_tile_determinism_4735.py /
test_marlin_fp32_schedule.py pass unchanged: no shared-memory declaration
or planner constant moves. test_marlin_scale_slot_race_4913.py also passes,
both the source check and the 10,000-launch time-slicing soak for gptq-fp16
and awq-zp-bf16.

Skips (both cards): test_awq_machete_marlin.py:290 (Machete SM90-only) and
:308 (Swordfish sm100/103/110). Not covered: the act-order kernel with
is_k_full=False (group_blocks == 0). GPT-QModel's marlin_is_k_full
never selects it for non-row-parallel layers, and no test drives it.

Model Support / Module Plan

Not applicable.

Logic Flow Documentation

  • The required diagrams and docs page are included below.
flowchart TD
    S["global_mn_tiles = parallel * n_tiles"] --> Q{"global_mn_tiles > gridDim.x?"}
    Q -- "no" --> P2only["part1_mn_iters = 0 (old stripe split)"]
    Q -- "yes" --> R["part2 = global % grid (+grid if part2*3 <= grid)\npart1_mn_iters = (global - part2) / grid"]
    P2only --> INIT["init_slice()"]
    R --> INIT
    INIT --> D{"!in_part2 and part1_mn_iters?"}
    D -- "yes" --> P1["init_part1_slice: whole tile, no lock"]
    D -- "no" --> SW["switch once to part 2 (may start mid-K)"]
    SW --> P2["init_part2_slice: stripe, locks"]
    P1 --> RUN["main loop"]
    P2 --> RUN
    RUN --> RED{"slice_count > 1?"}
    RED -- "yes" --> LOCK["barrier + global reduce"]
    RED -- "no" --> W["write_result"]
    LOCK --> W
    W --> RE["advance; rebuild a_gl_rd, b_gl_rd/B_ptr, s_gl_rd, zp_gl_rd\nfrom (slice_row, slice_col)"]
    RE --> INIT
    classDef new fill:#e6f4ea,stroke:#137333,color:#111
    classDef risk fill:#fce8e6,stroke:#c5221f,color:#111
    class Q,R,D,P1,SW new
    class RE risk
Loading
Situation Before (marlin_template.h on main) After
parallel*n_tiles <= gridDim.x stripes stripes (identical split)
more output tiles than blocks stripes; many tiles split over 2 blocks whole-tile rounds, then stripes over part2_mn_tiles
lock-offset rule parallel * n_tiles >= gridDim.x part2_mn_tiles >= gridDim.x
slice re-init B_ptr += b_sh_stride - b_gl_rd_delta_o*k_tiles, slice_row assumed 0 all read indices rebuilt from (slice_row, slice_col)

The red node is the failure-prone transition; the new test and the mutation
check above cover it.

Review Requirements

  • 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 (correctness). Performance regressions are not yet ruled out; see below.

Kernel Accuracy Requirements

  • Accuracy drift was measured against an independent Torch FP64 oracle.
  • Not a fusion change.
  • Skips listed above.

FP64 oracle sweep: GPTQ sym g128 (desc_act False/True) and AWQ zp g128,
FP16/BF16, with and without bias, M in {1, 7, 16, 64, 128, 512, 2048}.
Shapes: Llama-3-8B (4096x6144, 4096x4096, 4096x1024, 4096x28672, 14336x4096)
and Qwen2.5-7B (3584x3584, 3584x512, 18944x3584). That is 672 cases per card.
Every case is finite and bitwise identical across repeated launches.

card overall max abs err (base / change) mean of per-case max err cases with higher max err
RTX 4090 sm_89 0.2983 / 0.2983 0.05693 / 0.05693 0
RTX 5090 sm_120 0.2794 / 0.2794 0.05651 / 0.05651 1: 0.03064→0.03186 at abs ref max 69.1 (under half an FP16 ulp)

No storage change: no new buffers or caches, and the shared-memory layout is
unchanged.

Performance

Unmeasured / contaminated. The only run of this exact variant on GPU 2
(RTX 5090) began about 10:43. From about 10:45, other sessions' jobs ran on
that GPU continuously. That run shows implausible swings, for example
Llama gate_up M=512 at +72% while the full port that contains the same
scheduling measured -0.3% on the same cell a few minutes earlier. I treat it
as invalid and don't report it as data. A later guarded harness (it waits for
an idle GPU and re-measures any case that overlaps another process) never
got an idle window.

The full port (same scheduling + contiguous K), measured clean before the
contention, gives only a rough hint: up to -4.2% at Qwen down
M=2048 and about -0.5..-1% on most M ≥ 512 cells.

Required before merge: a clean A/B on an idle GPU with the same harness
(CUDA-graph timing, median of ≥ 50 replays, the shapes above, GPTQ/AWQ ×
FP16/BF16), both standalone and on top of #5216.

Notes

🤖 Generated with Claude Code

Qubitium and others added 4 commits November 18, 2026 10:06
#4913)

For group_blocks > thread_k_blocks (g128 with thread_k = 64) a quantization
group spans two pipeline stages. fetch_to_shared() copies the group's scales
and zero points only into the slot of the group's first stage. The second stage
re-read that slot (`2 * (pipe / 2)`) after the last wait_for_stage() barrier
that protects it. In the same window, faster warps refill that slot with stage
pipe + stages, which belongs to group g + 2.

cp.async latency normally hides the race. When the GPU time-slices to another
process, in-flight copies drain before the context is saved, so a lagging warp
applies group g+2's scales. One k-warp-group then gets a whole 64-row output
block wrong, with no error raised. This affects GPTQ and AWQ in fp16 and bf16
on sm_89 and sm_120.

Port vLLM's guard from vllm-project/vllm#24722 (vLLM >= 0.12.0): only the
group's first stage reads shared memory for scales and integer or float zero
points; the later stages keep frag_s / frag_qzp / frag_zpf.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ule)

Port the hybrid work schedule from vLLM's Marlin kernel
(vllm-project/vllm#24722, scheduling part only). With more output tiles
than threadblocks, each block first takes part1_mn_iters rounds of whole
tiles (all of K, slice_count 1, no lock or global reduction). The remaining
part2_mn_tiles are then striped along K as before. The striped remainder
is kept at least a third of the grid.

The first part-2 slice of a block usually starts mid-K. The slice re-init
now rebuilds a_gl_rd, b_gl_rd/B_ptr, s_gl_rd and zp_gl_rd from
(slice_row, slice_col) instead of assuming slice_row == 0.

#24722's contiguous-K warp layout and single-copy scale fetch are not
ported. Measured on an RTX 5090, they regressed M=16 by up to 9%, and they
reshape the scale-read lines that #5193 changes.

Adds test_marlin_hybrid_schedule.py, which drives the part-1 -> part-2
transition with g128 scales, AWQ zero points, bias and FP32/FP16 reductions
against an FP64 oracle, plus docs/marlin-hybrid-schedule.md.

Depends on #5188 (#4913 scale-slot race fix), which this branch carries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The part-2 slice restart copied the initial s_gl_rd row term from before
#5193, so it divided by 2 only for FP4 weights (w_type == kFE2M1f). Since
#5193 the 8-bit (paired) scale layout keys on the scale width, so MXFP8
restarts landed on twice the right scale row. On an RTX 4090, MXFP8 at
M=1000, K=4096, N=4096 came out with errors as large as the outputs. Use
is_8bit_scale like the initial s_gl_rd.

Add MXFP8 and MXFP4 cases to the part-1 -> part-2 transition test. They fail
with the old divisor and pass with this one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Correctness fix pushed (8c04ce5): the MXFP8 overlap with #5193 was a real bug, not just a merge note.

#5193 merged first, so this PR landed second. Its part-2 restart still divided the s_gl_rd row term by (w_type == vllm::kFE2M1f ? 2 : 1). Since #5193, the paired 8-bit scale layout keys on is_8bit_scale, so MXFP8 restarts read twice the right scale row. GitHub reported the PR as mergeable because there was no textual conflict.

This PR is still a draft and still needs a clean A/B benchmark before merge.

🤖 Generated with Claude Code

…rows)

The hybrid schedule is now a compile-time kernel variant (`hybrid` template
argument), instantiated only for 64-row tiles. The host launches it only for
calls with at least MARLIN_HYBRID_MIN_ROWS (512) rows; every smaller call runs
the hybrid=false kernel, which compiles to the original schedule.

A clean A/B on a 124-SM A100 measured the ungated hybrid kernel ~1 us slower
per call at M=1 and up to 14% slower at M=64, and 1.06x median (up to 1.20x)
faster at M >= 1024. The small-M cost shows even where no part-1 round runs,
so it is kernel code, not schedule; hence a compile-time gate.

Adds a source-contract test for the gate and FP64-oracle tests at 511 rows
(original kernel) and 512 rows (hybrid kernel).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Clean A/B on sm_80 (A100 PG506, 124 SMs), and a prefill-only gate

Setup: idle GPUs, 4-bit GPTQ g128, FP16 and BF16, 7 shapes (4096², 11008×4096, 4096×11008, 14336×4096, 4096×14336, 5120×8192, 32768×1280), M = 1…8192. Each build ran in its own process, in base/new/new/base order, timed with CUDA graphs and rotating weight copies (median of replays). Base is 0d8a6720f.

Ungated hybrid kernel (8c04ce5a) vs base:

M median range
1 0.967× 0.94–0.97×, slower in every cell
64 0.952× down to 0.86×
128–512 ~1.00× BF16 ~1.05×
≥ 1024 1.059× up to 1.20×

The M=1 cost (about 1 µs per call) also shows on shapes with no part-1 round. So it comes from the extra kernel code, not from the schedule.

08a516828 makes the hybrid schedule a prefill-only kernel: a compile-time hybrid template argument, instantiated only for 64-row tiles. The host launches it only when the call has at least MARLIN_HYBRID_MIN_ROWS = 512 rows. Below that, the hybrid=false kernel compiles to the original schedule.

Gated (08a516828) vs base:

M speed vs base output bits
1 1.000× (0.993–1.003) equal to base, 14/14
16–256 1.00× median equal to base, 56/56
512 1.023× median equal to the ungated hybrid, 14/14
≥ 1024 1.058× median, up to 1.16× equal to the ungated hybrid, 56/56
  • All runs are deterministic.
  • The low cells at ≥ 512 are 4096×4096 FP16. That shape swings between about 86 and 100 µs from run to run in both base and head, with the same bits as the head kernel.

Tests on sm_80:

  • 12 Marlin and AWQ-Marlin kernel files: 328 passed, 10 skipped. That includes all hybrid tests and the new gate tests: source contract, plus FP64 oracle at 511 rows (original kernel) and 512 rows (hybrid).
  • tests/test_marlin_jit.py: 64 passed in a fresh process. In the same process as the kernel suites, test_marlin_cuda_smoke_build_and_forward fails with "already loaded in this Python process". That's a test-ordering artifact.

🤖 Generated with Claude Code

@Qubitium
Qubitium marked this pull request as ready for review November 18, 2026 13:01
@Qubitium
Qubitium merged commit 102f4c7 into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the perf/marlin-hybrid-schedule branch November 18, 2026 13:02
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