Skip to content

Commit c278797

Browse files
committed
Refactor tiered:bool into tier_mode:str and added env vars to force specific tiering modes
1 parent 135ebca commit c278797

3 files changed

Lines changed: 172 additions & 48 deletions

File tree

‎aiter/ops/flydsl/kernels/topk_per_row_decode_tiered.py‎

Lines changed: 80 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
"""
4343

4444
from functools import cache
45-
from typing import Any
45+
from typing import Any, Literal
4646

4747
import flydsl.compiler as flyc
4848
import flydsl.expr as fx
@@ -107,30 +107,56 @@ def topk_workspace_slots(
107107
return int(num_rows) * row_slots
108108

109109

110-
def needs_workspace_zero(max_row_len: int, top_k: int, short_max: int) -> bool:
110+
def needs_workspace_zero(
111+
max_row_len: int,
112+
top_k: int,
113+
short_max: int,
114+
tier_mode: str = "auto",
115+
) -> bool:
111116
"""Return whether any row can enter the persistent multi-block path."""
117+
if tier_mode == "short":
118+
return False
119+
if tier_mode in ("mid", "long"):
120+
return True
112121
return max_row_len > max(short_max, top_k)
113122

114123

115124
@cache
116125
def create_topk_per_row_decode_tiered_kernel(
117-
blocks_per_row: int = 8,
118-
*,
119126
top_k: int,
127+
*,
128+
blocks_per_row: int = 8,
120129
bits_per_pass: int = 11,
121130
scan_stages: int = SCAN_STAGES,
122-
tiered: bool = True,
131+
tier_mode: Literal["auto", "short", "mid", "long"] = "auto",
123132
tiered_short_max: int = 16384,
124133
tiered_mid_cap: int = 16,
125134
tiered_mid_max: int = 65536,
126135
tiered_long_cap: int = 32,
127136
mask_non_finite: bool = True,
128137
) -> Any:
138+
"""Build a launcher that selects the Top-K largest values' column indices per
139+
decode row (unordered set, matching torch.topk by value). Implemented as a
140+
tiered persistent multi-block radix-select; the returned launcher is cached.
141+
142+
top_k: number of indices selected per row (compile-time; any positive value).
143+
blocks_per_row: workgroups launched per row (grid width); the mid/long tiers cap
144+
how many actually cooperate, excess workgroups return immediately.
145+
bits_per_pass: radix digit width, 10 or 11; 11 = 2048-bin LDS histogram, required
146+
by the short tier.
147+
scan_stages: histogram block-scan staging, one of 1/2/4/8.
148+
tier_mode: "auto" picks a tier per row by valid length; "short"/"mid"/"long"
149+
force that tier for every row.
150+
tiered_short_max: row_len <= this -> short tier (single workgroup, barrier-free).
151+
tiered_mid_max: short_max < row_len <= this -> mid tier; longer -> long tier.
152+
tiered_mid_cap / tiered_long_cap: max cooperating workgroups per row in the mid /
153+
long tier (clamped to blocks_per_row).
154+
mask_non_finite: clamp inf/NaN to -inf so they never rank into the top-k.
155+
"""
129156
short_max = tiered_short_max
130157
mid_cap = tiered_mid_cap
131158
mid_max = tiered_mid_max
132159
long_cap = tiered_long_cap
133-
"""Return a cached tiered persistent decode radix-select launcher."""
134160

135161
if bits_per_pass not in (10, 11):
136162
raise ValueError(f"bits_per_pass must be 10 or 11, got {bits_per_pass}")
@@ -142,22 +168,42 @@ def create_topk_per_row_decode_tiered_kernel(
142168
raise ValueError(f"mid_cap/long_cap must be >= 2, got {mid_cap}/{long_cap}")
143169
if mid_max < short_max:
144170
raise ValueError(f"mid_max must be >= short_max, got {mid_max} < {short_max}")
171+
if tier_mode not in ("auto", "short", "mid", "long"):
172+
raise ValueError(
173+
f"tier_mode must be one of auto/short/mid/long, got {tier_mode!r}"
174+
)
175+
# The short tier runs the standalone one-workgroup radix-select (2048-bin LDS
176+
# histogram), so it needs bits_per_pass == 11. It is compiled in for "auto"
177+
# (short rows) and "short" (all rows); forcing "short" without bpp==11 is an
178+
# error rather than a silent fallback.
179+
if tier_mode == "short" and bits_per_pass != 11:
180+
raise ValueError(
181+
f"tier_mode='short' requires bits_per_pass == 11, got {bits_per_pass}"
182+
)
145183

146-
# The short tier runs the standalone one-workgroup radix-select (11/11/10 ordered key, 2048-bin LDS
147-
# histogram), so it is only available when bits_per_pass == 11.
148-
short_tier = tiered and bits_per_pass == 11
184+
short_tier = tier_mode in ("auto", "short") and bits_per_pass == 11
149185
block_threads = BLOCK_THREADS
150186
red_slots = (block_threads + WARP_SIZE - 1) // WARP_SIZE
151187
num_passes = _num_passes(bits_per_pass)
152188
num_buckets = 1 << bits_per_pass
153189
row_workspace_slots = COUNTER_SLOTS + num_passes * num_buckets
190+
191+
# Caps/thresholds only affect codegen for modes that use them; include them in
192+
# the name for those modes so distinct configs cache separately.
193+
_cap_tag = (
194+
""
195+
if tier_mode == "short"
196+
else (
197+
f"_s{tiered_short_max}_mc{tiered_mid_cap}"
198+
f"_mm{tiered_mid_max}_lc{tiered_long_cap}"
199+
)
200+
)
154201
kernel_name = (
155202
f"topk_per_row_decode_persistent_k{top_k}_"
156203
f"bpp{bits_per_pass}_g{blocks_per_row}_v2"
157204
f"_stage{scan_stages}"
158-
f"{'_tiered' if tiered else ''}"
159-
f"{f'_s{tiered_short_max}_mc{tiered_mid_cap}' if tiered else ''}"
160-
f"{f'_mm{tiered_mid_max}_lc{tiered_long_cap}' if tiered else ''}"
205+
f"_{tier_mode}"
206+
f"{_cap_tag}"
161207
f"{'_1wg' if short_tier else ''}"
162208
f"{'_mf' if mask_non_finite else ''}"
163209
)
@@ -203,7 +249,7 @@ def topk_per_row_decode_tiered_kernel(
203249
c_parts = fx.Int32(blocks_per_row)
204250
c_sign_bit = fx.Int32(-2147483648)
205251
c_exp_mask = fx.Int32(0x7F800000) # fp32 exponent bits (all-ones => inf/NaN)
206-
c_neg_fltmax = fx.Float32(-3.4028234663852886e38) # torch.finfo(f32).min
252+
c_neg_inf = fx.Float32(float("-inf"))
207253
c_neg_one = fx.Int32(-1)
208254
c_zero_f32 = fx.Float32(0.0)
209255
c_row_ws = fx.Int32(row_workspace_slots)
@@ -239,24 +285,26 @@ def topk_per_row_decode_tiered_kernel(
239285
row_out = ArithValue(row) * ArithValue(c_top_k)
240286
row_ws_base = ArithValue(row) * ArithValue(c_row_ws)
241287

242-
# Per-row active-part cap over the fixed grid (excess blocks return immediately).
243-
active_parts = c_parts
244-
if const_expr(tiered):
245-
# Per-bucket active-part caps over the fixed launch grid (excess
246-
# blocks return immediately). Short rows run the single-workgroup short tier;
247-
# the mid and long persistent buckets cap how many of the grid's
248-
# blocks participate, trading CU coverage against barrier/atomic
249-
# contention. Caps are clamped to the grid (``c_parts``).
288+
# Active cooperating workgroups per row over the fixed grid (excess blocks
289+
# return immediately). "auto" picks per row by length; short/mid/long force
290+
# that tier for every row. Caps are clamped to the grid.
291+
c_mid_cap = fx.Int32(mid_cap)
292+
c_long_cap = fx.Int32(long_cap)
293+
mid_parts = (ArithValue(c_parts) < ArithValue(c_mid_cap)).select(
294+
c_parts, c_mid_cap
295+
)
296+
long_parts = (ArithValue(c_parts) < ArithValue(c_long_cap)).select(
297+
c_parts, c_long_cap
298+
)
299+
if const_expr(tier_mode == "short"):
300+
active_parts = c_one
301+
elif const_expr(tier_mode == "mid"):
302+
active_parts = mid_parts
303+
elif const_expr(tier_mode == "long"):
304+
active_parts = long_parts
305+
else: # "auto": pick per row by valid length
250306
c_short = fx.Int32(short_max)
251307
c_mid = fx.Int32(mid_max)
252-
c_mid_cap = fx.Int32(mid_cap)
253-
c_long_cap = fx.Int32(long_cap)
254-
mid_parts = (ArithValue(c_parts) < ArithValue(c_mid_cap)).select(
255-
c_parts, c_mid_cap
256-
)
257-
long_parts = (ArithValue(c_parts) < ArithValue(c_long_cap)).select(
258-
c_parts, c_long_cap
259-
)
260308
active_parts = (ArithValue(row_len) <= ArithValue(c_short)).select(
261309
c_one,
262310
(ArithValue(row_len) <= ArithValue(c_mid)).select(
@@ -393,13 +441,15 @@ def row_barrier(token: int):
393441
gpu.barrier()
394442

395443
def mask_nonfinite(val):
444+
# inf/NaN (exponent all-ones) -> -inf so they sort below every finite
445+
# value and are never selected.
396446
if const_expr(not mask_non_finite):
397447
return val
398448
bits = ArithValue(val).bitcast(T.i32)
399449
is_nonfinite = ArithValue(
400450
ArithValue(bits) & ArithValue(c_exp_mask)
401451
) == ArithValue(c_exp_mask)
402-
return is_nonfinite.select(c_neg_fltmax, val)
452+
return is_nonfinite.select(c_neg_inf, val)
403453

404454
def radix_twiddle_key(val):
405455
# Map larger fp32 values to smaller unsigned keys so ascending

‎aiter/ops/flydsl/topk_per_row_decode.py‎

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ def _environ_kernel_config() -> dict:
7070
bits_per_pass=_env_int("FLYDSL_TOPK_TIERED_BPP"),
7171
# 0/1 override for the non-finite mask (default on); set 0 to disable.
7272
mask_non_finite=_env_int("FLYDSL_TOPK_TIERED_MASK_NONFINITE"),
73+
# Force a single tier for every row (auto/short/mid/long)
74+
tier_mode=os.environ.get("FLYDSL_TOPK_TIERED_OVERRIDE"),
7375
)
7476
return {k: v for k, v in cfg.items() if v is not None}
7577

@@ -118,13 +120,13 @@ def _default_kernel_config(
118120
return dict(
119121
blocks_per_row=blocks_per_row,
120122
bits_per_pass=bits_per_pass,
121-
tiered=True,
122123
scan_stages=_TIERED_SCAN_STAGES,
123124
tiered_short_max=tiered_short_max,
124125
tiered_mid_cap=tiered_mid_cap_default,
125126
tiered_mid_max=_TIERED_MID_MAX,
126127
tiered_long_cap=tiered_long_cap_default,
127128
mask_non_finite=True,
129+
tier_mode="auto",
128130
)
129131

130132

@@ -141,6 +143,13 @@ def _kernel_config(num_rows: int, max_model_len: int) -> dict:
141143
if bits_per_pass not in (10, 11):
142144
raise ValueError(f"bits_per_pass must be 10 or 11, got {bits_per_pass}")
143145

146+
tier_mode = kernel_config["tier_mode"]
147+
if tier_mode not in ("auto", "short", "mid", "long"):
148+
raise ValueError(
149+
"FLYDSL_TOPK_TIERED_OVERRIDE must be one of auto/short/mid/long, "
150+
f"got {tier_mode!r}"
151+
)
152+
144153
kernel_config = _apply_deadlock_guard(kernel_config, num_rows, max_model_len)
145154
return kernel_config
146155

@@ -171,23 +180,31 @@ def _apply_deadlock_guard(
171180
if num_rows <= 0:
172181
return kernel_config
173182

174-
short_max = kernel_config["tiered_short_max"]
175-
if max_model_len <= short_max:
176-
return kernel_config # all rows short-tier -> barrier-free
183+
mode = kernel_config["tier_mode"]
184+
if mode == "short":
185+
return kernel_config # single workgroup/row -> barrier-free
177186

178-
# Worst-case workgroups any single row can put on the barrier, given the tier
179-
# its length can reach (mid vs long) and the grid width.
180187
mid_cap = kernel_config["tiered_mid_cap"]
181188
long_cap = kernel_config["tiered_long_cap"]
182189
blocks_per_row = kernel_config["blocks_per_row"]
183-
if max_model_len <= kernel_config["tiered_mid_max"]:
184-
max_active_workgroups_per_row = min(blocks_per_row, mid_cap)
185-
else:
186-
max_active_workgroups_per_row = min(blocks_per_row, max(mid_cap, long_cap))
187190

188-
is_single_workgroup = max_active_workgroups_per_row <= 1
189-
if is_single_workgroup:
190-
return kernel_config # single-workgroup tier -> barrier-free
191+
# Worst-case cooperating workgroups any single row can put on the barrier.
192+
# Forced mid/long use that tier's cap for every row; auto only reaches a
193+
# multi-block tier for rows longer than short_max.
194+
if mode == "mid":
195+
max_active_workgroups_per_row = min(blocks_per_row, mid_cap)
196+
elif mode == "long":
197+
max_active_workgroups_per_row = min(blocks_per_row, long_cap)
198+
else: # auto
199+
if max_model_len <= kernel_config["tiered_short_max"]:
200+
return kernel_config # all rows short-tier -> barrier-free
201+
if max_model_len <= kernel_config["tiered_mid_max"]:
202+
max_active_workgroups_per_row = min(blocks_per_row, mid_cap)
203+
else:
204+
max_active_workgroups_per_row = min(blocks_per_row, max(mid_cap, long_cap))
205+
206+
if max_active_workgroups_per_row <= 1:
207+
return kernel_config # single-workgroup -> barrier-free
191208

192209
# Co-resident envelope N = num_CU x occupancy. Occupancy is 2 on all CDNA:
193210
# the 1024-thread block is wave-limited (32 waves/CU / 16), with VGPR/LDS
@@ -206,11 +223,8 @@ def _apply_deadlock_guard(
206223
kernel_config["tiered_mid_cap"] = min(mid_cap, max_safe_active_workgroups)
207224
kernel_config["tiered_long_cap"] = min(long_cap, max_safe_active_workgroups)
208225
else:
209-
kernel_config["tiered_short_max"] = max_model_len
210-
211-
kernel_config["tiered_mid_max"] = max(
212-
kernel_config["tiered_mid_max"], max_model_len
213-
)
226+
# max_safe_active_workgroups < 2 -> force short tier
227+
kernel_config["tier_mode"] = "short"
214228
return kernel_config
215229

216230

@@ -249,6 +263,7 @@ def _compile_launcher(
249263
max_model_len,
250264
top_k,
251265
kernel_config["tiered_short_max"],
266+
tier_mode=kernel_config["tier_mode"],
252267
)
253268
launcher = create_topk_per_row_decode_tiered_kernel(
254269
top_k=top_k,

‎op_tests/flydsl_tests/test_flydsl_topk_per_row_decode.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import pytest
66
import torch
77

8+
import contextlib
9+
810
from aiter.ops.flydsl.utils import is_flydsl_available
911

1012
pytestmark = [pytest.mark.l2_device, pytest.mark.rocm_lower]
@@ -292,6 +294,63 @@ def test_non_finite_never_selected(k, L):
292294
_assert_row_topk_set(sanitized.cpu(), indices[0].cpu(), k, L)
293295

294296

297+
@contextlib.contextmanager
298+
def _tier_override(mode):
299+
"""Set FLYDSL_TOPK_TIERED_OVERRIDE and clear the config/launcher caches so the
300+
override actually takes effect (both are cached and otherwise ignore env)."""
301+
import os
302+
import aiter.ops.flydsl.topk_per_row_decode as m
303+
304+
prev = os.environ.get("FLYDSL_TOPK_TIERED_OVERRIDE")
305+
if mode is None:
306+
os.environ.pop("FLYDSL_TOPK_TIERED_OVERRIDE", None)
307+
else:
308+
os.environ["FLYDSL_TOPK_TIERED_OVERRIDE"] = mode
309+
m._environ_kernel_config.cache_clear()
310+
m._compile_launcher.cache_clear()
311+
try:
312+
yield m
313+
finally:
314+
if prev is None:
315+
os.environ.pop("FLYDSL_TOPK_TIERED_OVERRIDE", None)
316+
else:
317+
os.environ["FLYDSL_TOPK_TIERED_OVERRIDE"] = prev
318+
m._environ_kernel_config.cache_clear()
319+
m._compile_launcher.cache_clear()
320+
321+
322+
@pytest.mark.parametrize("mode", ["short", "mid", "long"])
323+
def test_tier_mode_override(mode):
324+
"""FLYDSL_TOPK_TIERED_OVERRIDE forces every row to a single tier. Assert the
325+
override reaches the resolved config (all modes give correct output, so output
326+
alone wouldn't prove the mode was applied), then check correctness. L > k so all
327+
three run real radix-select; single row so the deadlock guard is a no-op."""
328+
k, L = 2048, 120003
329+
with _tier_override(mode) as m:
330+
assert m._kernel_config(1, L)["tier_mode"] == mode
331+
_check_set_equivalence(k, 1, 1, L, "random", padded=True)
332+
333+
334+
def test_tier_mode_invalid_rejected():
335+
"""An unknown FLYDSL_TOPK_TIERED_OVERRIDE value is rejected."""
336+
with _tier_override("bogus"):
337+
logits = torch.randn((1, 8192), device="cuda", dtype=torch.float32)
338+
sl = torch.tensor([8192], device="cuda", dtype=torch.int32)
339+
idx = torch.empty((1, 2048), device="cuda", dtype=torch.int32)
340+
with pytest.raises(ValueError):
341+
flydsl_top_k_per_row_decode(
342+
logits,
343+
1,
344+
sl,
345+
idx,
346+
1,
347+
logits.stride(0),
348+
logits.stride(1),
349+
k=2048,
350+
ordered=False,
351+
)
352+
353+
295354
@pytest.mark.parametrize("k", [512, 2048])
296355
def test_row_strided_logits(k):
297356
"""logits.stride(0) > width (row-slice of a wider buffer): exercises the

0 commit comments

Comments
 (0)