Skip to content

Commit 135ebca

Browse files
committed
Add parameter to mask out non-inf values in the kernel.
1 parent c06b8db commit 135ebca

3 files changed

Lines changed: 56 additions & 0 deletions

File tree

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ def create_topk_per_row_decode_tiered_kernel(
124124
tiered_mid_cap: int = 16,
125125
tiered_mid_max: int = 65536,
126126
tiered_long_cap: int = 32,
127+
mask_non_finite: bool = True,
127128
) -> Any:
128129
short_max = tiered_short_max
129130
mid_cap = tiered_mid_cap
@@ -158,6 +159,7 @@ def create_topk_per_row_decode_tiered_kernel(
158159
f"{f'_s{tiered_short_max}_mc{tiered_mid_cap}' if tiered else ''}"
159160
f"{f'_mm{tiered_mid_max}_lc{tiered_long_cap}' if tiered else ''}"
160161
f"{'_1wg' if short_tier else ''}"
162+
f"{'_mf' if mask_non_finite else ''}"
161163
)
162164

163165
@fx.struct
@@ -200,6 +202,8 @@ def topk_per_row_decode_tiered_kernel(
200202
c_bins_idx = fx.Index(num_buckets)
201203
c_parts = fx.Int32(blocks_per_row)
202204
c_sign_bit = fx.Int32(-2147483648)
205+
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
203207
c_neg_one = fx.Int32(-1)
204208
c_zero_f32 = fx.Float32(0.0)
205209
c_row_ws = fx.Int32(row_workspace_slots)
@@ -388,10 +392,20 @@ def row_barrier(token: int):
388392
spin_until_slot_ge(counter_slot(COUNTER_PASS_DONE), token_value)
389393
gpu.barrier()
390394

395+
def mask_nonfinite(val):
396+
if const_expr(not mask_non_finite):
397+
return val
398+
bits = ArithValue(val).bitcast(T.i32)
399+
is_nonfinite = ArithValue(
400+
ArithValue(bits) & ArithValue(c_exp_mask)
401+
) == ArithValue(c_exp_mask)
402+
return is_nonfinite.select(c_neg_fltmax, val)
403+
391404
def radix_twiddle_key(val):
392405
# Map larger fp32 values to smaller unsigned keys so ascending
393406
# bucket scans select descending values. Normalize signed zero to
394407
# keep tie handling value-equivalent.
408+
val = mask_nonfinite(val)
395409
key_val = (ArithValue(val) == ArithValue(c_zero_f32)).select(
396410
c_zero_f32, val
397411
)
@@ -758,6 +772,7 @@ def one_workgroup_short_tier():
758772
c_thirtyone = fx.Int32(31)
759773

760774
def ordered_key(val):
775+
val = mask_nonfinite(val)
761776
key_val = (ArithValue(val) == ArithValue(c_zero_f32)).select(
762777
c_zero_f32, val
763778
)

‎aiter/ops/flydsl/topk_per_row_decode.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ def _environ_kernel_config() -> dict:
6868
tiered_mid_max=_env_int("FLYDSL_TOPK_TIERED_MID_MAX"),
6969
tiered_long_cap=_env_int("FLYDSL_TOPK_TIERED_LONG_CAP"),
7070
bits_per_pass=_env_int("FLYDSL_TOPK_TIERED_BPP"),
71+
# 0/1 override for the non-finite mask (default on); set 0 to disable.
72+
mask_non_finite=_env_int("FLYDSL_TOPK_TIERED_MASK_NONFINITE"),
7173
)
7274
return {k: v for k, v in cfg.items() if v is not None}
7375

@@ -122,6 +124,7 @@ def _default_kernel_config(
122124
tiered_mid_cap=tiered_mid_cap_default,
123125
tiered_mid_max=_TIERED_MID_MAX,
124126
tiered_long_cap=tiered_long_cap_default,
127+
mask_non_finite=True,
125128
)
126129

127130

‎op_tests/flydsl_tests/test_flydsl_topk_per_row_decode.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,44 @@ def test_all_identical_values(k):
254254
_assert_batch(logits, indices, row_ends, k)
255255

256256

257+
@pytest.mark.parametrize("L", [8192, 120003], ids=["short", "long"])
258+
@pytest.mark.parametrize("k", [256, 2048])
259+
def test_non_finite_never_selected(k, L):
260+
"""+inf / -inf / NaN in the valid region must never be selected"""
261+
device = torch.device("cuda")
262+
torch.manual_seed(_SEED)
263+
logits = torch.randn((1, L), dtype=torch.float32, device=device)
264+
# Scatter non-finite through the valid region. +inf/NaN are the ones a raw-bit
265+
# radix-select wrongly ranks at the very top; -inf should sort out naturally.
266+
bad = {
267+
10: float("inf"),
268+
100: float("nan"),
269+
L // 3: float("inf"),
270+
L // 2: float("-inf"),
271+
L - 5: float("nan"),
272+
}
273+
for pos, val in bad.items():
274+
logits[0, pos] = val
275+
sl = torch.tensor([L], dtype=torch.int32, device=device)
276+
277+
indices = _run(logits, sl, 1, 1, k)
278+
got = indices[0].to(device).long()
279+
280+
# (a) no selected index points to a non-finite value
281+
sel_vals = logits[0, got]
282+
assert torch.isfinite(sel_vals).all(), (
283+
f"selected non-finite values: "
284+
f"{sel_vals[~torch.isfinite(sel_vals)][:8].tolist()}"
285+
)
286+
# (b) the selected set is the top-k of the finite values (non-finite -> -inf)
287+
sanitized = torch.where(
288+
torch.isfinite(logits[0]),
289+
logits[0],
290+
torch.full_like(logits[0], float("-inf")),
291+
)
292+
_assert_row_topk_set(sanitized.cpu(), indices[0].cpu(), k, L)
293+
294+
257295
@pytest.mark.parametrize("k", [512, 2048])
258296
def test_row_strided_logits(k):
259297
"""logits.stride(0) > width (row-slice of a wider buffer): exercises the

0 commit comments

Comments
 (0)