Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions flashinfer/experimental/b12x/attention/dsa_indexer/tiled_topk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 "
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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,
)


Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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,
Expand Down
30 changes: 17 additions & 13 deletions flashinfer/experimental/b12x/attention/qsa/_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand All @@ -2743,23 +2744,25 @@ 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(
scores=chunk_scores,
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,
Expand All @@ -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:
Expand Down
46 changes: 41 additions & 5 deletions flashinfer/experimental/b12x/attention/qsa/_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
)

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand All @@ -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,
)

Expand Down Expand Up @@ -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])
Expand All @@ -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,
)

Expand Down
Loading
Loading