Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 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
105 changes: 41 additions & 64 deletions python/sglang/kernels/ops/attention/dsv4/candidate_blocks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
"""Candidate block selection of the two-level indexer: the per-row block counts
and sparse-row lengths, the block keys and the JIT block top-k, and the torch
block ids and masks."""
"""Candidate blocks of the two-level indexer: a candidate source keeps whole
blocks of ``block_size`` compressed positions, its newest block always, and a
consumer selects among the kept blocks only.

The per-row block counts and sparse-row lengths, the block keys, the block
selection (the JIT chain on SM100, torch elsewhere), and the torch top-k among
chosen blocks."""

from typing import Optional, Union

Expand Down Expand Up @@ -142,83 +146,56 @@ def amax_topk_blocks(
return blocks


def mask_topk_scores(
scores: torch.Tensor,
indices: torch.Tensor,
offsets: Optional[torch.Tensor] = None,
) -> torch.Tensor:
"""Keep masked indexer scores out of attention even when top-k underfills."""
columns = indices.to(torch.int64)
if offsets is not None:
columns = columns - offsets[:, None]
selected_scores = scores.gather(1, columns.clamp(0, scores.shape[1] - 1))
valid = (
(columns >= 0) & (columns < scores.shape[1]) & (selected_scores > -torch.inf)
)
return indices.masked_fill(~valid, -1)


def _candidate_block_topk(
def select_candidate_block_ids(
logits: torch.Tensor,
compress_lens: Union[torch.Tensor, int],
topk_blocks: int,
block_size: int,
) -> torch.return_types.topk:
) -> torch.Tensor:
"""The torch block selection: per row the ids of the ``topk_blocks`` blocks
with the largest maximum score, the block holding position
``compress_lens - 1`` always kept; int32 ``[rows, min(topk_blocks, blocks)]``,
unordered, ``-1`` where a row has fewer finite blocks. ``logits`` must already
be ``-inf`` past each row's causal length."""
width = logits.size(-1)
padding = -width % block_size
scores = F.pad(logits, (0, padding), value=-torch.inf) if padding else logits
scores = scores.unflatten(-1, (-1, block_size)).amax(dim=-1)
num_blocks = scores.size(-1)

last = (compress_lens - 1) // block_size
scores = scores.masked_fill(
torch.arange(num_blocks, device=logits.device) == last, torch.inf
)

return scores.topk(min(topk_blocks, num_blocks), dim=-1)


def select_candidate_block_ids(
logits: torch.Tensor,
compress_lens: Union[torch.Tensor, int],
topk_blocks: int,
block_size: int,
) -> torch.Tensor:
top = _candidate_block_topk(
logits=logits,
compress_lens=compress_lens,
topk_blocks=topk_blocks,
block_size=block_size,
)
top = scores.topk(min(topk_blocks, num_blocks), dim=-1)
return top.indices.to(torch.int32).masked_fill_(~(top.values > -torch.inf), -1)


def candidate_block_mask(
blocks: torch.Tensor, width: int, block_size: int
) -> torch.Tensor:
num_blocks = (width + block_size - 1) // block_size
keep = torch.zeros(
(*blocks.shape[:-1], num_blocks + 1), dtype=torch.bool, device=blocks.device
)
keep.scatter_(-1, blocks.to(torch.int64).masked_fill(blocks < 0, num_blocks), True)
return keep[..., :num_blocks].repeat_interleave(block_size, dim=-1)[..., :width]


def select_candidate_blocks(
logits: torch.Tensor,
compress_lens: Union[torch.Tensor, int],
topk_blocks: int,
def topk_among_blocks(
scores: torch.Tensor,
lens: torch.Tensor,
blocks: torch.Tensor,
k: int,
block_size: int,
) -> torch.Tensor:
top = _candidate_block_topk(
logits=logits,
compress_lens=compress_lens,
topk_blocks=topk_blocks,
block_size=block_size,
"""The torch top-``k`` of each row among its chosen blocks: ``scores``
``[rows, width]`` indexed by position, ``lens`` ``[rows]`` the causal length,
``blocks`` ``[rows, n]`` block ids with ``-1`` padding. Returns int64
``[rows, k]`` positions, unordered, ``-1`` where a row has fewer than ``k``
finite candidates; positions at or past ``lens`` never count."""
rows, width = scores.shape
if width == 0:
return torch.full((rows, k), -1, dtype=torch.int64, device=scores.device)
offsets = torch.arange(block_size, device=scores.device)
columns = (blocks.to(torch.int64)[:, :, None] * block_size + offsets).flatten(1)
valid = (
(blocks >= 0).repeat_interleave(block_size, dim=1)
& (columns < lens.to(torch.int64)[:, None])
& (columns < width)
)
width = logits.shape[-1]
num_blocks = (width + block_size - 1) // block_size
keep = torch.zeros(
(*logits.shape[:-1], num_blocks), dtype=torch.bool, device=logits.device
).scatter_(-1, top.indices, top.values > -torch.inf)
return keep.repeat_interleave(block_size, dim=-1)[..., :width]
candidates = scores.gather(1, columns.clamp(0, width - 1))
candidates = candidates.masked_fill(~valid, -torch.inf)
top = candidates.topk(min(k, candidates.shape[1]), dim=-1, sorted=False)
picked = columns.gather(1, top.indices).masked_fill(~(top.values > -torch.inf), -1)
if picked.shape[1] < k:
picked = F.pad(picked, (0, k - picked.shape[1]), value=-1)
return picked
14 changes: 7 additions & 7 deletions python/sglang/kernels/ops/attention/dsv4/topk.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,13 +331,13 @@ def topk_transform_packed_v2(
def topk_transform_sparse(
logits: torch.Tensor,
valid_lens: torch.Tensor,
phys_blocks: torch.Tensor,
page_indices: torch.Tensor,
blocks: torch.Tensor,
out_indices: torch.Tensor,
) -> None:
"""Top-``k`` (``k = page_indices.shape[1]``) of each row of the bf16 sparse
``logits`` within its first ``valid_lens[b]`` columns, as pool slots through
``phys_blocks`` (the published blocks as pool slots / 8); ``-1`` padded,
unordered."""
"""Top-``k`` (``k = out_indices.shape[1]``) of each row of the bf16 sparse
``logits`` within its first ``valid_lens[b]`` columns, ``-1`` padded, unordered;
column ``j`` is written as ``blocks[b, j // 8] * 8 + j % 8``: pool slots for the
published blocks as pool slots / 8, compressed positions for logical ids."""
topk_transform_bf16_small(
logits, valid_lens, phys_blocks, page_indices, CANDIDATE_BLOCK_SIZE
logits, valid_lens, blocks, out_indices, CANDIDATE_BLOCK_SIZE
)
Loading
Loading