Skip to content
Merged
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
5 changes: 4 additions & 1 deletion python/freetoken/attention/triton.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ def __init__(self, config: ModelConfig):

def _split_cap(self, bs: int) -> int:
"""The most decode KV splits any layer group takes at this batch size."""
return max(decode_kv_split_cap(bs, max(1, self.num_q_heads), heads, self.device.index) for heads in self.kv_heads)
return max(
decode_kv_split_cap(bs, max(1, self.num_q_heads), heads, self.device.index, self.kvcache.kv_format)
for heads in self.kv_heads
)

def _ensure_decode_scratch(
self,
Expand Down
63 changes: 49 additions & 14 deletions python/freetoken/kernel/triton/attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
import triton.language as tl

from freetoken.kernel.triton.e4m3_compat import FORCE_EMU
from freetoken.kernel.triton.kv_rows import kv_row_scale, kv_scale_args, kv_tile, kv_tile_rows, kv_tile_staged
from freetoken.kernel.triton.kv_rows import (
_kv_tile_gfx11_f16, kv_row_scale, kv_scale_args, kv_tile, kv_tile_rows, kv_tile_staged,
)
from freetoken.kvcache.format import NONE, KVFormat
from freetoken.utils.arch import get_rocm_gfx_arch, is_rocm

Expand All @@ -20,6 +22,9 @@
# a short request still takes up to this many splits of _MIN_BLOCK_KV keys, so tiny requests stay parallel
_MIN_SPLITS = 8
_MAX_KV_SPLITS = 64
# the gfx11 fp8 reader runs 16-key single-stage tiles: shorter splits and more programs hide its latency
_GFX11_F16_MIN_SPLIT_LEN = 32
_GFX11_F16_MAX_KV_SPLITS = 256
# requests with more query rows take the extend kernel
MAX_DECODE_ROWS = 8
# stage 2 merges at most this many fp32 partial elements per step
Expand Down Expand Up @@ -66,6 +71,14 @@ def _use_gfx12_fp8_reader(kv_format: KVFormat, q: torch.Tensor, k_cache: torch.T
)


def _use_gfx11_f16_reader(kv_format: KVFormat) -> bool:
# RDNA3 has neither fp8 nor fp32 -> bf16 converts; E4M3 read as fp16 bit patterns needs neither
return (
kv_format.name == "fp8_per_token_head" and not FORCE_EMU
and (get_rocm_gfx_arch() or "").startswith("gfx11")
)


def _multi_row_decode_launch(m: int, block_d: int, quantized: bool, q_bytes: int, kv_bytes: int, smem: int) -> tuple[int, int, int]:
"""(block_n, num_stages, num_warps) of stage 1 for ``m`` > 1 query rows x heads per program.

Expand All @@ -81,6 +94,11 @@ def _multi_row_decode_launch(m: int, block_d: int, quantized: bool, q_bytes: int
return block_n, 3, num_warps


def _gfx11_f16_decode_launch(m: int) -> tuple[int, int, int]:
"""(block_n, num_stages, num_warps) of stage 1 for the gfx11 fp8 reader with ``m`` query rows x heads per program."""
return 16, 1, (2 if m <= 16 else 4)


def _decode_heads_per_program(group: int, rows: int, head_dim: int) -> int:
"""Query heads per decode program: the whole GQA group within the cap, else its largest power-of-two divisor within the cap.

Expand All @@ -95,8 +113,8 @@ def _decode_heads_per_program(group: int, rows: int, head_dim: int) -> int:
return max(h for h in (1, 2, 4, 8, 16) if h <= cap and group % h == 0)


def _max_request_splits(keys: int) -> int:
return max(triton.cdiv(keys, _MIN_SPLIT_LEN), min(_MIN_SPLITS, triton.cdiv(keys, _MIN_BLOCK_KV)), 1)
def _max_request_splits(keys: int, min_split_len: int = _MIN_SPLIT_LEN) -> int:
return max(triton.cdiv(keys, min_split_len), min(_MIN_SPLITS, triton.cdiv(keys, _MIN_BLOCK_KV)), 1)


@functools.lru_cache(maxsize=None)
Expand All @@ -116,10 +134,14 @@ def _num_sms(device_index: int) -> int:
return int(torch.cuda.get_device_properties(device_index).multi_processor_count)


def decode_kv_split_cap(batch: int, num_q_heads: int, num_kv_heads: int, device_index: int) -> int:
"""Most KV splits per request for a decode batch: about four programs per SM, within [_MIN_SPLITS, _MAX_KV_SPLITS]."""
def decode_kv_split_cap(
batch: int, num_q_heads: int, num_kv_heads: int, device_index: int, kv_format: KVFormat = NONE,
) -> int:
"""Most KV splits per request for a decode batch: about four programs per SM, within [_MIN_SPLITS, _MAX_KV_SPLITS];
eight, within [_MIN_SPLITS, _GFX11_F16_MAX_KV_SPLITS], for the gfx11 fp8 reader."""
head_blocks = triton.cdiv(num_q_heads, min(16, max(1, num_q_heads // num_kv_heads)))
return max(_MIN_SPLITS, min(_MAX_KV_SPLITS, triton.cdiv(4 * _num_sms(device_index), batch * head_blocks)))
per_sm, max_splits = (8, _GFX11_F16_MAX_KV_SPLITS) if _use_gfx11_f16_reader(kv_format) else (4, _MAX_KV_SPLITS)
return max(_MIN_SPLITS, min(max_splits, triton.cdiv(per_sm * _num_sms(device_index), batch * head_blocks)))


def _select_extend_tile(head_dim: int, block_d: int, smem_optin: int) -> tuple[int, int]:
Expand Down Expand Up @@ -265,7 +287,7 @@ def _paged_attention_kernel(

@triton.jit
def _decode_num_splits(effective_len, max_kv_splits, MIN_SPLIT_LEN: tl.constexpr, MIN_SPLITS: tl.constexpr, MIN_BLOCK_KV: tl.constexpr):
# same rule as _max_request_splits: long requests split by length, short ones still take up to MIN_SPLITS small splits
# same rule as _max_request_splits(keys, MIN_SPLIT_LEN): long requests split by length, short ones still take up to MIN_SPLITS small splits
by_len = tl.maximum(tl.cdiv(effective_len, MIN_SPLIT_LEN), tl.minimum(MIN_SPLITS, tl.cdiv(effective_len, MIN_BLOCK_KV)))
return tl.minimum(tl.maximum(by_len, 1), max_kv_splits)

Expand Down Expand Up @@ -316,6 +338,7 @@ def _decode_grouped_stage1_kernel(
KV_OFFSET_DTYPE: tl.constexpr,
KV_FMT: tl.constexpr,
KV_PACK: tl.constexpr,
F16_KV: tl.constexpr,
):
batch_id = tl.program_id(0)
head_block_id = tl.program_id(1)
Expand Down Expand Up @@ -387,6 +410,8 @@ def _decode_grouped_stage1_kernel(
q = tl.load(q_ptr + q_offsets, mask=mask_h[:, None] & mask_d[None, :], other=0.0)
if KV_FMT == "none":
q = q.to(k_ptr.dtype.element_ty)
elif F16_KV:
q = q.to(tl.float16)

for rel_start in tl.range(split_start, split_end, BLOCK_N):
rel_offs = rel_start + tl.arange(0, BLOCK_N)
Expand All @@ -398,9 +423,11 @@ def _decode_grouped_stage1_kernel(
if KV_PACK == 4:
k = kv_tile_rows(k_ptr, slots, kv_head, stride_ks, stride_kh, mask_n,
D, BLOCK_D, True)
elif F16_KV:
k = _kv_tile_gfx11_f16(k_ptr + slots[None, :] * stride_ks + k_base_offsets, mask_n[None, :] & mask_d[:, None])
else:
k = kv_tile(k_ptr + slots[None, :] * stride_ks + k_base_offsets, mask_n[None, :] & mask_d[:, None], KV_FMT)
scale_k = kv_row_scale(k_scale_ptr + slots * stride_kss + kv_head, mask_n, KV_FMT)
scale_k = kv_row_scale(k_scale_ptr + slots * stride_kss + kv_head, mask_n, KV_FMT, F16_KV)
scores = tl.dot(q, k) * sm_scale * scale_k[None, :]
mask = mask_h[:, None] & mask_n[None, :]
if ROWS > 1:
Expand All @@ -413,9 +440,11 @@ def _decode_grouped_stage1_kernel(
if KV_PACK == 4:
v = kv_tile_rows(v_ptr, slots, kv_head, stride_vs, stride_vh, mask_n,
DV, BLOCK_DV, False)
elif F16_KV:
v = _kv_tile_gfx11_f16(v_ptr + slots[:, None] * stride_vs + v_base_offsets, mask_n[:, None] & mask_dv[None, :])
else:
v = kv_tile(v_ptr + slots[:, None] * stride_vs + v_base_offsets, mask_n[:, None] & mask_dv[None, :], KV_FMT)
scale_v = kv_row_scale(v_scale_ptr + slots * stride_vss + kv_head, mask_n, KV_FMT)
scale_v = kv_row_scale(v_scale_ptr + slots * stride_vss + kv_head, mask_n, KV_FMT, F16_KV)

row_max = tl.max(scores, axis=1)
if ROWS > 1:
Expand Down Expand Up @@ -569,7 +598,7 @@ def decode_paged_attention(
"""SGLang-style split-k grouped decode attention for up to MAX_DECODE_ROWS causal query rows per request.

Request ``i`` owns query rows ``qo_indptr[i]:qo_indptr[i + 1]`` (one row each when ``qo_indptr`` is None); ``q_positions`` holds each row's key position.
Each request takes ``max(ceil(keys / 128), min(8, ceil(keys / 32)))`` splits, capped by ``max_kv_splits`` (default :func:`decode_kv_split_cap`) and by the split dim of ``attn_logits`` / ``attn_lse``, which hold one entry per query row.
Each request takes ``max(ceil(keys / L), min(8, ceil(keys / 32)))`` splits, with ``L`` 128 (32 for the gfx11 fp8 reader), capped by ``max_kv_splits`` (default :func:`decode_kv_split_cap`) and by the split dim of ``attn_logits`` / ``attn_lse``, which hold one entry per query row.
The kernels compute the split count on the device, so a captured graph serves any context length.
"""

Expand All @@ -594,12 +623,14 @@ def decode_paged_attention(
if sliding_window is not None and sliding_window <= 0:
# the kernels treat a window <= 0 as no window
sliding_window = None
f16_kv = _use_gfx11_f16_reader(kv_format)
min_split_len = _GFX11_F16_MIN_SPLIT_LEN if f16_kv else _MIN_SPLIT_LEN
if max_kv_splits is None:
max_kv_splits = decode_kv_split_cap(batch, num_q_heads, num_kv_heads, q.device.index)
max_kv_splits = decode_kv_split_cap(batch, num_q_heads, num_kv_heads, q.device.index, kv_format)
if sliding_window:
# no request attends more than the window plus its later rows, so programs past its splits would only exit
span = sliding_window + max_q_len - 1
max_kv_splits = min(max_kv_splits, _max_request_splits(span))
max_kv_splits = min(max_kv_splits, _max_request_splits(span, min_split_len))
max_kv_splits = min(max_kv_splits, attn_logits.shape[2], attn_lse.shape[2])
if sinks is not None:
assert sinks.is_cuda
Expand Down Expand Up @@ -650,6 +681,9 @@ def decode_paged_attention(
kv_pack = 1
if is_rocm() and rows == 1 and _use_gfx12_fp8_reader(kv_format, q, k_cache, v_cache):
kv_pack, block_n, num_stages, num_warps = 4, 64, 1, 4
if f16_kv:
# one stage: the pipeliner cannot predicate the gfx11 tile's asm pin
block_n, num_stages, num_warps = _gfx11_f16_decode_launch(rows * block_h)

k_scale_arg, v_scale_arg, stride_kss, stride_vss = kv_scale_args(kv_format, k_cache, v_cache, k_scale, v_scale, q)
_decode_grouped_stage1_kernel[grid](
Expand Down Expand Up @@ -683,6 +717,7 @@ def decode_paged_attention(
KV_OFFSET_DTYPE=_kv_offset_dtype(k_cache, v_cache),
KV_FMT=kv_format.name,
KV_PACK=kv_pack,
F16_KV=f16_kv,
GROUP=group,
NUM_Q_HEADS=num_q_heads,
ROWS=rows,
Expand All @@ -692,7 +727,7 @@ def decode_paged_attention(
BLOCK_H=block_h,
VALID_BLOCK_H=valid_block_h,
MIN_BLOCK_KV=_MIN_BLOCK_KV,
MIN_SPLIT_LEN=_MIN_SPLIT_LEN,
MIN_SPLIT_LEN=min_split_len,
MIN_SPLITS=_MIN_SPLITS,
D=head_dim,
DV=head_dim,
Expand Down Expand Up @@ -722,7 +757,7 @@ def decode_paged_attention(
o.stride(1),
ROWS=rows,
MIN_BLOCK_KV=_MIN_BLOCK_KV,
MIN_SPLIT_LEN=_MIN_SPLIT_LEN,
MIN_SPLIT_LEN=min_split_len,
MIN_SPLITS=_MIN_SPLITS,
BLOCK_DV=block_dv,
DV=head_dim,
Expand Down
16 changes: 14 additions & 2 deletions python/freetoken/kernel/triton/kv_rows.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ def _kv_tile_gfx12_bf16(ptrs, mask, TRANSPOSE: tl.constexpr):
return values


@triton.jit
def _kv_tile_gfx11_f16(ptrs, mask):
"""E4M3FN codes as fp16 holding ``value / 256``, exact for every finite code; ``kv_row_scale(F16=True)`` restores the 256."""
codes = tl.load(ptrs, mask=mask, other=0).to(tl.uint16)
bits = ((codes & 0x80) << 8) | ((codes & 0x7F) << 7)
# keep the decode in the load layout: Triton otherwise repeats it for every dot-operand replica
bits = tl.inline_asm_elementwise("v_mov_b32 $0, $1", "=v,v", [bits], dtype=tl.uint16, is_pure=False, pack=2)
return bits.to(tl.float16, bitcast=True)


@triton.jit
def kv_tile(ptrs, mask, FMT: tl.constexpr):
"""One K or V tile in the dtype ``tl.dot`` takes."""
Expand Down Expand Up @@ -101,12 +111,14 @@ def kv_tile_staged(ptrs, mask, FMT: tl.constexpr):


@triton.jit
def kv_row_scale(ptrs, mask, FMT: tl.constexpr):
"""Row scales of a tile; all ones without scales, so the caller's multiply folds away."""
def kv_row_scale(ptrs, mask, FMT: tl.constexpr, F16: tl.constexpr = False):
"""Row scales of a tile; all ones without scales, so the caller's multiply folds away. ``F16`` pairs with ``_kv_tile_gfx11_f16``."""
if FMT == "none":
scale = tl.full(mask.shape, 1.0, tl.float32)
else:
scale = tl.load(ptrs, mask=mask, other=0.0)
if F16:
scale = scale * 256.0
return scale


Expand Down
Loading
Loading