4242"""
4343
4444from functools import cache
45- from typing import Any
45+ from typing import Any , Literal
4646
4747import flydsl .compiler as flyc
4848import 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
116125def 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
0 commit comments