diff --git a/flashinfer/experimental/b12x/attention/dsa_indexer/tiled_topk.py b/flashinfer/experimental/b12x/attention/dsa_indexer/tiled_topk.py index 870b299cd14..7e0de11087f 100644 --- a/flashinfer/experimental/b12x/attention/dsa_indexer/tiled_topk.py +++ b/flashinfer/experimental/b12x/attention/dsa_indexer/tiled_topk.py @@ -569,6 +569,7 @@ def __init__( extent_splits: int = 1, smem_candidate_capacity: int = _DEFAULT_SMEM_CANDIDATES, write_values: bool = True, + skip_leq_topk: bool = False, ): self.extent_splits = int(extent_splits) self.is_tiled = is_tiled @@ -585,6 +586,7 @@ def __init__( self.output_physical_slots = bool(output_physical_slots) self.smem_candidate_capacity = int(smem_candidate_capacity) self.write_values = bool(write_values) + self.skip_leq_topk = bool(skip_leq_topk) if self.smem_candidate_capacity < self.topk: raise ValueError( "shared candidate capacity must cover top-k output capacity, got " @@ -797,7 +799,7 @@ class SharedStorage: need_radix = total_len > topk_static - if not need_radix: + if (not need_radix) & (not cutlass.const_expr(self.skip_leq_topk)): i = Int32(tx) while i < topk_static: is_valid = i < total_len @@ -1333,6 +1335,7 @@ def _build_row_topk_kernel( output_physical_slots: bool = False, smem_candidate_capacity: int = _DEFAULT_SMEM_CANDIDATES, write_values: bool = True, + skip_leq_topk: bool = False, ): return DSATiledTopkKernel( is_tiled=False, @@ -1343,6 +1346,7 @@ def _build_row_topk_kernel( output_physical_slots=output_physical_slots, smem_candidate_capacity=smem_candidate_capacity, write_values=write_values, + skip_leq_topk=skip_leq_topk, ) @@ -1718,6 +1722,7 @@ def run_row_topk( output_index_offset: int = 0, output_gather_table: torch.Tensor | None = None, write_values: bool = True, + skip_leq_topk: bool = False, launcher=None, launcher_sink: dict[tuple[object, ...], object] | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: @@ -1836,7 +1841,12 @@ def run_row_topk( Int32(0), current_cuda_stream(), ) - launcher_key = ("row", bool(output_gather_table is not None), bool(write_values)) + launcher_key = ( + "row", + bool(output_gather_table is not None), + bool(write_values), + bool(skip_leq_topk), + ) if isinstance(launcher, Mapping): launcher = launcher[launcher_key] if launcher is not None: @@ -1850,6 +1860,7 @@ def run_row_topk( output_gather_table is not None, smem_candidate_capacity, bool(write_values), + bool(skip_leq_topk), ) input_key_tensor = row_logits lengths_key_tensor = lengths @@ -1870,7 +1881,9 @@ def run_row_topk( "output_gather_table", output_gather_table_for_kernel, dynamic=True ), ( - "row_topk_v10_initialized_overflow_output", + "row_topk_v11_skip_leq_topk" + if skip_leq_topk + else "row_topk_v10_initialized_overflow_output", topk, output_gather_table is not None, smem_candidate_capacity, diff --git a/flashinfer/experimental/b12x/attention/qsa/_contract.py b/flashinfer/experimental/b12x/attention/qsa/_contract.py index f20a878e6b2..4406cb47258 100644 --- a/flashinfer/experimental/b12x/attention/qsa/_contract.py +++ b/flashinfer/experimental/b12x/attention/qsa/_contract.py @@ -38,6 +38,7 @@ _ALIGN_BYTES = 256 _SCORE_WORKSPACE_LIMIT_BYTES = 128 * 1024 * 1024 +_MAX_WORKSPACE_Q_ROWS = 2048 _MIN_TOPK_WORKSPACE_BYTES = 1024 * 1024 _STABLE_TOPK_BLOCK = 512 _MAX_SCORE_CHUNK_GROUPS = 65536 @@ -850,7 +851,7 @@ def _target_splits(caps: Caps, rows: int) -> tuple[int, int]: def _scratch_layout( caps: Caps, ) -> tuple[_ScratchLayout, int, int, int, int, int]: - workspace_q_rows = int(caps.max_q_rows) + workspace_q_rows = min(int(caps.max_q_rows), _MAX_WORKSPACE_Q_ROWS) score_width_limit = max( 1, int(caps.score_workspace_bytes or _SCORE_WORKSPACE_LIMIT_BYTES) @@ -2709,18 +2710,18 @@ def _qsa_decode_impl( caps=caps, _prepared=None if programs is None else programs.support, ) - prior_values = chunk_topk_values_b - prior_ids = chunk_topk_ids_b - final_ids = prior_ids + prior_values = chunk_topk_values + prior_ids = chunk_topk_ids + final_ids = chunk_topk_ids for score_chunk in range(int(num_score_chunks)): group_offset = score_chunk * int(score_chunk_groups) group_count = min( int(score_chunk_groups), int(caps.max_groups) - group_offset ) - output_values = ( - chunk_topk_values if score_chunk % 2 == 0 else chunk_topk_values_b + scratch_values = ( + chunk_topk_values if score_chunk == 0 else chunk_topk_values_b ) - output_ids = chunk_topk_ids if score_chunk % 2 == 0 else chunk_topk_ids_b + scratch_ids = chunk_topk_ids if score_chunk == 0 else chunk_topk_ids_b if group_offset: launch_stage_topk_carry( prior_values=prior_values, @@ -2743,14 +2744,16 @@ def _qsa_decode_impl( group_offset=group_offset, group_count=group_count, caps=caps, + skip_empty_chunks=True, _prepared=None if programs is None else programs.support, ) launch_topk_groups( scores=chunk_scores, eligible_counts=chunk_merge_lengths, - topk_values=output_values, - topk_group_ids=output_ids, + topk_values=scratch_values, + topk_group_ids=scratch_ids, group_budget=group_budget, + skip_leq_topk=True, _prepared=None if programs is None else programs.support, ) launch_stabilize_topk( @@ -2758,8 +2761,8 @@ def _qsa_decode_impl( merge_lengths=chunk_merge_lengths, prior_ids=prior_ids, eligible_counts=chunk_eligible, - topk_values=output_values, - topk_group_ids=output_ids, + topk_values=scratch_values, + topk_group_ids=scratch_ids, tie_counts=chunk_tie_counts, greater_counts=chunk_greater_counts, stable_values=chunk_stable_values, @@ -2768,10 +2771,11 @@ def _qsa_decode_impl( greater_totals=chunk_greater_totals, group_offset=group_offset, group_budget=group_budget, + dest_values=chunk_topk_values, + dest_ids=chunk_topk_ids, + preserve_empty_carry=True, _prepared=None if programs is None else programs.support, ) - prior_values, prior_ids = output_values, output_ids - final_ids = output_ids selected = selected_positions[row_slice] if int(caps.dcp_size) == 1: diff --git a/flashinfer/experimental/b12x/attention/qsa/_kernels.py b/flashinfer/experimental/b12x/attention/qsa/_kernels.py index e6f894c7edc..dda8ebbc81f 100644 --- a/flashinfer/experimental/b12x/attention/qsa/_kernels.py +++ b/flashinfer/experimental/b12x/attention/qsa/_kernels.py @@ -551,6 +551,7 @@ def _score_representatives_kernel( CP_INTERLEAVE: tl.constexpr, BLOCK_G: tl.constexpr, BLOCK_D: tl.constexpr, + SKIP_EMPTY_CHUNKS: tl.constexpr = False, ): row = tl.program_id(0) group_block = tl.program_id(1) @@ -585,7 +586,12 @@ def _score_representatives_kernel( chunk_eligible = tl.minimum(tl.maximum(eligible - GROUP_OFFSET, 0), GROUP_COUNT) if group_block == 0: tl.store(eligible_counts + row, eligible) - tl.store(merge_lengths + row, carry_count + chunk_eligible) + active_merge = carry_count + chunk_eligible + if SKIP_EMPTY_CHUNKS: + active_merge = tl.where( + (GROUP_OFFSET > 0) & (chunk_eligible == 0), 0, active_merge + ) + tl.store(merge_lengths + row, active_merge) local_groups = group_block * BLOCK_G + tl.arange(0, BLOCK_G) groups = GROUP_OFFSET + local_groups group_mask = local_groups < GROUP_COUNT @@ -661,6 +667,7 @@ def _score_representatives_tiled_kernel( TILE_ROWS: tl.constexpr, BLOCK_G: tl.constexpr, GROUP_TILES: tl.constexpr, + SKIP_EMPTY_CHUNKS: tl.constexpr = False, ): # One tensor-core product scores a tile of groups for a tile of query rows, # so each key tile is read once per row tile instead of once per row. @@ -698,7 +705,12 @@ def _score_representatives_tiled_kernel( chunk_eligible = tl.minimum(tl.maximum(eligible - GROUP_OFFSET, 0), GROUP_COUNT) if tl.program_id(1) == 0: tl.store(eligible_counts + rows, eligible, mask=row_mask) - tl.store(merge_lengths + rows, carry_count + chunk_eligible, mask=row_mask) + active_merge = carry_count + chunk_eligible + if SKIP_EMPTY_CHUNKS: + active_merge = tl.where( + (GROUP_OFFSET > 0) & (chunk_eligible == 0), 0, active_merge + ) + tl.store(merge_lengths + rows, active_merge, mask=row_mask) first_local = tl.program_id(1) * (BLOCK_G * GROUP_TILES) # Selection reads only each row's first merge_lengths columns, so groups # past a row's eligible count are neither scored nor stored. @@ -775,8 +787,10 @@ def _stage_topk_carry_kernel( BLOCK_K: tl.constexpr, ): row = tl.program_id(0) - columns = tl.arange(0, BLOCK_K) eligible = tl.load(eligible_counts + row) + if eligible <= GROUP_OFFSET: + return + columns = tl.arange(0, BLOCK_K) carry_count = tl.minimum(tl.minimum(eligible, GROUP_OFFSET), GROUP_BUDGET) values = tl.load( prior_values + row * GROUP_BUDGET + columns, @@ -834,10 +848,17 @@ def _copy_stable_topk_kernel( stable_ids, topk_values, topk_ids, + merge_lengths, + group_offset, GROUP_BUDGET: tl.constexpr, BLOCK_K: tl.constexpr, + PRESERVE_EMPTY_CARRY: tl.constexpr = False, ): row = tl.program_id(0) + if PRESERVE_EMPTY_CARRY: + if group_offset > 0: + if tl.load(merge_lengths + row) == 0: + return columns = tl.arange(0, BLOCK_K) mask = columns < GROUP_BUDGET values = tl.load( @@ -1283,6 +1304,7 @@ def launch_score_representatives( group_offset: int, group_count: int, caps, + skip_empty_chunks: bool = False, ) -> None: rows = int(prepared_query.shape[0]) block_g = 32 @@ -1315,6 +1337,7 @@ def launch_score_representatives( CP_INTERLEAVE=int(getattr(caps, "cp_kv_cache_interleave_size", 1)), BLOCK_G=block_g, BLOCK_D=triton.next_power_of_2(int(caps.index_head_dim)), + SKIP_EMPTY_CHUNKS=bool(skip_empty_chunks), num_warps=4, ) @@ -1344,6 +1367,7 @@ def launch_score_representatives_tiled( group_offset: int, group_count: int, caps, + skip_empty_chunks: bool = False, ) -> None: rows = int(prepared_query.shape[0]) context = _support_launch_context.get() @@ -1387,6 +1411,7 @@ def launch_score_representatives_tiled( TILE_ROWS=tile_rows, BLOCK_G=block_g, GROUP_TILES=group_tiles, + SKIP_EMPTY_CHUNKS=bool(skip_empty_chunks), num_warps=warps, ) if selected and not compiling: @@ -1423,6 +1448,7 @@ def launch_topk_groups( topk_values: torch.Tensor, topk_group_ids: torch.Tensor, group_budget: int, + skip_leq_topk: bool = False, ) -> None: # This is the exact single-row radix kernel, not the cooperative multi-CTA # persistent path. @@ -1444,6 +1470,7 @@ def launch_topk_groups( topk=int(group_budget), output_values=topk_values, output_indices=topk_group_ids, + skip_leq_topk=bool(skip_leq_topk), **options, ) @@ -1488,6 +1515,9 @@ def launch_stabilize_topk( greater_totals: torch.Tensor, group_offset: int, group_budget: int, + dest_values: torch.Tensor | None = None, + dest_ids: torch.Tensor | None = None, + preserve_empty_carry: bool = False, ) -> None: """Make threshold ties exact and stable by retaining lower group IDs.""" rows = int(scores.shape[0]) @@ -1509,18 +1539,24 @@ def launch_stabilize_topk( group_offset=group_offset, group_budget=group_budget, prepared=prepared, + preserve_empty_carry=bool(preserve_empty_carry), ) if context is not None and context[1]: context[0]["stable_selection"] = raw + out_values = topk_values if dest_values is None else dest_values + out_ids = topk_group_ids if dest_ids is None else dest_ids _launch_triton( _copy_stable_topk_kernel, (rows,), stable_values, stable_ids, - topk_values, - topk_group_ids, + out_values, + out_ids, + merge_lengths, + int(group_offset), GROUP_BUDGET=int(group_budget), BLOCK_K=block_k, + PRESERVE_EMPTY_CARRY=bool(preserve_empty_carry), num_warps=8, ) diff --git a/flashinfer/experimental/b12x/attention/qsa/_stable_select_cute.py b/flashinfer/experimental/b12x/attention/qsa/_stable_select_cute.py index 9530ad50d3f..f6928e06709 100644 --- a/flashinfer/experimental/b12x/attention/qsa/_stable_select_cute.py +++ b/flashinfer/experimental/b12x/attention/qsa/_stable_select_cute.py @@ -28,10 +28,17 @@ class StableSelectionKernel: - def __init__(self, budget, input_order=False, indices_only=False): + def __init__( + self, + budget, + input_order=False, + indices_only=False, + preserve_empty_carry=False, + ): self.budget = int(budget) self.input_order = bool(input_order) self.indices_only = bool(indices_only) + self.preserve_empty_carry = bool(preserve_empty_carry) @cute.jit def __call__( @@ -55,145 +62,171 @@ def kernel(self, pointers: tuple, stride: Int64, group_offset: Int32): base = row.to(Int64) * Int64(self.budget) score_base = row.to(Int64) * stride length = lengths[row].to(Int32) - selected = cutlass.min(length, Int32(self.budget)) - if length <= self.budget: - carry = cutlass.min( - cutlass.min(eligible[row].to(Int32), group_offset), Int32(self.budget) - ) - for part in cutlass.range_constexpr(self.budget // 256): - column = tid + Int32(part * 256) - identifier = Int32(-1) - value = Float32(-float("inf")) - if column < length: - identifier = group_offset + column - carry - if column < carry: - identifier = prior_ids[base + column.to(Int64)].to(Int32) - if cutlass.const_expr(not self.indices_only): - value = scores[score_base + column.to(Int64)].to(Float32) - ids[base + column.to(Int64)] = identifier - values[base + column.to(Int64)] = value - else: - allocator = cutlass.utils.SmemAllocator() - minima = allocator.allocate_tensor( - Float32, cute.make_layout((8,)), byte_alignment=16 - ) - greater_counts = allocator.allocate_tensor( - Int32, cute.make_layout((8,)), byte_alignment=16 - ) - tie_counts = allocator.allocate_tensor( - Int32, cute.make_layout((8,)), byte_alignment=16 - ) - threshold = allocator.allocate_tensor( - Float32, cute.make_layout((1,)), byte_alignment=4 - ) - minimum = Float32(float("inf")) - for part in cutlass.range_constexpr(self.budget // 256): - column = tid + Int32(part * 256) - if column < selected: - minimum = cutlass.min( - minimum, Float32(top_values[base + column.to(Int64)]) - ) - values[base + column.to(Int64)] = Float32(-float("inf")) - ids[base + column.to(Int64)] = Int32(-1) - for shift in cutlass.range_constexpr(5): - minimum = cutlass.min( - minimum, cute.arch.shuffle_sync_bfly(minimum, offset=16 >> shift) + skip_empty = Int32(1 if self.preserve_empty_carry else 0) + if ( + (skip_empty == Int32(0)) + | (group_offset == Int32(0)) + | (length > Int32(0)) + ): + selected = cutlass.min(length, Int32(self.budget)) + if length <= self.budget: + carry = cutlass.min( + cutlass.min(eligible[row].to(Int32), group_offset), + Int32(self.budget), + ) + for part in cutlass.range_constexpr(self.budget // 256): + column = tid + Int32(part * 256) + identifier = Int32(-1) + value = Float32(-float("inf")) + if column < length: + identifier = group_offset + column - carry + if column < carry: + identifier = prior_ids[base + column.to(Int64)].to(Int32) + if cutlass.const_expr(not self.indices_only): + value = scores[score_base + column.to(Int64)].to(Float32) + ids[base + column.to(Int64)] = identifier + values[base + column.to(Int64)] = value + else: + allocator = cutlass.utils.SmemAllocator() + minima = allocator.allocate_tensor( + Float32, cute.make_layout((8,)), byte_alignment=16 + ) + greater_counts = allocator.allocate_tensor( + Int32, cute.make_layout((8,)), byte_alignment=16 + ) + tie_counts = allocator.allocate_tensor( + Int32, cute.make_layout((8,)), byte_alignment=16 + ) + threshold = allocator.allocate_tensor( + Float32, cute.make_layout((1,)), byte_alignment=4 ) - if lane == Int32(0): - minima[warp] = minimum - cute.arch.sync_threads() - if tid == Int32(0): minimum = Float32(float("inf")) - for w in cutlass.range_constexpr(8): - minimum = cutlass.min(minimum, Float32(minima[w])) - threshold[0] = minimum - cute.arch.sync_threads() - cutoff = Float32(threshold[0]) + for part in cutlass.range_constexpr(self.budget // 256): + column = tid + Int32(part * 256) + if column < selected: + minimum = cutlass.min( + minimum, Float32(top_values[base + column.to(Int64)]) + ) + values[base + column.to(Int64)] = Float32(-float("inf")) + ids[base + column.to(Int64)] = Int32(-1) + for shift in cutlass.range_constexpr(5): + minimum = cutlass.min( + minimum, + cute.arch.shuffle_sync_bfly(minimum, offset=16 >> shift), + ) + if lane == Int32(0): + minima[warp] = minimum + cute.arch.sync_threads() + if tid == Int32(0): + minimum = Float32(float("inf")) + for w in cutlass.range_constexpr(8): + minimum = cutlass.min(minimum, Float32(minima[w])) + threshold[0] = minimum + cute.arch.sync_threads() + cutoff = Float32(threshold[0]) - # Each warp owns a contiguous span so threshold ties retain earlier - # input positions while both score scans use coalesced memory loads. - tiles = (length + Int32(255)) // Int32(256) - span = tiles * Int32(32) - start = warp * span - ng, nt = Int32(0), Int32(0) - for tile in cutlass.range(tiles): - column = start + tile * Int32(32) + lane - if column < length: - value = Float32(scores[score_base + column.to(Int64)]) - if value > cutoff: - ng += Int32(1) - if value == cutoff: - nt += Int32(1) - for shift in cutlass.range_constexpr(5): - ng += cute.arch.shuffle_sync_bfly(ng, offset=16 >> shift) - nt += cute.arch.shuffle_sync_bfly(nt, offset=16 >> shift) - if lane == Int32(0): - greater_counts[warp], tie_counts[warp] = ng, nt - cute.arch.sync_threads() - greater_before, ties_before, total_greater = Int32(0), Int32(0), Int32(0) - for w in cutlass.range_constexpr(8): - count = Int32(greater_counts[w]) - total_greater += count - if Int32(w) < warp: - greater_before += count - ties_before += Int32(tie_counts[w]) - need = selected - total_greater - carry = cutlass.min( - cutlass.min(eligible[row].to(Int32), group_offset), Int32(self.budget) - ) - for tile in cutlass.range(tiles): - column = start + tile * Int32(32) + lane - value = Float32(-float("inf")) - is_greater, is_tie = Int32(0), Int32(0) - if column < length: - value = Float32(scores[score_base + column.to(Int64)]) - if value > cutoff: - is_greater = Int32(1) - if value == cutoff: - is_tie = Int32(1) - gp, tp = is_greater, is_tie + # Each warp owns a contiguous span so threshold ties retain earlier + # input positions while both score scans use coalesced memory loads. + tiles = (length + Int32(255)) // Int32(256) + span = tiles * Int32(32) + start = warp * span + ng, nt = Int32(0), Int32(0) + for tile in cutlass.range(tiles): + column = start + tile * Int32(32) + lane + if column < length: + value = Float32(scores[score_base + column.to(Int64)]) + if value > cutoff: + ng += Int32(1) + if value == cutoff: + nt += Int32(1) for shift in cutlass.range_constexpr(5): - distance = Int32(1 << shift) - source_lane = cutlass.max(lane - distance, Int32(0)) - g = cute.arch.shuffle_sync(gp, source_lane) - t = cute.arch.shuffle_sync(tp, source_lane) - if lane >= distance: - gp += g - tp += t - tie_rank = ties_before + tp - Int32(1) - chosen = (is_greater != Int32(0)) | ( - (is_tie != Int32(0)) & (tie_rank < need) + ng += cute.arch.shuffle_sync_bfly(ng, offset=16 >> shift) + nt += cute.arch.shuffle_sync_bfly(nt, offset=16 >> shift) + if lane == Int32(0): + greater_counts[warp], tie_counts[warp] = ng, nt + cute.arch.sync_threads() + greater_before, ties_before, total_greater = ( + Int32(0), + Int32(0), + Int32(0), ) - if chosen: - destination = greater_before + gp - Int32(1) - if is_tie != Int32(0): - destination = total_greater + tie_rank - if cutlass.const_expr(self.input_order): - destination = ( - greater_before - + gp - + cutlass.min(ties_before + tp, need) - - Int32(1) - ) - global_id = group_offset + column - carry - if column < carry: - global_id = prior_ids[base + column.to(Int64)].to(Int32) - values[base + destination.to(Int64)] = value - ids[base + destination.to(Int64)] = global_id - greater_before += cute.arch.shuffle_sync(gp, Int32(31)) - ties_before += cute.arch.shuffle_sync(tp, Int32(31)) + for w in cutlass.range_constexpr(8): + count = Int32(greater_counts[w]) + total_greater += count + if Int32(w) < warp: + greater_before += count + ties_before += Int32(tie_counts[w]) + need = selected - total_greater + carry = cutlass.min( + cutlass.min(eligible[row].to(Int32), group_offset), + Int32(self.budget), + ) + for tile in cutlass.range(tiles): + column = start + tile * Int32(32) + lane + value = Float32(-float("inf")) + is_greater, is_tie = Int32(0), Int32(0) + if column < length: + value = Float32(scores[score_base + column.to(Int64)]) + if value > cutoff: + is_greater = Int32(1) + if value == cutoff: + is_tie = Int32(1) + gp, tp = is_greater, is_tie + for shift in cutlass.range_constexpr(5): + distance = Int32(1 << shift) + source_lane = cutlass.max(lane - distance, Int32(0)) + g = cute.arch.shuffle_sync(gp, source_lane) + t = cute.arch.shuffle_sync(tp, source_lane) + if lane >= distance: + gp += g + tp += t + tie_rank = ties_before + tp - Int32(1) + chosen = (is_greater != Int32(0)) | ( + (is_tie != Int32(0)) & (tie_rank < need) + ) + if chosen: + destination = greater_before + gp - Int32(1) + if is_tie != Int32(0): + destination = total_greater + tie_rank + if cutlass.const_expr(self.input_order): + destination = ( + greater_before + + gp + + cutlass.min(ties_before + tp, need) + - Int32(1) + ) + global_id = group_offset + column - carry + if column < carry: + global_id = prior_ids[base + column.to(Int64)].to(Int32) + values[base + destination.to(Int64)] = value + ids[base + destination.to(Int64)] = global_id + greater_before += cute.arch.shuffle_sync(gp, Int32(31)) + ties_before += cute.arch.shuffle_sync(tp, Int32(31)) -def compile_stable_selection(budget, device, input_order=False, indices_only=False): +def compile_stable_selection( + budget, + device, + input_order=False, + indices_only=False, + preserve_empty_carry=False, +): if indices_only and not input_order: raise ValueError( "indices-only selection requires input ordering and an unsegmented score row" ) - compile_key = (int(budget), bool(input_order), bool(indices_only)) + compile_key = ( + int(budget), + bool(input_order), + bool(indices_only), + bool(preserve_empty_carry), + ) key = (device, compile_key) raw = _CACHE.get(key) if raw is None: - kernel = StableSelectionKernel(budget, input_order, indices_only) + kernel = StableSelectionKernel( + budget, input_order, indices_only, preserve_empty_carry + ) raise_if_kernel_resolution_frozen("cute.compile", target=kernel, cache_key=key) pointers = tuple( make_ptr(t, 16, cute.AddressSpace.gmem, assumed_align=t.width // 8) @@ -208,7 +241,7 @@ def compile_stable_selection(budget, device, input_order=False, indices_only=Fal current_cuda_stream(), compile_spec=KernelCompileSpec.from_key( "attention.qsa.stable_selection", - 3, + 4, compile_key, ), ) @@ -230,6 +263,7 @@ def launch_stable_selection( prepared=None, input_order=False, indices_only=False, + preserve_empty_carry=False, ): if indices_only and group_offset != 0: raise ValueError("indices-only selection does not accept segmented scores") @@ -241,7 +275,11 @@ def launch_stable_selection( prepared if prepared is not None else compile_stable_selection( - group_budget, device, input_order, indices_only + group_budget, + device, + input_order, + indices_only, + preserve_empty_carry, ) ) if compile_only_launches_enabled(): diff --git a/tests/experimental/b12x/attention/test_qsa_contract.py b/tests/experimental/b12x/attention/test_qsa_contract.py index 6dbe79a52b8..aa236880336 100644 --- a/tests/experimental/b12x/attention/test_qsa_contract.py +++ b/tests/experimental/b12x/attention/test_qsa_contract.py @@ -1973,17 +1973,22 @@ def test_qsa_paged_representative_scores_match_fp32_reference() -> None: @pytest.mark.parametrize( - ("score_workspace_bytes", "chunks", "width"), - [(None, 9, 8192), (512 * 1024 * 1024, 3, 32768), (1024 * 1024 * 1024, 1, 65536)], + ("max_q_rows", "score_workspace_bytes", "chunks", "width"), + [ + (4096, None, 5, 16384), + (8192, None, 5, 16384), + (4096, 256 * 1024 * 1024, 3, 32768), + (4096, 512 * 1024 * 1024, 1, 65536), + ], ) def test_qsa_score_workspace_bound_sets_selection_chunks( - score_workspace_bytes, chunks, width + max_q_rows, score_workspace_bytes, chunks, width ) -> None: from b12x.preparation.types import FrozenMapping caps = _caps( "cuda:0", - max_q_rows=4096, + max_q_rows=max_q_rows, max_seq_len=262144, main_page_size=64, compressed_page_size=16, @@ -1993,7 +1998,10 @@ def test_qsa_score_workspace_bound_sets_selection_chunks( ) query = qsa_contract._query_from_caps(caps, FrozenMapping()) assert qsa_contract._caps_from_query(query, ordinal=0) == caps - _, chunk_groups, workspace_width, num_chunks, *_ = qsa_contract._scratch_layout(caps) + _, chunk_groups, workspace_width, num_chunks, _, workspace_q_rows = ( + qsa_contract._scratch_layout(caps) + ) + assert workspace_q_rows == min(max_q_rows, 2048) assert (num_chunks, workspace_width) == (chunks, width) assert chunk_groups * num_chunks >= caps.max_groups diff --git a/tests/experimental/b12x/attention/test_qsa_stable_selection.py b/tests/experimental/b12x/attention/test_qsa_stable_selection.py index 991a2188ec1..b550ded0b31 100644 --- a/tests/experimental/b12x/attention/test_qsa_stable_selection.py +++ b/tests/experimental/b12x/attention/test_qsa_stable_selection.py @@ -140,3 +140,96 @@ def run(live_rows=rows): assert torch.all(ids[live_rows:] == -98765) assert _CACHE.keys() == resolved.keys() assert all(_CACHE[key] is value for key, value in resolved.items()) + + +@pytest.mark.parametrize("budget", [512, 2048]) +def test_stable_selection_preserve_empty_carry_keeps_dest_untouched(budget): + device = require_b12x() + rows, width, group_offset = 6, budget + 1024, 4096 + generator = torch.Generator(device=device).manual_seed(4242) + scores = torch.rand((rows, width), generator=generator, device=device) + scores[:, :budget].copy_(scores[:, :budget].sort(descending=True).values) + # Rows 0, 2, 4 have merge_lengths == 0 (no new eligible groups in this chunk); + # rows 1, 3, 5 have active merge lengths across <= budget and > budget regimes. + lengths = torch.tensor( + [0, budget - 13, 0, budget, 0, width], dtype=torch.int32, device=device + ) + eligible = torch.tensor( + [ + 128, + budget - 13, + group_offset, + budget, + 512, + group_offset + width - budget, + ], + dtype=torch.int32, + device=device, + ) + prior = ( + torch.arange(budget, dtype=torch.int32, device=device) + .expand(rows, -1) + .contiguous() + ) + dest_values = torch.full((rows, budget), 7.25, dtype=torch.float32, device=device) + dest_ids = torch.full((rows, budget), 1234, dtype=torch.int32, device=device) + scratch_values = torch.empty_like(dest_values) + scratch_ids = torch.empty_like(dest_ids) + masked = scores.masked_fill( + torch.arange(width, device=device)[None, :] >= lengths[:, None], + -float("inf"), + ) + scratch_values.copy_(masked.topk(budget, sorted=False).values) + stable_values = torch.full_like(dest_values, -99.0) + stable_ids = torch.full_like(dest_ids, -99) + blocks = (width + 511) // 512 + counts = torch.empty((rows, blocks), dtype=torch.int32, device=device) + other_counts = torch.empty_like(counts) + thresholds = torch.empty((rows,), dtype=torch.float32, device=device) + totals = torch.empty_like(lengths) + + launch_stabilize_topk( + scores=scores, + merge_lengths=lengths, + prior_ids=prior, + eligible_counts=eligible, + topk_values=scratch_values, + topk_group_ids=scratch_ids, + tie_counts=counts, + greater_counts=other_counts, + stable_values=stable_values, + stable_ids=stable_ids, + thresholds=thresholds, + greater_totals=totals, + group_offset=group_offset, + group_budget=budget, + dest_values=dest_values, + dest_ids=dest_ids, + preserve_empty_carry=True, + ) + torch.cuda.synchronize(device) + + for row in (0, 2, 4): + assert torch.all(dest_values[row] == 7.25) + assert torch.all(dest_ids[row] == 1234) + assert torch.all(stable_values[row] == -99.0) + assert torch.all(stable_ids[row] == -99) + + for row in (1, 3, 5): + length = int(lengths[row]) + carry = min(int(eligible[row]), group_offset, budget) + global_ids = ( + torch.arange(length, device=device, dtype=torch.int32) + + group_offset + - carry + ) + global_ids[:carry] = prior[row, :carry] + order = torch.argsort(scores[row, :length], descending=True, stable=True)[ + :budget + ] + expected_v = torch.full((budget,), -float("inf"), device=device) + expected_i = torch.full((budget,), -1, dtype=torch.int32, device=device) + expected_v[: len(order)] = scores[row, order] + expected_i[: len(order)] = global_ids[order] + torch.testing.assert_close(dest_values[row], expected_v, rtol=0, atol=0) + assert torch.equal(dest_ids[row], expected_i)