Repository navigation
[HIP] Mask partial vectors in sampling kernels - #5767
UD-mmcminn wants to merge 1 commit into
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags & labels: |
|
No activity for 15 days, so this is now labelled |
|
@aiter-bot review |
|
aiter-bot — queued behind 1 review(s); expect to start in about 50 min. The box reviews one PR at a time. |
ROCm/aiter PR #5767 — [HIP] Mask partial vectors in sampling kernelsSplits 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):
📝 [inferred] The rounded-buffer + |
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
|
@UD-mmcminn CI failed! |
|
No activity for 15 days, so this is now labelled |
|
The tail correctness fix passes the targeted gfx942 checks, but the shared argmax bulk path regresses on already-aligned inputs. Head: The changed full-vector traversal in 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
All three independent pairs show the slowdown, and the across-round variation is substantially smaller than the effect. The aligned 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. |
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_samplerandom_sample_outer_exponentialrandom_samplemixed_sample_outer_exponentialmixed_sampleexponentialProblem
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
-inf.1.0.The sampling test also now forces an independent FP32 reference buffer. Previously:
aliased and repeatedly modified the original input when it was already FP32. Using
copy=Trueprevents benchmark iterations from corrupting their input.Validation
Hardware:
gfx908:sramecc+:xnack-Deterministic tail coverage:
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:
M=1,32N=32000N=32003All comparisons passed with exact token equality.
Additional large-vocabulary BF16 coverage passed at
N=151936andN=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:
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.