3838}
3939
4040
41+ def _next_pow2 (n : int ) -> int :
42+ if n <= 1 :
43+ return 1
44+ return 1 << (n - 1 ).bit_length ()
45+
46+
4147def _env_int (name : str , default : int | None = None ) -> int | None :
4248 value = os .environ .get (name )
4349 if value is None :
@@ -84,9 +90,11 @@ def _default_kernel_config(
8490
8591 # Grid width per row: enough workgroups to cover the row at LOAD_VEC elements
8692 # per thread, clamped to [2, 32] (32 = the wg cap the mid/long tiers can use;
87- # BLOCK_THREADS is fixed at 1024, so max_blocks is 32).
93+ # BLOCK_THREADS is fixed at 1024, so max_blocks is 32). blocks_per_row is
94+ # rounded to the next pow 2 to reduce the number of compilations.
8895 items_per_block = _TIERED_LOAD_VEC * _TIERED_BLOCK_THREADS
89- blocks_per_row = min (32 , max (2 , math .ceil (max_model_len / items_per_block )))
96+ raw_blocks_per_row = max (2 , math .ceil (max_model_len / items_per_block ))
97+ blocks_per_row = min (32 , _next_pow2 (raw_blocks_per_row ))
9098
9199 # bits_per_pass: 11 (2048-bin LDS histogram) whenever the arch can afford it;
92100 # the short tier requires 11. gfx942/gfx950 both qualify (CU count >= 128).
@@ -113,9 +121,11 @@ def _default_kernel_config(
113121
114122 # Batch-aware short vs multi-block crossover (arch-specific base/slope/cap). The
115123 # multi-block barrier floor grows under CU contention as more rows launch, while
116- # the single-workgroup path is flat in batch.
124+ # the single-workgroup path is flat in batch. Bucket num_rows to the next pow 2
125+ # for the crossover, so nearby batch sizes share one compiled kernel.
117126 base , slope , cap = _SHORT_MAX_PARAMS .get (arch , _SHORT_MAX_PARAMS ["gfx942" ])
118- tiered_short_max = min (cap , base + num_rows * slope )
127+ short_max_rows = _next_pow2 (num_rows )
128+ tiered_short_max = min (cap , base + short_max_rows * slope )
119129
120130 return dict (
121131 blocks_per_row = blocks_per_row ,
@@ -248,11 +258,18 @@ def flydsl_top_k_per_row_decode_workspace_size(
248258
249259
250260@functools .lru_cache (maxsize = 16384 )
251- def _compile_launcher (
261+ def _build_launcher (
252262 top_k : int ,
253263 num_rows : int ,
254264 max_model_len : int ,
255265):
266+ """Build (and lru-cache) the launcher + workspace metadata for this shape.
267+
268+ Returns the flyc.jit launcher object, does not compile. The first
269+ _run_compiled() call triggers flyc.compile.
270+
271+ Cached per unique (top_k, num_rows, max_model_len).
272+ """
256273 kernel_config = _kernel_config (num_rows , max_model_len )
257274
258275 workspace_slots = topk_workspace_slots (
@@ -386,7 +403,7 @@ def flydsl_top_k_per_row_decode(
386403 workspace ,
387404 )
388405
389- launcher , workspace_slots , workspace_zero = _compile_launcher (
406+ launcher , workspace_slots , workspace_zero = _build_launcher (
390407 k ,
391408 numRows ,
392409 logits .shape [1 ],
0 commit comments