Skip to content

[HIP] Mask partial vectors in sampling kernels - #5767

Open
UD-mmcminn wants to merge 1 commit into
ROCm:mainfrom
UD-mmcminn:fix-sampling-vector-tails
Open

UD-mmcminn wants to merge 1 commit into
ROCm:mainfrom
UD-mmcminn:fix-sampling-vector-tails

Conversation

@UD-mmcminn

Copy link
Copy Markdown

Summary

Fix out-of-bounds vector accesses in the sampling kernels when the vocabulary size is not divisible by the vector width.

The implementation separates the branch-free full-vector path from the final partial-vector path, preserving bulk-path performance while making tail loads and stores bounds-safe.

This covers:

  • greedy_sample
  • random_sample_outer_exponential
  • random_sample
  • mixed_sample_outer_exponential
  • mixed_sample
  • exponential

Problem

The kernels previously entered a vector load or store whenever the vector's starting offset was less than N. For a final partial vector, that could access elements beyond the end of the row.

Depending on allocation layout, those accesses could read the next row, sample an invalid token, or overwrite memory following an exponential-output row.

Implementation

  • Keep complete vector loads and stores on a branch-free bulk path.
  • Handle only the final partial vector with scalar-masked helpers.
  • Pad invalid input lanes with -inf.
  • Pad invalid external-exponential lanes with 1.0.
  • Store only valid lanes from the final exponential vector.
  • Distribute the greedy tail across lanes instead of serializing it in one lane.
  • Preserve one Philox vector draw per owned vector, including a partial vector.
  • Leave public APIs, launch geometry, and generator ownership unchanged.

The sampling test also now forces an independent FP32 reference buffer. Previously:

logits = input.to(torch.float)
logits.div_(...)

aliased and repeatedly modified the original input when it was already FP32. Using copy=True prevents benchmark iterations from corrupting their input.

Validation

Hardware:

  • AMD Instinct MI100
  • gfx908:sramecc+:xnack-
  • PyTorch 2.10.0 with ROCm 7.2

Deterministic tail coverage:

for dtype in bf16 fp16 fp32; do
  AITER_REBUILD=0 python op_tests/test_sample.py \
    --tail-only \
    -d "$dtype" \
    -n 1 17 4097 16385
done

All 12 dtype/size cases passed. Each case exercises greedy sampling, both random paths, both mixed paths, and guarded exponential output.

Reference comparisons were also run for:

  • BF16, FP16, and FP32
  • M=1,32
  • aligned N=32000
  • partial-vector N=32003
  • greedy, random, and mixed sampling
  • internal and external exponential generation

All comparisons passed with exact token equality.

Additional large-vocabulary BF16 coverage passed at N=151936 and N=151937.

The translation unit also compiles directly for gfx908 without private-memory use or register spills.

Performance

The bulk/tail split was compared against the initial bounds-safe implementation, which performed bounds checks throughout the vector loop. Values below are three-run medians on MI100:

Path Shape Initial safe patch Bulk/tail implementation Improvement
Greedy M1 × 32000 8.612 µs 7.173 µs 16.7%
Greedy M32 × 32000 8.823 µs 7.450 µs 15.6%
Greedy M1 × 151936 22.772 µs 20.468 µs 10.1%
Greedy M32 × 151936 21.687 µs 20.341 µs 6.2%
Random, external exponential M32 × 32000 39.721 µs 37.622 µs 5.3%
Random, internal exponential M32 × 32000 41.356 µs 35.648 µs 13.8%
Random, external exponential M1 × 151936 108.752 µs 99.754 µs 8.3%
Random, internal exponential M1 × 151936 166.134 µs 146.698 µs 11.7%

Across the measured aligned-shape matrix, the bulk/tail implementation was 5.3%–26.5% faster than the initial bounds-safe version.

This performance comparison is against the first correctness implementation, not a claim of speedup over the previous out-of-bounds upstream path.

CI impact

No workflow or runner configuration is changed. This does not add a required gfx908 CI job.

@UD-mmcminn
UD-mmcminn requested a review from a team September 22, 2026 17:22
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
multigpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 5767 --add-label <label>

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to opt this PR out.

@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Oct 9, 2026
@junhaha666

Copy link
Copy Markdown
Contributor

@aiter-bot review

@aiter-bot

Copy link
Copy Markdown

aiter-bot — queued behind 1 review(s); expect to start in about 50 min. The box reviews one PR at a time.

@junhaha666 junhaha666 removed the stale The PR hasn't been updated in 2 weeks label Oct 23, 2026
@aiter-bot

Copy link
Copy Markdown

ROCm/aiter PR #5767 — [HIP] Mask partial vectors in sampling kernels

Splits the vocabulary traversal of the six sampling kernels (greedy, random, mixed, their outer-exponential variants, and exponential) into a branch-free full-vector loop plus a masked scalar tail, so a vocab size that is not a multiple of the vector width no longer reads past the end of a logits row or writes past the end of an exponential-output row.

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — target op_tests/test_sample.py existed, but auto-validation is disabled (REVIEW_AUTO_VALIDATE=0) and no idle GPU on this box (all 8 at 98–99% VRAM, no torch env) for a manual run — environment gap, not a PR defect
Perf (advisory): NOT RUN — perf stage skipped (auto-validation disabled) and no idle GPU for a manual base-vs-head run of python3 op_tests/test_sample.py; the PR's own table compares its two intermediate patches, not base vs head

⚠️ [verified] csrc/kernels/sample_kernels.cu restructures the hot traversal loop of all six sampling kernels, yet the only timing in the PR compares the author's own two bounds-safe intermediate patches — the summary's "5.3%–26.5% faster" exceeds the best row shown (16.7%) and traces to no displayed measurement — so the fix's cost against the previous upstream code is unmeasured, while every unaligned row now swaps one unmasked vector load for up to 15 predicated scalar tail loads (greedy VecSize=16). Author must run python3 op_tests/test_sample.py base vs head on one locked GPU at aligned and unaligned N and report the delta.

⚠️ [verified] The deterministic tail checks this PR adds to op_tests/test_sample.py sit behind --tail-only, which nothing in CI passes — .github/scripts/aiter_test.sh runs the file bare and the default N=151936 is a multiple of both 4 and 16 — so the partial-vector paths this PR fixes (sample_load_tail, sample_store_tail, the distributed greedy tail) get zero CI regression coverage and a future break of them would pass CI green. Author must wire the tail checks into CI (or add a non-aligned N to the default size list) so the fixed paths run after merge.

📝 [inferred] The rounded-buffer + idx < d vector-loop pattern this PR removes from csrc/kernels/sample_kernels.cu still lives in csrc/kernels/activation_kernels.cu, csrc/kernels/rmsnorm_quant_kernels.cu and csrc/kernels/mhc_kernels.cu — if a non-vector-aligned dim ever reaches those kernels, the same tail overread exists there, but no such caller is confirmed. Reviewer should ask whether a follow-up PR applies the same bulk/tail split to those kernels.

@junhaha666 junhaha666 closed this Oct 23, 2026
@junhaha666 junhaha666 reopened this Oct 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the gfx1201 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 5767 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

@junhaha666

Copy link
Copy Markdown
Contributor

@UD-mmcminn CI failed!

@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Nov 8, 2026
@junhaha666

Copy link
Copy Markdown
Contributor

The tail correctness fix passes the targeted gfx942 checks, but the shared argmax bulk path regresses on already-aligned inputs.

Head: ad6565b427f7dbdc5c980f661e2d36e6787703ee. Exact current PR base tested: 1e2d557d7877f880e7daf3ac8d5cc45f918f6d9e. Independently matched historical base: 94dca7bc674650b6de2609eeae2bcdd58e970bf3.

The changed full-vector traversal in csrc/kernels/sample_kernels.cu:336-366 runs through the public greedy_sample entrypoint and the zero-temperature branch of mixed_sample_outer_exponential. The primary reproducer is contiguous BF16 [1, 151936]; that vocabulary size is aligned, so this is not a partial-tail-only cost.

Six interleaved exact-head/current-base rounds show roughly an 11% slowdown for these single-row argmax calls. Since the current base also has unrelated JIT/header updates, I did not attribute that comparison alone to this PR. I then ran three new alternating head/merge-base pairs using a separately implemented 100-call graph timer. The merge-base-to-head diff contains only this sampling kernel and its test file; the surrounding JIT and headers are identical.

Every focused run checks the actual public API result against torch.argmax on identical seed-5767 tensors before timing. Both head and historical base produce the same correct token.

Vocabulary Public path Historical base median (us) Head median (us) Median paired change
151936 greedy 10.149 11.394 +12.29%
151936 mixed_zero_temperature 10.881 12.175 +11.90%

All three independent pairs show the slowdown, and the across-round variation is substantially smaller than the effect. The aligned 151936 case reproduces it without ever needing the new scalar tail handling.

Expected: the bounds-safe change preserves the efficient full-vector traversal for aligned serving inputs, as described in the PR. Actual: supported argmax calls take consistently longer at this head, including the aligned case.

Reproducer: run the following unchanged script in clean checkouts of the exact head, current base, and historical base using the standard source/JIT setup on gfx942. Keep inputs and method unchanged; alternate the head and historical base for three or more pairs. The timer uses 30 warmup calls, 100 captured calls, five warmup replays, and 25 CUDA-event samples per round.

import json
import statistics
import subprocess
import torch
import aiter

assert torch.cuda.get_device_properties(0).gcnArchName.split(':')[0] == 'gfx942'
for columns in (151936,):
    generator = torch.Generator().manual_seed(5767)
    logits = torch.randn((1, columns), generator=generator).bfloat16().cuda()
    exponentials = torch.ones_like(logits, dtype=torch.float32)
    temperature = torch.zeros(1, device='cuda')
    output = torch.empty(1, device='cuda', dtype=torch.int32)
    expected = logits.argmax(-1).to(torch.int32)
    functions = {'greedy': lambda: aiter.greedy_sample(output, logits), 'mixed_zero_temperature': lambda: aiter.mixed_sample_outer_exponential(output, logits, exponentials, temperature, eps=1e-6)}
    for name, function in functions.items():
        function()
        assert torch.equal(output, expected)
        for warmup in range(30):
            function()
        torch.cuda.synchronize()
        graph = torch.cuda.CUDAGraph()
        with torch.cuda.graph(graph):
            for iteration in range(100):
                function()
        for warmup in range(5):
            graph.replay()
        torch.cuda.synchronize()
        samples = []
        for sample in range(25):
            start = torch.cuda.Event(enable_timing=True)
            end = torch.cuda.Event(enable_timing=True)
            start.record()
            graph.replay()
            end.record()
            end.synchronize()
            samples.append(start.elapsed_time(end) * 10)
        print(json.dumps({'sha': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(), 'rows': 1, 'columns': columns, 'dtype': 'bf16', 'operation': name, 'median_us': statistics.median(samples), 'samples_us': samples, 'actual': output.tolist(), 'expected': expected.tolist()}))

Could we keep the bounds-safe tail handling while avoiding this cost in the full-vector argmax path? This is a performance concern; the reported targeted head correctness checks pass.

@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Nov 27, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants