test(kernel): unify duplicated torch references under numerics/torch (#3949)

Kernel tests added since the first consolidation pass wrote their own
PyTorch references again, several of them copied across files or
imported from other test modules. Move them into
`tokenspeed_kernel.numerics.torch` and have the tests call the shared
ones:

- quantization: one exact UE8M0 FP8 group quantizer for five copies, an
FP8 group round trip, 2-D block and packed-UE8M0 dequantization, and the
block-scaled NVFP4 (four and six target scales) and MXFP8 activation
models; the GEMM reference reuses these instead of private copies.
- moe: the MXFP4 clamped-SwiGLU experts and the FP8 block-scaled route
reference shared by the gfx950 FP8 MoE tests.
- attention: a paged attention reference for four paged-decode oracles,
the QSA FP8 prefill model (dropping its standalone test module), the DSA
FP8 sparse KV packer, the DSV4.1 page mask and logit cleaning
references, and a step-recording KDA delta rule for three verify
oracles. The GDN WY oracle builds on torch_gdn_recurrence.

Every replacement matches the code it replaces bit for bit on CPU
inputs, except reduction-order rounding in the FP32 paged attention and
FP64 recurrence oracles. Oracles whose reduction order differs from the
shared reference keep their own code, so tight kernel tolerances do not
shift.

---------

Signed-off-by: Lei Zhang <antiagainst@gmail.com>
This commit is contained in:
Lei Zhang
2026-11-29 15:10:36 -08:00
committed by GitHub
parent 4469a8a531
commit 60509dc6a9
47 changed files with 978 additions and 917 deletions
@@ -19,8 +19,8 @@
# SOFTWARE.
"""PyTorch references for ``tokenspeed_kernel.ops.attention.dsa``
(DeepSeek sparse attention): the indexer's top-k key selection, and MLA over
the selected keys."""
(DeepSeek sparse attention): the indexer's top-k key selection, MLA over the
selected keys, and the FP8 sparse cache rows it reads."""
from __future__ import annotations
@@ -53,6 +53,39 @@ def dsa_index_scores(
return (per_head.relu() * weights.float()).sum(dim=1) * scale
def dsa_pack_fp8_sparse_kv(
latent: torch.Tensor, rope: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
"""Pack MLA cache rows into the FP8 sparse layout FlashMLA reads.
Each row holds the FP8 E4M3 latent (one ``amax / 448`` scale per row,
``amax`` floored at ``1e-6``), that FP32 scale repeated once per 128
latent values, and the BF16 rope part.
Args:
latent: ``[slots, rank]``.
rope: ``[slots, rope_dim]`` BF16.
Returns:
``(packed, dequantized)``: ``uint8 [slots, rank + rank / 128 * 4 +
rope_dim * 2]`` rows and the FP32 latent they encode.
"""
kv_lora_rank = latent.shape[1]
qk_rope_head_dim = rope.shape[1]
scale = latent.float().abs().amax(dim=1, keepdim=True).clamp_min(1.0e-6) / 448.0
latent_fp8 = (latent.float() / scale).clamp(-448.0, 448.0).to(torch.float8_e4m3fn)
row_bytes = kv_lora_rank + kv_lora_rank // 128 * 4 + qk_rope_head_dim * 2
sparse = torch.empty(
(latent.shape[0], row_bytes), dtype=torch.uint8, device=latent.device
)
sparse[:, :kv_lora_rank].copy_(latent_fp8.view(torch.uint8))
scale_start = kv_lora_rank
scale_end = scale_start + kv_lora_rank // 128 * 4
sparse[:, scale_start:scale_end].view(torch.float32).copy_(scale)
sparse[:, scale_end:].view(torch.bfloat16).copy_(rope)
return sparse, latent_fp8.float() * scale
def _select(
scores: torch.Tensor, ids: torch.Tensor, topk: int
) -> tuple[torch.Tensor, int]:
@@ -446,3 +446,78 @@ def torch_dsv41_sparse_scores(
normalized[row, : chosen.numel()] = chosen.int()
ends[row] = valid.sum()
return scores, ends, normalized, full
def dsv41_mask_table_pages(
values: torch.Tensor,
lengths: torch.Tensor,
table: torch.Tensor,
pages: int,
page_size: int,
) -> torch.Tensor:
"""``mask_invalid_table_pages``: in place, ``-inf`` every logit in ``[0,
length)`` of a row whose page, by that row's ``table`` row, lies outside
``[0, pages)``. Later columns are untouched. Returns ``values``."""
capacity = table.shape[1] * page_size
column = torch.arange(capacity, device=values.device)
page = table[:, column // page_size]
hole = (column[None] < lengths.clamp(0, capacity)[:, None]) & (
(page < 0) | (page >= pages)
)
values[:, :capacity].masked_fill_(hole, -torch.inf)
return values
def dsv41_clean_logits(
values: torch.Tensor,
lengths: torch.Tensor,
table: torch.Tensor,
pages: int,
capacity: int,
width: int,
page_size: int,
) -> torch.Tensor:
"""``clean_logits``: ``[rows, width]`` copies of the logits in ``[0,
min(length, capacity))`` on valid pages (in ``[0, pages)`` by the row's
``table`` row), ``-inf`` everywhere else."""
columns = torch.arange(width, device=values.device)
valid = (columns[None, :] < capacity) & (
columns[None, :] < lengths.clamp(0, capacity)[:, None]
)
page_index = columns // page_size
page = table[:, page_index.clamp(max=table.shape[1] - 1)]
valid &= (page_index < table.shape[1])[None, :] & (page >= 0) & (page < pages)
padded = torch.full(
(values.shape[0], width),
-float("inf"),
dtype=values.dtype,
device=values.device,
)
padded[:, :capacity] = values[:, :capacity]
return torch.where(valid, padded, -float("inf"))
def dsv41_clean_logits_for_selection(
values: torch.Tensor,
lengths: torch.Tensor,
table: torch.Tensor,
pages: int,
capacity: int,
page_size: int,
alignment: int,
) -> torch.Tensor:
"""``clean_logits_for_selection``: rows padded to ``alignment`` columns
holding the logits in ``[0, capacity)``, ``-inf`` past a row's length or
on an invalid page; NaN marks the columns from ``capacity`` on, which the
kernel leaves unspecified."""
width = (capacity + alignment - 1) // alignment * alignment
out = torch.full(
(values.shape[0], width), torch.nan, dtype=values.dtype, device=values.device
)
column = torch.arange(capacity, device=values.device)
page = table[:, column // page_size]
valid = (column[None] < lengths.clamp(0, capacity)[:, None]) & (
(page >= 0) & (page < pages)
)
out[:, :capacity] = values[:, :capacity].masked_fill(~valid, -torch.inf)
return out
@@ -166,6 +166,48 @@ def kda_delta_rule(
return torch.stack(outputs), running
def kda_delta_rule_steps(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
decay: torch.Tensor,
beta: torch.Tensor,
state: torch.Tensor,
) -> tuple[torch.Tensor, list[torch.Tensor], torch.Tensor]:
""":func:`kda_delta_rule` keeping every step, in the inputs' dtype.
Per token: ``S = S * decay`` per key channel, the correction ``c = beta *
(v - S k)``, ``S = S + c k^T`` and the output ``S q``; the products reduce
as elementwise sums. Pass ``q`` normalized and scaled, ``k`` normalized,
and ``decay = exp(gate)`` (see :func:`kda_gate`).
Args:
q, k, decay: ``[T, H, K]``.
v: ``[T, H, V]``.
beta: ``[T, H]`` write strengths (post-sigmoid).
state: ``[H, V, K]`` initial state.
Returns:
``(outputs [T, H, V], states, corrections [T, H, V])``: ``states[t]``
is the ``[H, V, K]`` state after token ``t``.
"""
running = state
outputs, states, corrections = [], [], []
for token in range(q.shape[0]):
running = running * decay[token][:, None, :]
correction = (v[token] - (running * k[token][:, None, :]).sum(-1)) * beta[
token
][:, None]
running = running + correction[:, :, None] * k[token][:, None, :]
outputs.append((running * q[token][:, None, :]).sum(-1))
states.append(running)
corrections.append(correction)
if not outputs:
empty = v.new_empty((0, *v.shape[1:]))
return empty, states, empty
return torch.stack(outputs), states, torch.stack(corrections)
@register_kernel(
"attention",
"kda_conv_decode",
@@ -113,6 +113,55 @@ def torch_dense_attention(
return out, lse.transpose(0, 1)
def torch_paged_attention(
q: torch.Tensor,
k_cache: torch.Tensor,
v_cache: torch.Tensor,
page_table: torch.Tensor,
seq_lens: list[int],
query_lens: list[int],
*,
scale: float,
window_left: int | None,
sinks: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Grouped-query attention of packed query rows over paged caches.
Request ``r`` owns the next ``query_lens[r]`` rows of ``q``, the last
positions of its ``seq_lens[r]``-key sequence: its row ``t`` sees the
first ``seq_lens[r] - (query_lens[r] - 1 - t)`` keys, and with
``window_left`` only the last ``window_left + 1`` of them. See
:func:`torch_dense_attention` for the sinks, empty rows and the LSE.
Args:
q: ``[sum(query_lens), Hq, D]``.
k_cache: ``[num_pages, page_size, Hkv, D]``.
v_cache: ``[num_pages, page_size, Hkv, Dv]``.
page_table: ``[requests, max_pages]`` page ids.
seq_lens: Keys of each request, its new rows included.
query_lens: Query rows of each request.
Returns:
``(out [rows, Hq, Dv], lse [rows, Hq])`` in FP32.
"""
outs, lses = [], []
start = 0
for request, (length, rows) in enumerate(zip(seq_lens, query_lens, strict=True)):
out, lse = torch_dense_attention(
q[start : start + rows],
gather_pages(k_cache, page_table[request], length),
gather_pages(v_cache, page_table[request], length),
scale=scale,
causal_offset=length - rows,
window_left=window_left,
sinks=sinks,
)
outs.append(out)
lses.append(lse)
start += rows
return torch.cat(outs), torch.cat(lses)
def torch_causal_attention(
q: torch.Tensor, k: torch.Tensor, v: torch.Tensor
) -> torch.Tensor:
@@ -19,10 +19,13 @@
# SOFTWARE.
"""PyTorch references for ``tokenspeed_kernel.ops.attention.qsa``: the block
scorer, attention over the selected cache slots and the BF16 KV scratch."""
scorer, attention over the selected cache slots (with the FP8 prefill's
rounding model) and the BF16 KV scratch."""
from __future__ import annotations
import math
import torch
from tokenspeed_kernel.numerics.torch.attention.mha import torch_dense_attention
from tokenspeed_kernel.registry import Priority, register_kernel
@@ -195,6 +198,111 @@ def torch_qsa_paged_block_scores(
return torch.where(blocks[None, :] < complete[:, None], scores, -torch.inf)
def qsa_fp8_prefill_attention(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
slots: torch.Tensor,
positions: torch.Tensor,
ids: torch.Tensor,
*,
attention_scale: float,
k_scale: float,
v_scale: float,
) -> torch.Tensor:
"""QSA FP8 prefill attention with explicit Q/P FP8 rounding, FP32 accumulation.
The contract of the native FP8 CuTe DSL prefill: 12 query heads per KV
head, head dim 256, and up to 512 complete four-token blocks plus a causal
tail per row.
Uses per-head maxabs/448 Q scales and 128-token online-softmax tiles with
FP8-rounded probabilities. The caller configures IEEE matmul precision;
this function does not change global precision settings.
Args:
q: Queries [rows, 12 * kv_heads, 256], converted to FP32 before quantizing.
k: Key-cache values [cache_slots, kv_heads, 256].
v: Value-cache values with the same shape as k.
slots: Physical slots [rows, 2051]. Complete four-token blocks occupy
the prefix (up to 2048 entries); up to three causal tail tokens
occupy columns starting at 2048. Nonpositive slots are masked.
positions: Zero-based query positions [rows], bounding each row's
complete-block prefix and tail; negative positions give empty rows.
ids: One-dimensional indices of the query rows to evaluate, in output order.
attention_scale: Scalar multiplier for query-key scores.
k_scale: Scalar key-cache descale applied to scores.
v_scale: Scalar value-cache descale applied to the normalized output.
Returns:
FP32 attention values [len(ids), 12 * kv_heads, 256], with zero for
fully masked rows. Final BF16 rounding is left to the caller.
"""
kv_heads = k.shape[1]
queries = q[ids].float().reshape(len(ids), kv_heads, 12, 256)
selected, pos = slots[ids], positions[ids]
visible = (pos + 1).clamp_min(0)
complete = (visible // 4).clamp_max(512) * 4
length = complete + visible % 4
logical = torch.arange(2051, device=q.device)[None, :]
columns = torch.where(
logical < complete[:, None], logical, 2048 + logical - complete[:, None]
).clamp_max(2050)
physical = selected.gather(1, columns.long()).long()
valid = (logical < length[:, None]) & (physical > 0)
physical = torch.where(valid, physical, torch.zeros_like(physical))
operands = []
for cache in (k, v):
x = cache[physical].float().permute(0, 2, 1, 3).contiguous()
operands.append(torch.where(valid[:, None, :, None], x, torch.zeros_like(x)))
keys, values = operands
maximum = queries.abs().amax(-1, keepdim=True)
# Use correctly rounded FP32 division; Torch scalar division can instead
# multiply by a rounded reciprocal and change FP8 midpoint decisions.
scale = torch.where(
maximum > 0, (maximum.double() / 448.0).float(), torch.ones_like(maximum)
)
quantized = (
(queries.double() / scale.double())
.float()
.clamp(-448, 448)
.to(torch.float8_e4m3fn)
.float()
)
scores = (
(quantized @ keys.transpose(-1, -2))
* (
scale
* (
float(k_scale)
* float(
torch.tensor(
math.log2(math.e) * attention_scale, dtype=torch.float32
)
)
)
)
).masked_fill(~valid[:, None, None, :], -torch.inf)
running_max = torch.full(scores.shape[:-1], -torch.inf, device=q.device)
denominator = torch.zeros_like(running_max)
numerator = torch.zeros((*running_max.shape, 256), device=q.device)
for start in range(0, 2051, 128):
tile = scores[..., start : start + 128]
updated = torch.maximum(running_max, tile.amax(-1))
safe = torch.where(torch.isneginf(updated), torch.zeros_like(updated), updated)
alpha = torch.exp2(running_max - safe)
probability = torch.exp2(tile - safe[..., None])
denominator = denominator * alpha + probability.sum(-1)
rounded = (probability * 448.0).to(torch.float8_e4m3fn).float()
numerator = (
numerator * alpha[..., None] + rounded @ values[..., start : start + 128, :]
)
running_max = updated
return (
numerator * (v_scale / (denominator.clamp_min(1e-30)[..., None] * 448.0))
).reshape(len(ids), kv_heads * 12, 256)
def qsa_stream_topk_ids(scores: torch.Tensor, k: int) -> list[int]:
"""Top-k block ids under the stream path's tie-breaking.
@@ -24,6 +24,11 @@ import math
import torch
import torch.nn.functional as F
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_fp8_blocks,
dequantize_fp8_groups,
unpack_ue8m0_words,
)
from tokenspeed_kernel.registry import Priority, register_kernel
from tokenspeed_kernel.signature import (
ScaleFormat,
@@ -76,19 +81,6 @@ _DENSE_GEMM_FORMAT_SIGNATURES = format_signatures(
)
def _dequant_scales(scales: torch.Tensor) -> torch.Tensor:
if scales.dtype == torch.uint8:
# ue8m0: biased power-of-two exponent bytes.
return torch.exp2(scales.float() - 127.0)
return scales.float()
def _unpack_ue8m0_scales(scales: torch.Tensor, k_tiles: int) -> torch.Tensor:
shifts = torch.arange(0, 32, 8, dtype=torch.int32, device=scales.device)
exponents = ((scales.unsqueeze(-1) >> shifts) & 0xFF).flatten(1)[:, :k_tiles]
return exponents.to(torch.uint8)
def _as_baddbmm_alpha(alpha: torch.Tensor | float | int | None) -> float | int:
if alpha is None:
return 1
@@ -158,9 +150,9 @@ def torch_mm_fp8_blockscale(
block_n, block_k = block_size
k_tiles = math.ceil(K / block_k)
if A_scales.dtype == torch.int32:
A_scales = _unpack_ue8m0_scales(A_scales, k_tiles)
A_scales = unpack_ue8m0_words(A_scales, k_tiles)
if B_scales.dtype == torch.int32:
B_scales = _unpack_ue8m0_scales(B_scales, k_tiles)
B_scales = unpack_ue8m0_words(B_scales, k_tiles)
block_n = 1
n_tiles = math.ceil(N / block_n)
assert A_scales.shape == (M, k_tiles), (
@@ -172,13 +164,10 @@ def torch_mm_fp8_blockscale(
f"got {tuple(B_scales.shape)}"
)
A_scaled = _dequant_scales(A_scales).repeat_interleave(block_k, dim=1)[:, :K]
B_scaled = (
_dequant_scales(B_scales)
.repeat_interleave(block_n, dim=0)
.repeat_interleave(block_k, dim=1)[:N, :K]
output = (
dequantize_fp8_groups(A, A_scales, block_k)
@ dequantize_fp8_blocks(B, B_scales, block_n, block_k).T
)
output = (A.float() * A_scaled) @ (B.float() * B_scaled).T
if alpha is not None:
output = output * alpha.float()
@@ -30,8 +30,14 @@ from typing import Callable, Sequence
import torch
import torch.nn.functional as F
from tokenspeed_kernel.numerics.torch.activation import torch_situ_and_mul
from tokenspeed_kernel.numerics.torch.quantization import dequantize_mxfp4
from tokenspeed_kernel.numerics.torch.activation import (
torch_silu_and_mul,
torch_situ_and_mul,
)
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_fp8_blocks,
dequantize_mxfp4,
)
from tokenspeed_kernel.registry import Priority, register_kernel
from tokenspeed_kernel.signature import (
dense_tensor_format,
@@ -199,6 +205,110 @@ def mxfp4_situ_moe_experts(
).to(dtype)
def mxfp4_silu_moe_experts(
hidden_states: torch.Tensor,
w13_packed: torch.Tensor,
w13_scales: torch.Tensor,
w2_packed: torch.Tensor,
w2_scales: torch.Tensor,
topk_ids: torch.Tensor,
topk_weights: torch.Tensor,
*,
limit: float | None,
) -> torch.Tensor:
""":func:`torch_moe_experts` of MXFP4 experts with a clamped SwiGLU.
A ``limit`` clips ``gate`` from above only and ``up`` on both sides
before ``silu(gate) * up`` (DeepSeek-V4.1's ``Expert.forward``). The
``fc1`` output and each expert's output round to BF16; the sum returns in
``hidden_states``'s dtype.
"""
return torch_moe_experts(
hidden_states,
DequantizedExperts(dequantize_mxfp4, w13_packed, w13_scales),
DequantizedExperts(dequantize_mxfp4, w2_packed, w2_scales),
topk_ids,
topk_weights,
activation=lambda gate_up: torch_silu_and_mul(gate_up.bfloat16(), limit),
w13_bias=None,
w2_bias=None,
quantize_input=None,
quantize_intermediate=None,
round_expert_output=torch.Tensor.bfloat16,
first_expert=0,
).to(hidden_states.dtype)
def fake_quantize_fp8_rows_128(x: torch.Tensor) -> torch.Tensor:
"""FP32 round trip of 2-D ``x`` through FP8 with one scale per 128 columns,
as the gfx950 FP8 MoE quantizes activations: the scale is ``amax * (1 /
448)`` (``amax`` floored at ``1e-10``) and the codes ``x * (1 / scale)``,
both products rather than quotients."""
groups = x.float().reshape(x.shape[0], -1, 128)
scales = groups.abs().amax(dim=-1).clamp_min(1.0e-10) * (1.0 / 448.0)
codes = (groups * scales.reciprocal()[..., None]).clamp(-448.0, 448.0)
codes = codes.to(torch.float8_e4m3fn).reshape_as(x)
return codes.float() * scales.repeat_interleave(128, dim=1)
def fp8_block_scaled_moe_routes(
hidden_states: torch.Tensor,
w13: torch.Tensor,
w2: torch.Tensor,
w13_scales: torch.Tensor,
w2_scales: torch.Tensor,
topk_ids: torch.Tensor,
topk_weights: torch.Tensor,
*,
first_expert: int,
limit: float,
quantized_activations: bool,
) -> tuple[torch.Tensor, bool]:
"""Routed experts over 128x128 block-scaled FP8 weights with a clamped
SwiGLU, summed per token from per-route partials.
Each route's ``fc2`` output times its weight is one partial, rounded to
BF16 when ``quantized_activations`` (else kept in FP32); a token's
partials then sum in FP32 and round to BF16. With
``quantized_activations`` the input and the BF16 intermediate take the
:func:`fake_quantize_fp8_rows_128` round trip.
Returns:
``(out [tokens, hidden] BF16, clamp_active)``, where ``clamp_active``
tells whether ``limit`` clipped any routed gate or up value.
"""
if quantized_activations:
x = fake_quantize_fp8_rows_128(hidden_states)
else:
x = hidden_states.float()
partials = torch.zeros(
(*topk_ids.shape, hidden_states.shape[1]),
device=hidden_states.device,
dtype=torch.bfloat16 if quantized_activations else torch.float32,
)
clamp_active = False
for expert in range(w13.shape[0]):
tokens, slots = torch.where(topk_ids == first_expert + expert)
if tokens.numel() == 0:
continue
gate_up = dequantize_fp8_blocks(w13[expert], w13_scales[expert], 128, 128)
gate, up = F.linear(x[tokens], gate_up).chunk(2, dim=-1)
clamp_active |= bool(((gate > limit) | (up.abs() > limit)).any().item())
intermediate = (F.silu(gate.clamp(max=limit)) * up.clamp(-limit, limit)).to(
torch.bfloat16
)
if quantized_activations:
intermediate = fake_quantize_fp8_rows_128(intermediate)
else:
intermediate = intermediate.float()
down_weight = dequantize_fp8_blocks(w2[expert], w2_scales[expert], 128, 128)
down = F.linear(intermediate, down_weight)
partials[tokens, slots] = (down * topk_weights[tokens, slots, None]).to(
partials.dtype
)
return partials.float().sum(dim=1).to(torch.bfloat16), clamp_active
@register_kernel(
"moe",
"softmax_topk",
@@ -67,6 +67,32 @@ def quantize_fp8_groups(
return codes.flatten(-2), scale.squeeze(-1)
def quantize_fp8_ue8m0_groups(
x: torch.Tensor, group_size: int, *, min_amax: float
) -> tuple[torch.Tensor, torch.Tensor]:
"""Quantize each ``group_size`` run of the last dimension to FP8 E4M3 with
a UE8M0 scale, as the group quantizers' kernels round it.
The scale is the power of two at or above ``amax / 448`` (``amax`` floored
at ``min_amax``), taken exactly from the quotient's FP32 bits: its biased
exponent, plus one when the mantissa is nonzero. Unlike
:func:`quantize_fp8_groups` with ``power_of_two_scale``, this does not go
through an FP32 ``log2``, which rounds quotients a few ulp above a power of
two down to it.
Returns:
``(codes, exponents)``: FP8 codes shaped like ``x`` and the ``int32``
biased exponents ``[..., last_dim / group_size]``.
"""
groups = x.float().unflatten(-1, (-1, group_size))
raw = groups.abs().amax(dim=-1).clamp_min(min_amax) / _FP8_MAX
bits = raw.view(torch.int32)
exponents = ((bits >> 23) & 0xFF) + ((bits & 0x7FFFFF) != 0).to(torch.int32)
scales = (exponents << 23).view(torch.float32)
codes = (groups / scales[..., None]).clamp(-_FP8_MAX, _FP8_MAX).to(_FP8_DTYPE)
return codes.flatten(-2), exponents
def dequantize_fp8_groups(
codes: torch.Tensor, scales: torch.Tensor, group_size: int
) -> torch.Tensor:
@@ -83,6 +109,43 @@ def dequantize_fp8_groups(
)
def dequantize_fp8_blocks(
codes: torch.Tensor, scales: torch.Tensor, block_rows: int, block_cols: int
) -> torch.Tensor:
"""FP32 values of FP8 ``codes [..., R, C]`` with one scale per
``block_rows x block_cols`` tile, ``scales [..., ceil(R / block_rows),
ceil(C / block_cols)]`` in FP32 or UE8M0 exponent bytes when ``uint8``."""
if scales.dtype == torch.uint8:
scales = ue8m0_to_float(scales)
rows, cols = codes.shape[-2:]
expanded = scales.float().repeat_interleave(block_rows, dim=-2)
expanded = expanded.repeat_interleave(block_cols, dim=-1)
return codes.float() * expanded[..., :rows, :cols]
def fake_quantize_fp8_groups(
x: torch.Tensor,
group_size: int,
*,
power_of_two_scale: bool,
min_scale: float = 1e-10,
) -> torch.Tensor:
"""FP32 round trip of :func:`quantize_fp8_groups` through
:func:`dequantize_fp8_groups`; MXFP8 when ``group_size`` is 32 and
``power_of_two_scale``."""
codes, scales = quantize_fp8_groups(
x, group_size, power_of_two_scale=power_of_two_scale, min_scale=min_scale
)
return dequantize_fp8_groups(codes, scales, group_size)
def unpack_ue8m0_words(packed: torch.Tensor, num_groups: int) -> torch.Tensor:
"""UE8M0 exponent bytes of DeepGEMM's packed scales: four per ``int32``
word, lowest byte first, trimmed to ``num_groups`` along the last dim."""
shifted = torch.stack([(packed >> (8 * i)) & 0xFF for i in range(4)], dim=-1)
return shifted.flatten(-2)[..., :num_groups].to(torch.uint8)
# OCP E2M1 values by 4-bit code: sign bit 3, magnitude bits 0-2.
_E2M1_VALUES = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0)
_E2M1_VALUES = _E2M1_VALUES + tuple(-v for v in _E2M1_VALUES)
@@ -142,6 +205,84 @@ def dequantize_nvfp4_blocks(packed: torch.Tensor, scales: torch.Tensor) -> torch
return dequantize_e2m1(packed) * scales.float().repeat_interleave(16, dim=-1)
def round_e2m1(y: torch.Tensor) -> torch.Tensor:
"""Round to the nearest E2M1 value, saturating at 6.
A tie goes to the value with the even code: the midpoints 0.25, 0.75,
1.25, 1.75, 2.5, 3.5 and 5 round to 0, 1, 1, 2, 2, 4 and 4.
"""
a = y.abs()
v = torch.full_like(a, 0.5)
v = torch.where(a <= 0.25, 0.0, v)
v = torch.where(a >= 0.75, 1.0, v)
v = torch.where(a > 1.25, 1.5, v)
v = torch.where(a >= 1.75, 2.0, v)
v = torch.where(a > 2.5, 3.0, v)
v = torch.where(a >= 3.5, 4.0, v)
v = torch.where(a > 5.0, 6.0, v)
return torch.where(y < 0, -v, v)
def fake_quantize_block_scaled_nvfp4(
x: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""TokenSpeed's NVFP4 activation quantization of rows ``x [R, N]`` (FP32).
Each row's outer scale is ``amax / 1536``. Every 16-value group tries an
FP8 E4M3 block scale that maps its maximum to 6 and one that maps it to 4,
and keeps the one whose reconstruction has the smaller absolute error
(summed pairwise, the 6 scale on a tie). This is the four/six contract of
``tokenspeed_kernel.ops.moe.block_scaled``, for FP32 inputs.
Returns:
``(values, amax)``: ``bf16(e2m1 * block_scale)`` of each element
without the outer scale, as FP32 ``[R, N]``, and the FP32 row maxima
``[R]``.
"""
fp32_max = torch.finfo(torch.float32).max
amax = x.abs().amax(-1, keepdim=True)
enc = torch.clamp(torch.tensor(1536.0) / amax, max=fp32_max)
dec = 1.0 / enc
outer = amax * (1.0 / 1536.0)
groups = x.view(x.shape[0], -1, 16)
gm = groups.abs().amax(-1, keepdim=True)
candidates = []
for target in (6.0, 4.0):
sc = torch.clamp(gm * (enc[:, :, None] * (1.0 / target)), max=448.0)
sc = sc.to(_FP8_DTYPE).float()
inv = torch.clamp(1.0 / (sc * dec[:, :, None]), max=fp32_max)
value = round_e2m1((groups * inv).double()).float() * sc
error = (groups - value * outer[:, :, None]).abs()
while error.shape[-1] > 1:
error = error.view(*error.shape[:-1], -1, 2).sum(-1)
candidates.append((value, error))
(six, six_error), (four, four_error) = candidates
best = torch.where(four_error < six_error, four, six)
return best.view(x.shape).bfloat16().float(), amax.view(-1)
def fake_quantize_block_scaled_mxfp8(x: torch.Tensor) -> torch.Tensor:
"""TokenSpeed's MXFP8 activation quantization of rows ``x [R, N]`` (FP32),
decoded as the block-scaled expert GEMMs do and rounded to BF16.
The UE8M0 exponent of each 32-value group rounds ``amax * fp32(1 / 448)``
up to a power of two (the product, not the quotient, as the kernels
compute it); maxima at most ``2**-127`` take exponent 0, whose inverse
scale is ``2**127``. This is the MXFP8 contract of
``tokenspeed_kernel.ops.moe.block_scaled``, for FP32 inputs.
"""
groups = x.view(x.shape[0], -1, 32)
raw = groups.abs().amax(-1) * torch.tensor(1.0 / 448.0)
bits = raw.view(torch.int32)
exponent = ((bits + 0x007FFFFF) & 0x7F800000) >> 23
exponent = torch.where(raw <= 2.0**-127, 0, exponent.clamp(max=254))
scale = torch.exp2(exponent.double() - 127).float().clamp(min=2.0**-127)
inverse = torch.where(exponent == 0, torch.tensor(2.0**127), 1.0 / scale)
values = (groups * inverse[..., None]).clamp(-_FP8_MAX, _FP8_MAX)
codes = values.to(_FP8_DTYPE).float()
return (codes * scale[..., None]).view(x.shape).bfloat16().float()
def fake_quantize_mxfp4_even(values: torch.Tensor) -> torch.Tensor:
"""MXFP4 round trip with Quark's "even" scale and saturating E2M1 RNE.
@@ -32,6 +32,7 @@ from dataclasses import dataclass
import pytest
import torch
from tokenspeed_kernel.numerics.torch.attention.mha import torch_paged_attention
from tokenspeed_kernel.ops.attention.mha import mha_decode_with_kvcache
from utils import is_cdna4
@@ -112,29 +113,21 @@ def reference_precision():
@reference_precision()
def reference(inputs):
"""Independent FP32 dense oracle; only one request is materialized at once."""
q = inputs["q"].float()
result = torch.empty_like(q)
width = inputs["max_seqlen_q"]
"""FP32 paged attention; only one request is materialized at once."""
lengths = inputs["cache_seqlens"].cpu().tolist()
for batch, length in enumerate(lengths):
blocks = inputs["page_table"][batch, : (length + 63) // 64].long()
k = inputs["k_cache"][blocks].reshape(-1, 128)[:length].float()
v = inputs["v_cache"][blocks].reshape(-1, 128)[:length].float()
query = q[batch * width : (batch + 1) * width]
logits = torch.einsum("qhd,kd->qhk", query, k) * (128**-0.5)
ends = length - width + 1 + torch.arange(width, device=q.device)
positions = torch.arange(length, device=q.device)
mask = positions[None, :] < ends[:, None]
if inputs["window_left"] >= 0:
mask &= positions[None, :] >= (ends - inputs["window_left"] - 1)[:, None]
probabilities = torch.softmax(
logits.masked_fill(~mask[:, None, :], -torch.inf), dim=-1
)
result[batch * width : (batch + 1) * width] = torch.einsum(
"qhk,kd->qhd", probabilities, v
)
return result
window = inputs["window_left"]
out, _ = torch_paged_attention(
inputs["q"],
inputs["k_cache"],
inputs["v_cache"],
inputs["page_table"],
lengths,
[inputs["max_seqlen_q"]] * len(lengths),
scale=128**-0.5,
window_left=window if window >= 0 else None,
sinks=None,
)
return out
def changed_inputs(inputs):
@@ -25,6 +25,7 @@ from types import SimpleNamespace
import pytest
import torch
import torch.nn.functional as F
from tokenspeed_kernel.numerics.torch.moe import fp8_block_scaled_moe_routes
from utils import is_cdna4
pytestmark = pytest.mark.skipif(not is_cdna4(), reason="requires AMD gfx950 GPU")
@@ -496,7 +497,6 @@ def test_gluon_block_fp8_warp_routed_reference(
from test_gluon_fp8_packed_small import (
_assert_numerics,
_fixture,
_reference,
)
from tokenspeed_kernel_amd.ops.gfx950.moe.fp8 import (
gluon_fp8_block_warp_decode_moe,
@@ -509,7 +509,7 @@ def test_gluon_block_fp8_warp_routed_reference(
rows, ep_size, rank, True, 4096, intermediate
)
expert_start = rank * w13.shape[0]
expected = _reference(
expected = fp8_block_scaled_moe_routes(
x,
w13,
w2,
@@ -517,8 +517,8 @@ def test_gluon_block_fp8_warp_routed_reference(
s2,
ids,
weights,
expert_start,
7.0,
first_expert=expert_start,
limit=7.0,
quantized_activations=False,
)[0]
actual = gluon_fp8_block_warp_decode_moe(
@@ -572,7 +572,6 @@ def test_gluon_block_fp8_packed_warp_stress(
from test_gluon_fp8_packed_small import (
_assert_numerics,
_fixture,
_reference,
)
from tokenspeed_kernel_amd.ops.gfx950.moe.fp8 import (
gluon_fp8_block_warp_decode_moe,
@@ -588,7 +587,7 @@ def test_gluon_block_fp8_packed_warp_stress(
x[:, 1::2] = x[:, ::2]
x[:, 0] += 0.125
w13[:, :, 1::2] = (-w13[:, :, ::2].float()).to(w13.dtype)
expected = _reference(
expected = fp8_block_scaled_moe_routes(
x,
w13,
w2,
@@ -596,8 +595,8 @@ def test_gluon_block_fp8_packed_warp_stress(
s2,
ids,
weights,
0,
7.0,
first_expert=0,
limit=7.0,
quantized_activations=False,
)[0]
raw = gluon_fp8_block_warp_decode_moe(
@@ -27,6 +27,7 @@ from dataclasses import dataclass
import pytest
import torch
from tokenspeed_kernel.numerics.torch.moe import fp8_block_scaled_moe_routes
from utils import is_cdna4
pytest.importorskip(
@@ -169,7 +170,6 @@ def test_packed_fp8_runtime_routes_do_not_recompile(
from test_gluon_fp8_packed_small import (
_assert_numerics,
_fixture,
_reference,
_routes,
)
from tokenspeed_kernel_amd.ops.gfx950.moe.fp8.weight_preprocess import (
@@ -201,7 +201,7 @@ def test_packed_fp8_runtime_routes_do_not_recompile(
changed_weights = (
torch.arange(1, 9, device="cuda").float()[None, :].expand_as(weights) / 36.0
)
normal, _ = _reference(
normal, _ = fp8_block_scaled_moe_routes(
x,
w13,
w2,
@@ -209,11 +209,11 @@ def test_packed_fp8_runtime_routes_do_not_recompile(
s2,
original_ids,
original_weights,
start,
7.0,
first_expert=start,
limit=7.0,
quantized_activations=path not in ("warp", "public-warp"),
)
changed, _ = _reference(
changed, _ = fp8_block_scaled_moe_routes(
x,
w13,
w2,
@@ -221,8 +221,8 @@ def test_packed_fp8_runtime_routes_do_not_recompile(
s2,
changed_ids,
changed_weights,
start,
7.0,
first_expert=start,
limit=7.0,
quantized_activations=path not in ("warp", "public-warp"),
)
assert not torch.equal(normal, changed)
@@ -236,7 +236,7 @@ def test_packed_fp8_runtime_routes_do_not_recompile(
w2[expert].fill_(-0.5)
s13[expert].mul_(1.25)
s2[expert].mul_(0.75)
updated, _ = _reference(
updated, _ = fp8_block_scaled_moe_routes(
x,
w13,
w2,
@@ -244,8 +244,8 @@ def test_packed_fp8_runtime_routes_do_not_recompile(
s2,
original_ids,
original_weights,
start,
7.0,
first_expert=start,
limit=7.0,
quantized_activations=path not in ("warp", "public-warp"),
)
assert not torch.equal(normal, updated)
@@ -424,7 +424,6 @@ def test_packed_plan_reuses_one_bank_across_warp_boundary(record_property) -> No
from test_gluon_fp8_packed_small import (
_assert_numerics,
_fixture,
_reference,
)
from tokenspeed_kernel.ops.moe import moe_apply
from tokenspeed_kernel_amd.ops.gfx950.moe.fp8.weight_preprocess import (
@@ -434,7 +433,7 @@ def test_packed_plan_reuses_one_bank_across_warp_boundary(record_property) -> No
x, w13, w2, s13, s2, ids, weights = _fixture(8, 1, 0, False, 4096, 512)
sizes = (1, 2, 3, 4, 5, 8)
references = {
rows: _reference(
rows: fp8_block_scaled_moe_routes(
x[:rows],
w13,
w2,
@@ -442,8 +441,8 @@ def test_packed_plan_reuses_one_bank_across_warp_boundary(record_property) -> No
s2,
ids[:rows],
weights[:rows],
0,
7.0,
first_expert=0,
limit=7.0,
quantized_activations=rows > 4,
)[0]
for rows in sizes
@@ -27,6 +27,7 @@ from collections.abc import Callable
import pytest
import torch
import torch.nn.functional as F
from tokenspeed_kernel.numerics.torch.moe import fp8_block_scaled_moe_routes
pytest.importorskip("tokenspeed_kernel_amd", reason="AMD kernel package is optional")
@@ -72,68 +73,6 @@ def test_packed_fp8_pack_matches_aiter_shuffle_bytes(
assert torch.equal(packed.view(torch.uint8), expected)
def _quantize_reference(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
groups = x.float().reshape(x.shape[0], -1, 128)
scales = groups.abs().amax(dim=-1).clamp_min(1.0e-10) * (1.0 / 448.0)
quantized = (
(groups * scales.reciprocal()[..., None])
.clamp(-448.0, 448.0)
.to(torch.float8_e4m3fn)
)
return quantized.reshape_as(x), scales
def _reference(
x: torch.Tensor,
w13: torch.Tensor,
w2: torch.Tensor,
s13: torch.Tensor,
s2: torch.Tensor,
ids: torch.Tensor,
weights: torch.Tensor,
expert_start: int,
limit: float,
*,
quantized_activations: bool,
) -> tuple[torch.Tensor, bool]:
if quantized_activations:
qx, sx = _quantize_reference(x)
dequantized_x = qx.float() * sx.repeat_interleave(128, dim=1)
else:
dequantized_x = x.float()
partials = torch.zeros(
(*ids.shape, x.shape[1]),
device=x.device,
dtype=torch.bfloat16 if quantized_activations else torch.float32,
)
clamp_active = False
for expert in range(w13.shape[0]):
tokens, slots = torch.where(ids == expert_start + expert)
if tokens.numel() == 0:
continue
gate_up = w13[expert].float() * s13[expert].repeat_interleave(
128, dim=0
).repeat_interleave(128, dim=1)
gate, up = F.linear(dequantized_x[tokens], gate_up).chunk(2, dim=-1)
clamp_active |= bool(((gate > limit) | (up.abs() > limit)).any().item())
intermediate = (F.silu(gate.clamp(max=limit)) * up.clamp(-limit, limit)).to(
torch.bfloat16
)
if quantized_activations:
qi, si = _quantize_reference(intermediate)
dequantized_i = qi.float() * si.repeat_interleave(128, dim=1)
else:
dequantized_i = intermediate.float()
down_weight = w2[expert].float() * s2[expert].repeat_interleave(
128, dim=0
).repeat_interleave(128, dim=1)
down = F.linear(dequantized_i, down_weight)
partials[tokens, slots] = (down * weights[tokens, slots, None]).to(
partials.dtype
)
return partials.float().sum(dim=1).to(torch.bfloat16), clamp_active
def _routes(
m: int, local_experts: int, ep_size: int, expert_start: int, variant: int
) -> torch.Tensor:
@@ -312,7 +251,7 @@ def test_packed_fp8_moe_matches_clamped_routed_reference(
ids[:, 0] = expert_start
ids[:, 1] = expert_start + 1
limit = 10.0 if schedule in ("split", "warp") else 7.0
expected, clamp_active = _reference(
expected, clamp_active = fp8_block_scaled_moe_routes(
x,
w13,
w2,
@@ -320,8 +259,8 @@ def test_packed_fp8_moe_matches_clamped_routed_reference(
s2,
ids,
weights,
expert_start,
limit,
first_expert=expert_start,
limit=limit,
quantized_activations=schedule != "warp",
)
@@ -383,8 +322,17 @@ def test_packed_fp8_large_schedule_with_sparse_routes_matches_reference(
x, w13, w2, s13, s2, ids, weights = _fixture(
m, 1, 0, False, 4096, 512, local_experts=32
)
expected, _ = _reference(
x, w13, w2, s13, s2, ids, weights, 0, 7.0, quantized_activations=True
expected, _ = fp8_block_scaled_moe_routes(
x,
w13,
w2,
s13,
s2,
ids,
weights,
first_expert=0,
limit=7.0,
quantized_activations=True,
)
packed13, packed2 = pack_fp8_weight_n16k32(w13), pack_fp8_weight_n16k32(w2)
del w13, w2
@@ -24,8 +24,12 @@ from __future__ import annotations
import pytest
import torch
from tokenspeed_kernel.numerics.torch.activation import torch_situ_and_mul
from tokenspeed_kernel.numerics.torch.moe import mxfp4_situ_moe_experts
from tokenspeed_kernel.numerics.torch.quantization import dequantize_mxfp4
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_fp8_groups,
dequantize_mxfp4,
)
from utils import is_cdna4
if not is_cdna4():
@@ -142,26 +146,14 @@ def _q32(x):
return q.reshape_as(x), exponent.to(torch.uint8)
def _dequant_q(q, scale):
return (
q.float().reshape(q.shape[0], -1, 32)
* torch.exp2(scale.float() - 127).unsqueeze(-1)
).reshape(q.shape)
def _situ_math(g, u):
# Independent FP32 math; hardware exp2/rcp can differ at a BF16 boundary.
return (
4
* torch.tanh(g.float() / 4)
* torch.sigmoid(g.float())
* (25 * torch.tanh(u.float() / 25))
).bfloat16()
return torch_situ_and_mul(torch.cat((g, u), -1), 4.0, 25.0).bfloat16()
def _expert_math(x, raw, ids, weights, start):
xq, xs = _q32(x)
a = _dequant_q(xq, xs)
a = dequantize_fp8_groups(xq, xs, 32)
result = torch.zeros_like(x, dtype=torch.float32)
for expert in range(raw["w13_weight"].shape[0]):
token, slot = (ids == expert + start).nonzero(as_tuple=True)
@@ -172,7 +164,7 @@ def _expert_math(x, raw, ids, weights, start):
g, u = gu.chunk(2, -1)
zq, zs = _q32(_situ_math(g, u))
w2 = dequantize_mxfp4(raw["w2_weight"][expert], raw["w2_scale"][expert])
projected = _dequant_q(zq, zs) @ w2.T
projected = dequantize_fp8_groups(zq, zs, 32) @ w2.T
contribution = (projected * weights[token, slot].float()[:, None]).bfloat16()
result.index_add_(0, token, contribution.float())
return result.bfloat16()
@@ -28,6 +28,9 @@ import math
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import (
fake_quantize_block_scaled_nvfp4,
)
from utils import is_cdna4
if not is_cdna4():
@@ -489,44 +492,6 @@ def _quant_kernel(scratch, step, PLAN: gl.constexpr, N: gl.constexpr):
quant.quant_stage(mb.row(task), "x_mlp", "xq", "xa", "xq_flag", N, "quant")
def _e2m1(y):
"""Round to the nearest E2M1 value, ties to the even code (TokenSpeed's
thresholds 0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5), saturating at 6."""
a = y.abs()
v = torch.full_like(a, 0.5)
v = torch.where(a <= 0.25, 0.0, v)
v = torch.where(a >= 0.75, 1.0, v)
v = torch.where(a > 1.25, 1.5, v)
v = torch.where(a >= 1.75, 2.0, v)
v = torch.where(a > 2.5, 3.0, v)
v = torch.where(a >= 3.5, 4.0, v)
v = torch.where(a > 5.0, 6.0, v)
return torch.where(y < 0, -v, v)
def _nvfp4_reference(x):
"""``bf16(v sc)`` and amax of rows ``x [R, N]`` (FP32 values)."""
amax = x.abs().amax(-1, keepdim=True)
enc = torch.clamp(torch.tensor(1536.0) / amax, max=3.4028234663852886e38)
dec = 1.0 / enc
outer = amax * (1.0 / 1536.0)
groups = x.view(x.shape[0], -1, 16)
gm = groups.abs().amax(-1, keepdim=True)
cands = []
for target in (6.0, 4.0):
sc = torch.clamp(gm * (enc[:, :, None] * (1.0 / target)), max=448.0)
sc = sc.to(torch.float8_e4m3fn).float()
inv = torch.clamp(1.0 / (sc * dec[:, :, None]), max=3.4028234663852886e38)
v = _e2m1((groups * inv).double()).float()
value = v * sc
e = (groups - value * outer[:, :, None]).abs()
while e.shape[-1] > 1:
e = e.view(*e.shape[:-1], -1, 2).sum(-1)
cands.append((value, e))
best = torch.where(cands[1][1] < cands[0][1], cands[1][0], cands[0][0])
return best.view(x.shape).bfloat16().float(), amax.view(-1)
@_ROUTE_DIMS
@pytest.mark.parametrize("rows,chain", _ROUTE_ROWS)
def test_nvfp4_quant_matches_tokenspeed(dims, rows, chain):
@@ -556,7 +521,7 @@ def test_nvfp4_quant_matches_tokenspeed(dims, rows, chain):
**extern_compile_options(),
)
torch.cuda.synchronize()
want, amax = _nvfp4_reference(x.float())
want, amax = fake_quantize_block_scaled_nvfp4(x.float())
for r in range(rows):
got = words(scratch, plan, "xq", dims.hidden // 2, row=r)
got = got.view(torch.bfloat16).float().cpu()
@@ -31,13 +31,16 @@ import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_nvfp4_blocks,
fake_quantize_block_scaled_nvfp4,
)
from utils import is_cdna4
if not is_cdna4():
pytest.skip("AMD CDNA4 is required", allow_module_level=True)
from monokernel_testing import fill, fill_words, words # noqa: E402
from test_inkling2_attention_gfx950 import _nvfp4_reference # noqa: E402
from tokenspeed_kernel.ops.communication._iris import ( # noqa: E402
IrisGroup,
get_or_create_context,
@@ -133,9 +136,6 @@ def _experts_kernel(scratch, step, up, down, PLAN: gl.constexpr, RANK: gl.conste
)
_E2M1 = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6, -0.0, -0.5, -1, -1.5, -2, -3, -4, -6])
def _bank(local, n, k, g):
"""A random NVFP4 bank of ``local`` experts ``[n, k]`` on the GPU and a
function giving one expert's BF16 values."""
@@ -145,13 +145,9 @@ def _bank(local, n, k, g):
)
wa = (torch.rand(local, generator=g) + 0.5).cuda()
wd = torch.tensor([2.0], device="cuda")
table = _E2M1.cuda()
def values(e):
c = codes[e].int()
v = torch.stack([table[c & 15], table[c >> 4]], -1).view(n, k)
s = scales[e].float().repeat_interleave(16, dim=1)
return (v * s).bfloat16().float()
return dequantize_nvfp4_blocks(codes[e], scales[e]).bfloat16().float()
return (codes, scales, wa, wd), values
@@ -262,6 +258,12 @@ def _regular_swiglu(dims, gate_up, weights, ids):
def _swiglu(gu, gamma):
"""Inkling's capped SwiGLU of interleaved FP32 ``gu``, times ``gamma``,
rounded to BF16."""
# Keep the strided views: on CPU, ATen's sigmoid takes a scalar loop for
# them, whose FP32 results the kernels match bit for bit. A contiguous
# copy (as torch_situ_and_mul's [gate | up] input) takes the SIMD loop,
# which differs by an ulp in about 3% of values and flips BF16 roundings.
g, u = gu[0::2], gu[1::2]
sg = torch.sigmoid(g)
return (
@@ -287,7 +289,7 @@ def test_expert_stages_match_tokenspeed_routes(dims, rows, chain):
ids = _route_ids(dims, RANK, rows, g)
weights = torch.rand(rows, 8, generator=g) + 0.2
x = torch.randn(rows, H, generator=g)
xq, xa = _nvfp4_reference(x)
xq, xa = fake_quantize_block_scaled_nvfp4(x)
for r in range(rows):
route = torch.cat([ids[r], weights[r].view(torch.int32)])
fill(scratch, plan, "route", route.cuda(), tag, row=r)
@@ -368,7 +370,7 @@ def test_expert_stages_match_tokenspeed_routes(dims, rows, chain):
assert torch.equal(gate_up, regular_up[r * 8 + k]), (r, k)
# From the kernel's gate_up on: h, its quantization and w2.
h = _swiglu(gate_up, weights[r, k])
hq, ha = _nvfp4_reference(h.view(1, -1))
hq, ha = fake_quantize_block_scaled_nvfp4(h.view(1, -1))
got_hq = words(scratch, plan, "hq", 8 * INTER // 2, row=r).view(
torch.bfloat16
)
@@ -467,7 +469,7 @@ def test_swiglu_equals_regular_swiglu(dims, rows, chain):
assert torch.equal(got_ha, want_ha[route : route + 1].view(torch.int32))
# And the torch reference of the math.
h = _swiglu(gate_up[route].float(), weights[r, k])
hq, ha = _nvfp4_reference(h.view(1, -1))
hq, ha = fake_quantize_block_scaled_nvfp4(h.view(1, -1))
close = (got_hq[k].view(torch.bfloat16).float() == hq[0]).float().mean()
assert close > 0.995, f"row {r} route {k}: {close:.4f} of hq agree"
torch.testing.assert_close(want_ha[route], ha[0], rtol=2**-7, atol=0)
@@ -26,6 +26,10 @@ from __future__ import annotations
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_fp8_groups,
fake_quantize_block_scaled_mxfp8,
)
from utils import is_cdna4
if not is_cdna4():
@@ -79,21 +83,6 @@ EXPERT_CASES = [(ip.GEOMETRIES[0], rows, chain) for rows, chain in ROWS] + [
EXPERT_IDS = [f"h{d.hidden}-r{rows}-c{chain}" for d, rows, chain in EXPERT_CASES]
def _mxfp8_reference(x):
"""``bf16(v s)`` of rows ``x [R, N]`` (FP32) through TokenSpeed's MXFP8
quantizer (``_mxfp8_chunk_codes``) and the expert GEMMs' decode."""
groups = x.view(x.shape[0], -1, 32)
raw = groups.abs().amax(-1) * torch.tensor(1.0 / 448.0)
bits = raw.view(torch.int32)
exponent = ((bits + 0x007FFFFF) & 0x7F800000) >> 23
exponent = torch.where(raw <= 2.0**-127, 0, exponent.clamp(max=254))
scale = torch.exp2(exponent.double() - 127).float().clamp(min=2.0**-127)
inverse = torch.where(exponent == 0, torch.tensor(2.0**127), 1.0 / scale)
values = (groups * inverse[..., None]).clamp(-448.0, 448.0)
codes = values.to(torch.float8_e4m3fn).float()
return (codes * scale[..., None]).view(x.shape).bfloat16().float()
def _words(x):
return x.bfloat16().contiguous().view(torch.int32)
@@ -159,7 +148,7 @@ def test_mxfp8_quant_equals_regular_quantizer(dims, rows, chain):
"mxfp8",
dequant,
)
want = _mxfp8_reference(x.float())
want = fake_quantize_block_scaled_mxfp8(x.float())
for r in range(rows):
assert payloads(scratch, plan, "xq_flag", 1, tag, row=r).item() == 1
got = words(scratch, plan, "xq", H // 2, row=r).cpu()
@@ -228,8 +217,7 @@ def _bank(local, n, k, g):
exps = exps.cuda()
def values(e):
s = torch.exp2(exps[e].float() - 127).repeat_interleave(32, dim=1)
return (codes[e].float() * s).bfloat16().float()
return dequantize_fp8_groups(codes[e], exps[e], 32).bfloat16().float()
return (codes, exps), values
@@ -322,7 +310,7 @@ def test_mxfp8_expert_stages_equal_regular_routes(dims, rows, chain):
ids = _route_ids(dims, RANK, rows, g)
weights = torch.rand(rows, 8, generator=g) + 0.2
x = torch.randn(rows, H, generator=g) * 4
xq = _mxfp8_reference(x)
xq = fake_quantize_block_scaled_mxfp8(x)
for r in range(rows):
route = torch.cat([ids[r], weights[r].view(torch.int32)])
fill(scratch, plan, "route", route.cuda(), tag, row=r)
@@ -381,7 +369,9 @@ def test_mxfp8_expert_stages_equal_regular_routes(dims, rows, chain):
_assert_dot_close(gate_up, xq[r : r + 1], up_values(e).cpu())
assert torch.equal(gate_up, regular_up[r * 8 + k]), (r, k)
# From the kernel's gate_up on: h, its quantization and w2.
hq = _mxfp8_reference(_swiglu(gate_up, weights[r, k]).view(1, -1))[0]
hq = fake_quantize_block_scaled_mxfp8(
_swiglu(gate_up, weights[r, k]).view(1, -1)
)[0]
assert torch.equal(hq_routes[r * 8 + k], hq), (r, k)
got = _route_pairs(scratch, plan, "ex2", r, k, H // 2, tag)
if r in math_rows:
@@ -458,5 +448,5 @@ def test_mxfp8_swiglu_equals_regular_swiglu(dims, rows, chain):
route = r * 8 + k
assert torch.equal(got_hq[k], want_hq[route].view(torch.int16)), (r, k)
h = _swiglu(gate_up[route].float(), weights[r, k])
hq = _mxfp8_reference(h.view(1, -1))[0]
hq = fake_quantize_block_scaled_mxfp8(h.view(1, -1))[0]
assert torch.equal(got_hq[k].view(torch.bfloat16).float(), hq), (r, k)
@@ -27,6 +27,7 @@ from dataclasses import dataclass
import pytest
import torch
from tokenspeed_kernel.numerics.torch.attention.dsa import (
dsa_pack_fp8_sparse_kv,
torch_dsa_paged_index_topk,
torch_dsa_sparse_attention,
torch_dsa_workspace_index_topk,
@@ -1647,28 +1648,6 @@ def test_dsa_prefill_topk_gluon_long_row_uses_radix_path() -> None:
)
def _pack_sparse_kv(
latent: torch.Tensor,
rope: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
kv_lora_rank = latent.shape[1]
qk_rope_head_dim = rope.shape[1]
scale = latent.float().abs().amax(dim=1, keepdim=True).clamp_min(1.0e-6) / 448.0
latent_fp8 = (latent.float() / scale).clamp(-448.0, 448.0).to(torch.float8_e4m3fn)
row_bytes = kv_lora_rank + kv_lora_rank // 128 * 4 + qk_rope_head_dim * 2
sparse = torch.empty(
(latent.shape[0], row_bytes),
dtype=torch.uint8,
device=latent.device,
)
sparse[:, :kv_lora_rank].copy_(latent_fp8.view(torch.uint8))
scale_start = kv_lora_rank
scale_end = scale_start + kv_lora_rank // 128 * 4
sparse[:, scale_start:scale_end].view(torch.float32).copy_(scale)
sparse[:, scale_end:].view(torch.bfloat16).copy_(rope)
return sparse, latent_fp8.float() * scale
def _dsa_visible_ranges(case: _DSACase, device: str) -> tuple[list[range], int]:
if case.mode == "decode":
assert case.visible_lens is not None
@@ -1758,7 +1737,7 @@ def test_dsa_with_sparse_kvcache(api, q_dtype: torch.dtype) -> None:
q = q_bf16.to(q_dtype)
latent = torch.randn(num_slots, kv_lora_rank, device=device, dtype=torch.bfloat16)
rope = torch.randn(num_slots, qk_rope_head_dim, device=device, dtype=torch.bfloat16)
sparse_kv, dequant_latent = _pack_sparse_kv(latent, rope)
sparse_kv, dequant_latent = dsa_pack_fp8_sparse_kv(latent, rope)
topk_slots = torch.full((tokens, topk), -1, device=device, dtype=torch.int32)
topk_lens = torch.tensor([5, 7, 4], device=device, dtype=torch.int32)
for token in range(tokens):
@@ -2091,7 +2070,7 @@ def test_dsa_decode_sparse_kvcache_trims_large_topk_for_tiny_lens() -> None:
).to(torch.float8_e4m3fn)
latent = torch.randn(num_slots, kv_lora_rank, device=device, dtype=torch.bfloat16)
rope = torch.randn(num_slots, qk_rope_head_dim, device=device, dtype=torch.bfloat16)
sparse_kv, dequant_latent = _pack_sparse_kv(latent, rope)
sparse_kv, dequant_latent = dsa_pack_fp8_sparse_kv(latent, rope)
topk_slots = torch.full((tokens, topk), -1, device=device, dtype=torch.int32)
topk_lens = torch.tensor([1, 3], device=device, dtype=torch.int32)
topk_slots[0, 0] = 2
@@ -2745,7 +2724,7 @@ def test_dsa_lse_matches_the_reference(
(num_slots, qk_rope_head_dim), device=device, generator=generator
)
if kv_kind == "sparse":
sparse_kv, ref_latent = _pack_sparse_kv(latent, rope)
sparse_kv, ref_latent = dsa_pack_fp8_sparse_kv(latent, rope)
caches = {"kv_cache": None, "sparse_kv_cache": sparse_kv}
ref_rope = rope
else:
@@ -3014,7 +2993,7 @@ def test_dsa_glm52_selected_attention_cases(case: _DSACase) -> None:
reference_latent = kv_cache[:, : case.kv_lora_rank]
reference_rope = kv_cache[:, case.kv_lora_rank :]
elif case.kv_layout == "sparse":
sparse_kv_cache, reference_latent = _pack_sparse_kv(latent, rope)
sparse_kv_cache, reference_latent = dsa_pack_fp8_sparse_kv(latent, rope)
reference_rope = rope
else:
raise AssertionError(f"unknown DSA KV layout {case.kv_layout!r}")
@@ -22,6 +22,10 @@
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_fp8_groups,
dequantize_nvfp4_blocks,
)
from utils import assert_no_triton_compile, is_cdna4
if not is_cdna4():
@@ -58,21 +62,6 @@ def _weights(experts, n, k, fmt):
)
def _nvfp4_values(packed, scales):
"""BF16 values of NVFP4 codes: each E2M1 value times its E4M3 group scale."""
codes = torch.stack([packed & 15, packed >> 4], -1).reshape(packed.shape[0], -1)
magnitude = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6], device=packed.device)
value = magnitude[(codes & 7).long()] * torch.where(codes >= 8, -1.0, 1.0)
return (value * scales.float().repeat_interleave(16, dim=1)).bfloat16()
def _mxfp8_values(codes, exponents):
"""BF16 values of MXFP8 codes: each E4M3 value times ``2^(e - 127)`` of
its group's UE8M0 exponent ``e``."""
scale = torch.exp2(exponents.float() - 127).repeat_interleave(32, dim=1)
return (codes.float() * scale).bfloat16()
_EXPERT_MM_TILES = [(16, 128, 256), (16, 64, 256), (32, 128, 128), (64, 128, 128)]
# Ragged shapes take the masked loop. Whole tiles of NVFP4 or MXFP8 weights
# with BF16 activations take the LDS ring; 3 programs run several tiles each
@@ -139,8 +128,11 @@ def test_expert_mm_masking_and_runtime_rows(
if bf16_x:
q, qs, qa, xb = triton_block_quantize_values(x, fmt)
# The quantizer's BF16 values are exactly what its codes encode.
decode = _nvfp4_values if fmt == "nvfp4" else _mxfp8_values
assert torch.equal(xb, decode(q, qs))
if fmt == "nvfp4":
decoded = dequantize_nvfp4_blocks(q, qs)
else:
decoded = dequantize_fp8_groups(q, qs, 32)
assert torch.equal(xb, decoded.bfloat16())
else:
q, qs, qa = triton_block_quantize(x, fmt)
# Expert 12 is always empty. Expert 13 belongs to the next EP shard.
@@ -21,6 +21,7 @@
"""Independent PyTorch convolution/recurrence oracle for retained KDA tests."""
import torch
from tokenspeed_kernel.numerics.torch.attention.kda import kda_delta_rule_steps
from tokenspeed_kernel.ops.attention import kda
from tokenspeed_kernel.ops.metadata import REQUEST_ENDED
from tokenspeed_kernel.platform import current_platform
@@ -297,18 +298,22 @@ def reference(case):
page = int(case["reads"][row])
running = endpoint(case["state"][page], records.history, row)
taps = case["conv"][page].float().clone()
row_states, row_windows = [running.clone()], [taps.clone()]
row_windows = [taps.clone()]
qs, keys, values, decays, betas = [], [], [], [], []
for token in range(begin, end):
joined = torch.cat((taps, case["raw"][token, :, None].float()), dim=-1)
values = (
convolved = (
torch.nn.functional.silu((joined * case["weights"].float()).sum(-1))
.to(case["raw"].dtype)
.float()
)
taps = joined[:, 1:]
q, key, value = (part.view(heads, 128) for part in values.chunk(3))
q = q * torch.rsqrt(q.square().sum(-1, keepdim=True) + 1e-6) * 128**-0.5
key = key * torch.rsqrt(key.square().sum(-1, keepdim=True) + 1e-6)
q, key, value = (part.view(heads, 128) for part in convolved.chunk(3))
qs.append(
q * torch.rsqrt(q.square().sum(-1, keepdim=True) + 1e-6) * 128**-0.5
)
keys.append(key * torch.rsqrt(key.square().sum(-1, keepdim=True) + 1e-6))
values.append(value)
gate = case["gate"][token].float().view(heads, 128) + case["bias"].view(
heads, 128
)
@@ -318,15 +323,16 @@ def reference(case):
if case["lower_bound"] is not None
else -a * torch.nn.functional.softplus(gate)
)
running = running * log_decay.exp()[:, None, :]
correction = (value - (running * key[:, None, :]).sum(-1)) * torch.sigmoid(
case["beta"][token].float()
)[:, None]
running = running + correction[:, :, None] * key[:, None, :]
output[token] = (running * q[:, None, :]).sum(-1)
row_states.append(running.clone())
decays.append(log_decay.exp())
betas.append(torch.sigmoid(case["beta"][token].float()))
row_windows.append(taps.clone())
states.append(row_states)
if qs:
output[begin:end], row_states, _ = kda_delta_rule_steps(
*(torch.stack(x) for x in (qs, keys, values, decays, betas)), running
)
else:
row_states = []
states.append([running.clone(), *row_states])
windows.append(row_windows)
return output, states, windows
@@ -22,6 +22,7 @@ from concurrent.futures import ThreadPoolExecutor
import pytest
import torch
from tokenspeed_kernel.numerics.torch.attention.dsa import dsa_pack_fp8_sparse_kv
from tokenspeed_kernel.ops.attention.dsa import (
deep_gemm,
dsa_decode,
@@ -43,28 +44,6 @@ from tokenspeed_kernel.platform import current_platform
platform = current_platform()
def _pack_sparse_kv(
latent: torch.Tensor,
rope: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
kv_lora_rank = latent.shape[1]
qk_rope_head_dim = rope.shape[1]
scale = latent.float().abs().amax(dim=1, keepdim=True).clamp_min(1.0e-6) / 448.0
latent_fp8 = (latent.float() / scale).clamp(-448.0, 448.0).to(torch.float8_e4m3fn)
row_bytes = kv_lora_rank + kv_lora_rank // 128 * 4 + qk_rope_head_dim * 2
sparse = torch.empty(
(latent.shape[0], row_bytes),
dtype=torch.uint8,
device=latent.device,
)
sparse[:, :kv_lora_rank].copy_(latent_fp8.view(torch.uint8))
scale_start = kv_lora_rank
scale_end = scale_start + kv_lora_rank // 128 * 4
sparse[:, scale_start:scale_end].view(torch.float32).copy_(scale)
sparse[:, scale_end:].view(torch.bfloat16).copy_(rope)
return sparse, latent_fp8.float() * scale
@pytest.mark.skipif(
not (platform.is_nvidia and platform.is_hopper_plus),
reason="The flashmla DSA solution registers on Hopper+ NVIDIA GPUs only",
@@ -80,7 +59,7 @@ def test_flashmla_dsa_dcp_partials(phase, q_len, degree):
query = torch.randn((3, max(4, degree), 576), device="cuda", dtype=torch.bfloat16)
dense = torch.cat((latent, rope), dim=-1)
sparse, reference_latent = (
_pack_sparse_kv(latent, rope) if packed else (None, latent)
dsa_pack_fp8_sparse_kv(latent, rope) if packed else (None, latent)
)
slots = torch.full((3, 512), -1, device="cuda", dtype=torch.int32)
slots[0, :4] = torch.tensor([64, 65, 128, 193], device="cuda")
@@ -32,6 +32,7 @@ from __future__ import annotations
import pytest
import torch
from tokenspeed_kernel.numerics.torch.attention.kda import kda_delta_rule_steps
from utils import assert_no_cute_compile, is_nvidia
if not is_nvidia():
@@ -293,25 +294,29 @@ def _reference(inputs):
page = int(inputs["state_indices"][b])
if page <= 0:
continue
S = inputs["checkpoint_state"][page].double().clone()
for t in range(starts[b + 1] - starts[b]):
tok = starts[b] + t
q = inputs["q"][0, tok].double()
k = inputs["k"][0, tok].double()
x = inputs["raw_g"][0, tok].double() + inputs["dt_bias"].double()
if inputs["lower_bound"] is not None:
gate = inputs["lower_bound"] * torch.sigmoid(A[:, None] * x)
else:
gate = -A[:, None] * torch.nn.functional.softplus(x)
beta = torch.sigmoid(inputs["raw_beta"][0, tok].double())
k = k * torch.rsqrt((k * k).sum(-1, keepdim=True) + 1e-6)
q = q * torch.rsqrt((q * q).sum(-1, keepdim=True) + 1e-6) * key_dim**-0.5
S = S * gate.exp()[:, None, :]
value = inputs["v"][0, tok].double()
c = (value - (S * k[:, None, :]).sum(-1)) * beta[:, None]
S = S + c[:, :, None] * k[:, None, :]
out[0, tok] = (S * q[:, None, :]).sum(-1)
corrections[(b, t)] = c
begin, end = starts[b], starts[b + 1]
if begin == end:
continue
q = inputs["q"][0, begin:end].double()
k = inputs["k"][0, begin:end].double()
x = inputs["raw_g"][0, begin:end].double() + inputs["dt_bias"].double()
if inputs["lower_bound"] is not None:
gate = inputs["lower_bound"] * torch.sigmoid(A[:, None] * x)
else:
gate = -A[:, None] * torch.nn.functional.softplus(x)
beta = torch.sigmoid(inputs["raw_beta"][0, begin:end].double())
k = k * torch.rsqrt((k * k).sum(-1, keepdim=True) + 1e-6)
q = q * torch.rsqrt((q * q).sum(-1, keepdim=True) + 1e-6) * key_dim**-0.5
out[0, begin:end], _, c = kda_delta_rule_steps(
q,
k,
inputs["v"][0, begin:end].double(),
gate.exp(),
beta,
inputs["checkpoint_state"][page].double(),
)
for t in range(end - begin):
corrections[(b, t)] = c[t]
return out, corrections
@@ -22,6 +22,12 @@
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_fp8_blocks,
dequantize_fp8_groups,
quantize_fp8_ue8m0_groups,
unpack_ue8m0_words,
)
from tokenspeed_kernel.ops.gemm import mm
from tokenspeed_kernel.ops.gemm.deepgemm import prepare_deepgemm_fp8_weight
from tokenspeed_kernel.ops.quantization import quantize_fp8
@@ -34,27 +40,6 @@ pytestmark = pytest.mark.skipif(
)
def unpack(scales, groups):
shifts = torch.arange(4, device=scales.device) * 8
exponents = ((scales.to(torch.int64)[..., None] >> shifts) & 255).flatten(1)[
:, :groups
]
return torch.exp2(exponents.float() - 127)
def reference_quant(x):
m, k = x.shape
groups = x.float().view(m, k // 128, 128)
raw = groups.abs().amax(-1).clamp_min(1e-10) / 448
bits = raw.view(torch.int32)
exponent = (((bits >> 23) & 255) + ((bits & 0x7FFFFF) != 0)).clamp(1, 254)
scales = (exponent << 23).view(torch.float32)
codes = (
(groups / scales[..., None]).clamp(-448, 448).to(torch.float8_e4m3fn).view(m, k)
)
return codes, scales, exponent
@pytest.mark.parametrize(
"m,n,k",
[
@@ -76,12 +61,10 @@ def test_registered_deepgemm_values_out_graph(m, n, k, pdl):
try:
w = torch.randn(n, k, device="cuda", dtype=torch.bfloat16) * 0.03
qw, sw = quantize_fp8(w, granularity="block", block_size=[128, 128])
original_weight = qw.float() * sw.repeat_interleave(128, 0)[
:n
].repeat_interleave(128, 1)
original_weight = dequantize_fp8_blocks(qw, sw, 128, 128)
qw, packed_w = prepare_deepgemm_fp8_weight(qw, sw)
prepared_weight = qw.float() * unpack(packed_w, k // 128).repeat_interleave(
128, 1
prepared_weight = dequantize_fp8_groups(
qw, unpack_ue8m0_words(packed_w, k // 128), 128
)
assert (
prepared_weight - original_weight
@@ -101,9 +84,9 @@ def test_registered_deepgemm_values_out_graph(m, n, k, pdl):
)
def check():
qa, sa, _ = reference_quant(x)
dw = qw.float() * unpack(packed_w, k // 128).repeat_interleave(128, 1)
ref = (qa.float() * sa.repeat_interleave(128, 1)) @ dw.t()
qa, ea = quantize_fp8_ue8m0_groups(x, 128, min_amax=1e-10)
dw = dequantize_fp8_groups(qw, unpack_ue8m0_words(packed_w, k // 128), 128)
ref = dequantize_fp8_groups(qa, ea.to(torch.uint8), 128) @ dw.t()
torch.testing.assert_close(out.float(), ref, rtol=0.01, atol=0.001)
assert run().data_ptr() == out.data_ptr()
@@ -37,6 +37,10 @@ if not (
):
pytest.skip("DeepGEMM MegaMoE needs an SM100-family GPU", allow_module_level=True)
from tokenspeed_kernel.numerics.torch.quantization import ( # noqa: E402
dequantize_fp8_groups,
fake_quantize_fp8_groups,
)
from tokenspeed_kernel.ops.activation import silu_and_mul
from tokenspeed_kernel.ops.moe import deep_gemm as mega_moe
@@ -72,19 +76,8 @@ class _Experts(nn.Module):
def _fp8_round_trip(x):
"""Group-32 UE8M0 E4M3 quantize and dequantize, as the input staging rounds."""
tokens, size = x.shape
groups = x.float().view(tokens, size // 32, 32)
amax = groups.abs().amax(-1).clamp_min(1e-4)
bits = (amax / 448.0).view(torch.int32)
exponent = (((bits >> 23) & 0xFF) + ((bits & 0x7FFFFF) != 0).int()).clamp(1, 254)
scale = (exponent << 23).view(torch.float32)[..., None]
return ((groups / scale).to(torch.float8_e4m3fn).float() * scale).view(tokens, size)
def _dequantize(codes, scales):
scale = (scales.int() << 23).view(torch.float32)
return (codes.float().view(codes.shape[0], -1, 32) * scale[..., None]).view(
codes.shape
return fake_quantize_fp8_groups(
x, 32, power_of_two_scale=True, min_scale=1e-4 / 448
)
@@ -140,7 +133,8 @@ def test_fused_shared_expert_adds_its_output():
gate_up, gate_up_scale, down, down_scale = _shared_weights(2)
# Reference: E4M3 inputs, BF16 gate/up as the kernel clamps them, then the
# FP8 round trip of the activations before the down projection.
w1, w2 = _dequantize(gate_up, gate_up_scale), _dequantize(down, down_scale)
w1 = dequantize_fp8_groups(gate_up, gate_up_scale, 32)
w2 = dequantize_fp8_groups(down, down_scale, 32)
g = torch.Generator(device="cuda").manual_seed(3)
cases = []
for tokens in (1, 64, 200):
@@ -33,6 +33,11 @@ import pytest
import torch
import torch.distributed as dist
import torch.nn.functional as F
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_fp8_groups,
dequantize_mxfp4,
fake_quantize_fp8_groups,
)
from tokenspeed_kernel.ops.moe import (
deep_gemm,
moe_apply,
@@ -65,32 +70,11 @@ def group(tmp_path_factory):
dist.destroy_process_group()
def _dequant(packed, scales):
levels = torch.tensor(
[0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6],
device=packed.device,
)
codes = torch.stack((packed & 15, packed >> 4), -1).flatten(-2).long()
sf = torch.exp2(scales.float() - 127).repeat_interleave(32, -1)
return levels[codes] * sf
def _fp8(x):
if not x.numel():
return x
groups = x.reshape(x.shape[0], -1, 32)
scale = torch.exp2(
torch.ceil(torch.log2(groups.abs().amax(-1).clamp_min(1e-4) / 448))
"""MXFP8 round trip of the staged activations (amax floor 1e-4)."""
return fake_quantize_fp8_groups(
x, 32, power_of_two_scale=True, min_scale=1e-4 / 448
)
return (
(groups / scale.unsqueeze(-1)).to(torch.float8_e4m3fn).float()
* scale.unsqueeze(-1)
).reshape_as(x)
def _dequant_fp8(weights, scales):
scale = torch.exp2(scales.float() - 127).repeat_interleave(32, -1)
return weights.float() * scale
class Experts(nn.Module):
@@ -132,7 +116,7 @@ class Experts(nn.Module):
if not rows.numel():
continue
gate, up = (
(xq[rows] @ _dequant(w13[expert], sf13[expert]).T)
(xq[rows] @ dequantize_mxfp4(w13[expert], sf13[expert]).T)
.to(torch.bfloat16)
.float()
.chunk(2, -1)
@@ -140,7 +124,7 @@ class Experts(nn.Module):
# DeepGEMM rounds FC1 to BF16 and applies routing weights before
# quantizing the intermediate activation for FC2.
inter = _fp8(F.silu(gate) * up * scores[rows, slots, None])
value = inter @ _dequant(w2[expert], sf2[expert]).T
value = inter @ dequantize_mxfp4(w2[expert], sf2[expert]).T
result.index_add_(0, rows, value)
return result
@@ -345,7 +329,7 @@ def test_heterogeneous_dp_graph_replay_with_shared_expert(group, monkeypatch):
routed = experts.reference(x, ids, scores)
xq = _fp8(x.float())
gate, up = (
(xq @ _dequant_fp8(ref_gate_up, ref_gate_up_scale).T)
(xq @ dequantize_fp8_groups(ref_gate_up, ref_gate_up_scale, 32).T)
.to(torch.bfloat16)
.float()
.chunk(2, -1)
@@ -353,7 +337,7 @@ def test_heterogeneous_dp_graph_replay_with_shared_expert(group, monkeypatch):
# DeepGEMM rounds the linear accumulators to BF16, then keeps the
# SwiGLU result in FP32 until its per-row FP8 scale and cast.
shared_inter = _fp8(F.silu(gate) * up)
shared = shared_inter @ _dequant_fp8(ref_down, ref_down_scale).T
shared = shared_inter @ dequantize_fp8_groups(ref_down, ref_down_scale, 32).T
expected = routed + shared
run = partial(
@@ -31,6 +31,12 @@ from __future__ import annotations
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_fp8_blocks,
dequantize_fp8_groups,
ue8m0_to_float,
unpack_ue8m0_words,
)
from tokenspeed_kernel.platform import current_platform
if not torch.cuda.is_available() or not current_platform().is_hopper_plus:
@@ -92,22 +98,6 @@ def _pack_weight_scales(scales: torch.Tensor, n: int, k: int) -> torch.Tensor:
)
def _dequantize(q: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
return q.float() * scales.repeat_interleave(_BLOCK, dim=-1)
def _dequantize_weight(q: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
expanded = scales.repeat_interleave(_BLOCK, dim=1).repeat_interleave(_BLOCK, dim=2)
return q.float() * expanded
def _unpack_ue8m0(packed: torch.Tensor, num_groups: int) -> torch.Tensor:
bytes_ = torch.stack(
[(packed >> (8 * i)) & 0xFF for i in range(4)], dim=-1
).flatten(-2)[..., :num_groups]
return torch.exp2(bytes_.float() - 127.0)
def test_masked_swiglu_writes_packed_mn_major_scales_for_deep_gemm():
"""The decode kernel must need no clear or post-quant scale transform."""
torch.manual_seed(0)
@@ -122,7 +112,7 @@ def test_masked_swiglu_writes_packed_mn_major_scales_for_deep_gemm():
)
num_groups = ispp // _BLOCK
scales = _unpack_ue8m0(packed_scales, num_groups)
scales = ue8m0_to_float(unpack_ue8m0_words(packed_scales, num_groups))
assert out.shape == (experts, capacity, ispp)
assert packed_scales.shape == (experts, capacity, 2)
assert packed_scales.dtype == torch.int32
@@ -226,9 +216,9 @@ def test_low_latency_expert_compute_matches_dequantized_reference(enable_pdl):
# Reference on the kernels' own operands so only the masked layout wiring
# is under test, not quantization noise.
x_ref = _dequantize(recv_x, recv_scales)
w13_ref = _dequantize_weight(w13, w13_scales)
w2_ref = _dequantize_weight(w2, w2_scales)
x_ref = dequantize_fp8_groups(recv_x, recv_scales, _BLOCK)
w13_ref = dequantize_fp8_blocks(w13, w13_scales, _BLOCK, _BLOCK)
w2_ref = dequantize_fp8_blocks(w2, w2_scales, _BLOCK, _BLOCK)
for expert in range(experts):
valid = int(masked_m[expert])
if not valid:
@@ -240,10 +230,11 @@ def test_low_latency_expert_compute_matches_dequantized_reference(enable_pdl):
rtol=2e-2,
atol=2e-2 * gateup_ref.abs().max(),
)
down_ref = (
down_in[expert, :valid].float().view(valid, ispp // _BLOCK, _BLOCK)
* _unpack_ue8m0(down_scales[expert, :valid], ispp // _BLOCK)[..., None]
).view(valid, ispp)
down_ref = dequantize_fp8_groups(
down_in[expert, :valid],
unpack_ue8m0_words(down_scales[expert, :valid], ispp // _BLOCK),
_BLOCK,
)
reference = down_ref @ w2_ref[expert].t()
torch.testing.assert_close(
out[expert, :valid].float(),
@@ -31,7 +31,11 @@ from __future__ import annotations
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import dequantize_fp8_groups
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_fp8_blocks,
dequantize_fp8_groups,
unpack_ue8m0_words,
)
from tokenspeed_kernel.ops.activation.triton import fused_swiglu_fp8_ue8m0
from tokenspeed_kernel.ops.moe._deep_ep.permute import (
deepep_gather,
@@ -91,21 +95,9 @@ def _pack_weight_scales(scales: torch.Tensor, n: int, k: int) -> torch.Tensor:
)
def _dequantize(q: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
return q.float() * scales.repeat_interleave(_BLOCK, dim=-1)
def _dequantize_weight(q: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
expanded = scales.repeat_interleave(_BLOCK, dim=1).repeat_interleave(_BLOCK, dim=2)
return q.float() * expanded
def _dequantize_packed(q: torch.Tensor, packed: torch.Tensor) -> torch.Tensor:
num_groups = q.shape[1] // _BLOCK
bytes_ = torch.stack(
[(packed >> (8 * i)) & 0xFF for i in range(4)], dim=-1
).flatten(-2)[:, :num_groups]
return dequantize_fp8_groups(q, bytes_.to(torch.uint8), _BLOCK)
scales = unpack_ue8m0_words(packed, q.shape[1] // _BLOCK)
return dequantize_fp8_groups(q, scales, _BLOCK)
def test_fused_silu_block_quant_fills_mn_major_scales():
@@ -133,7 +125,7 @@ def test_fused_silu_block_quant_fills_mn_major_scales():
torch.nn.functional.silu(gateup[:, :ispp].float()) * gateup[:, ispp:].float()
)
torch.testing.assert_close(
_dequantize(out, scales),
dequantize_fp8_groups(out, scales, _BLOCK),
reference,
rtol=6e-2,
atol=6e-2 * reference.abs().max(),
@@ -202,9 +194,9 @@ def test_normal_mode_expert_compute_matches_dequantized_reference(enable_pdl):
# Reference, stage by stage on the kernels' own operands so only the grouped
# GEMM layout wiring is under test: a mis-tagged row or a mis-strided scale
# block produces garbage, not quantization-level noise.
x_ref = _dequantize(recv_x, recv_scales)
w13_ref = _dequantize_weight(w13, w13_scales)
w2_ref = _dequantize_weight(w2, w2_scales)
x_ref = dequantize_fp8_groups(recv_x, recv_scales, _BLOCK)
w13_ref = dequantize_fp8_blocks(w13, w13_scales, _BLOCK, _BLOCK)
w2_ref = dequantize_fp8_blocks(w2, w2_scales, _BLOCK, _BLOCK)
row_to_token = {}
for token in range(num_recv):
for slot in range(top_k):
@@ -346,7 +338,9 @@ def test_ue8m0_quantized_activations_round_trip_through_the_grouped_gemm():
)
assert torch.isfinite(out).all()
expected = torch.einsum(
"rk,rnk->rn", dequantized, _dequantize_weight(w, w_scales)[m_indices.long()]
"rk,rnk->rn",
dequantized,
dequantize_fp8_blocks(w, w_scales, _BLOCK, _BLOCK)[m_indices.long()],
)
torch.testing.assert_close(
out.float(), expected, rtol=5e-2, atol=5e-2 * expected.abs().max()
@@ -35,7 +35,7 @@ from types import SimpleNamespace
import pytest
import torch
from test_marlin_mxfp4_apply import _clamped_swiglu_moe_reference
from tokenspeed_kernel.numerics.torch.moe import mxfp4_silu_moe_experts
from tokenspeed_kernel.ops.tuning import autotune
from tokenspeed_kernel.platform import ArchVersion, current_platform
from utils import make_mxfp4_moe_weights
@@ -100,8 +100,26 @@ def _case(num_tokens, seed):
scale_range=(126, 127),
)
topk_ids, topk_weights = _routing(num_tokens, num_experts, top_k, generator)
expected = _clamped_swiglu_moe_reference(x, raw, topk_ids, topk_weights, limit)
unclamped = _clamped_swiglu_moe_reference(x, raw, topk_ids, topk_weights, None)
expected = mxfp4_silu_moe_experts(
x,
raw["w13_weight"],
raw["w13_scale"],
raw["w2_weight"],
raw["w2_scale"],
topk_ids,
topk_weights,
limit=limit,
)
unclamped = mxfp4_silu_moe_experts(
x,
raw["w13_weight"],
raw["w13_scale"],
raw["w2_weight"],
raw["w2_scale"],
topk_ids,
topk_weights,
limit=None,
)
magnitude = expected.float().abs().max()
assert (
expected.float() - unclamped.float()
@@ -32,6 +32,10 @@ import types
import pytest
import torch
import torch.distributed as dist
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_mxfp4,
fake_quantize_fp8_groups,
)
from tokenspeed_kernel.ops.moe._cute_dsl.k3_decode_support import (
BATCHES,
EXPERTS,
@@ -49,8 +53,6 @@ pytestmark = pytest.mark.skipif(
int(os.environ.get("WORLD_SIZE", "1")) != TP, reason="requires TP8"
)
FP4 = (0, 0.5, 1, 1.5, 2, 3, 4, 6, -0.0, -0.5, -1, -1.5, -2, -3, -4, -6)
def _setup():
local_rank = int(os.environ["LOCAL_RANK"])
@@ -75,23 +77,11 @@ def _require_multicast():
pytest.skip("platform has no rank-agreed multicast support")
def _dequant_fp4(packed, scales):
"""[rows, k/2] E2M1 pairs and [rows, k/32] E8M0 scales to FP32 [rows, k]."""
table = torch.tensor(FP4, device=packed.device)
values = torch.stack((table[(packed & 15).long()], table[(packed >> 4).long()]), -1)
values = values.flatten(-2)
return values * torch.exp2(scales.float() - 127).repeat_interleave(32, -1)
def _mxfp8(x, *, floor):
"""Per-32 MXFP8 E4M3 round trip; ``floor`` picks the floor(log2 amax) - 8 scale."""
def _mxfp8_floor(x):
"""Per-32 MXFP8 E4M3 round trip with the floor(log2 amax) - 8 scale."""
blocks = x.float().unflatten(-1, (-1, 32))
amax = blocks.abs().amax(-1, keepdim=True).clamp(min=2.0**-126)
if floor:
exponent = torch.floor(torch.log2(amax)) - 8
else:
exponent = torch.ceil(torch.log2(amax / 448))
scale = torch.exp2(exponent)
scale = torch.exp2(torch.floor(torch.log2(amax)) - 8)
quantized = (blocks / scale).clamp(-448, 448).to(torch.float8_e4m3fn).float()
return (quantized * scale).flatten(-2)
@@ -175,15 +165,20 @@ def _reference(weights, x):
routed = scores.gather(1, ids)
routed = routed / (routed.sum(-1, keepdim=True) + 1e-20) * SCALE
latent = _mxfp8((x32 @ weights.down.float().T).bfloat16(), floor=False)
latent = fake_quantize_fp8_groups(
(x32 @ weights.down.float().T).bfloat16(),
32,
power_of_two_scale=True,
min_scale=2.0**-126 / 448,
)
combined = torch.zeros(x.shape[0], LATENT, device=x.device)
for t in range(x.shape[0]):
chosen = ids[t]
for r in range(TP):
w13 = _dequant_fp4(weights.w13[r][chosen], weights.w13_scale[r][chosen])
w2 = _dequant_fp4(weights.w2[r][chosen], weights.w2_scale[r][chosen])
w13 = dequantize_mxfp4(weights.w13[r][chosen], weights.w13_scale[r][chosen])
w2 = dequantize_mxfp4(weights.w2[r][chosen], weights.w2_scale[r][chosen])
gate_up = w13 @ latent[t]
h = _mxfp8(_situ(gate_up[:, :I_RANK], gate_up[:, I_RANK:]), floor=True)
h = _mxfp8_floor(_situ(gate_up[:, :I_RANK], gate_up[:, I_RANK:]))
out = (w2 @ h.unsqueeze(-1)).squeeze(-1)
combined[t] += (routed[t].unsqueeze(-1) * out).sum(0)
rms = torch.rsqrt(combined.pow(2).mean(-1, keepdim=True) + EPS)
@@ -31,13 +31,10 @@ from types import SimpleNamespace
import pytest
import torch
from tokenspeed_kernel.numerics.torch.activation import torch_silu_and_mul
from tokenspeed_kernel.numerics.torch.moe import (
DequantizedExperts,
mxfp4_silu_moe_experts,
mxfp4_situ_moe_experts,
torch_moe_experts,
)
from tokenspeed_kernel.numerics.torch.quantization import dequantize_mxfp4
from tokenspeed_kernel.ops.moe.marlin import (
_swiglu_limit,
marlin_mxfp4_moe_weights,
@@ -248,28 +245,6 @@ def test_marlin_mxfp4_silu_without_situ_beta() -> None:
torch.testing.assert_close(actual.float(), expected.float(), atol=5e-2, rtol=5e-2)
def _clamped_swiglu_moe_reference(
x, raw, topk_ids, topk_weights, limit: float | None
) -> torch.Tensor:
"""Routed MXFP4 experts with the checkpoint's SwiGLU clamp: ``gate`` is
clipped from above only, ``up`` on both sides, before ``silu(gate) * up``
(DeepSeek-V4.1 ``inference/model.py`` ``Expert.forward``)."""
return torch_moe_experts(
x,
DequantizedExperts(dequantize_mxfp4, raw["w13_weight"], raw["w13_scale"]),
DequantizedExperts(dequantize_mxfp4, raw["w2_weight"], raw["w2_scale"]),
topk_ids,
topk_weights,
activation=lambda gate_up: torch_silu_and_mul(gate_up.bfloat16(), limit),
w13_bias=None,
w2_bias=None,
quantize_input=None,
quantize_intermediate=None,
round_expert_output=torch.Tensor.bfloat16,
first_expert=0,
).to(x.dtype)
@pytest.mark.parametrize("ep_size", [1, 2])
def test_marlin_mxfp4_swiglu_honors_checkpoint_clamp_limit(ep_size: int) -> None:
"""``w.swiglu_arg.limit`` must reach the GEMM1 epilogue. Weights are scaled
@@ -305,8 +280,26 @@ def test_marlin_mxfp4_swiglu_honors_checkpoint_clamp_limit(ep_size: int) -> None
)
topk_weights = topk_weights / topk_weights.sum(-1, keepdim=True)
expected = _clamped_swiglu_moe_reference(x, raw, topk_ids, topk_weights, limit)
unclamped = _clamped_swiglu_moe_reference(x, raw, topk_ids, topk_weights, None)
expected = mxfp4_silu_moe_experts(
x,
raw["w13_weight"],
raw["w13_scale"],
raw["w2_weight"],
raw["w2_scale"],
topk_ids,
topk_weights,
limit=limit,
)
unclamped = mxfp4_silu_moe_experts(
x,
raw["w13_weight"],
raw["w13_scale"],
raw["w2_weight"],
raw["w2_scale"],
topk_ids,
topk_weights,
limit=None,
)
magnitude = expected.float().abs().max()
assert (
expected.float() - unclamped.float()
@@ -42,6 +42,9 @@ import torch.distributed as dist
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_nvfp4_blocks as _dequant,
)
from tokenspeed_kernel.numerics.torch.quantization import (
fake_quantize_nvfp4,
)
from utils import is_nvidia
if not is_nvidia():
@@ -70,26 +73,6 @@ LOCAL_EXPERTS = (
TOP_K = 16
def _requant(x, scale):
values = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6], device=x.device)
blocks = x.reshape(*x.shape[:-1], -1, 16)
sf = (blocks.abs().amax(-1) / (6 * scale)).to(torch.float8_e4m3fn).float()
normalized = blocks / (sf.unsqueeze(-1) * scale).clamp_min(1e-30)
# Ties select an even E2M1 code, matching round-to-nearest-even.
distances = (normalized.abs().unsqueeze(-1) - values).abs()
nearest = distances.argmin(-1)
tie = (nearest % 2 == 1) & (nearest < 7)
next_distance = distances.gather(
-1, (nearest + 1).clamp_max(7).unsqueeze(-1)
).squeeze(-1)
nearest = torch.where(
tie & (next_distance == distances.amin(-1)), nearest + 1, nearest
)
return (values[nearest] * normalized.sign() * sf.unsqueeze(-1) * scale).reshape_as(
x
)
def _weights(plan, activation: str, intermediate: int):
w = torch.nn.Module()
w.tp_size = 1
@@ -210,7 +193,7 @@ def _reference(x, ids, weights, reference, capacity, activation):
* (25 * torch.tanh(up / 25))
)
partial = (
((_requant(activated, 1.25) / 1.25) @ w2[local_expert].T)
((fake_quantize_nvfp4(activated, 1.25) / 1.25) @ w2[local_expert].T)
.mul(1.25 * scale2)
.bfloat16()
.float()
@@ -26,6 +26,8 @@ import pytest
import torch
from tokenspeed_kernel._triton import triton
from tokenspeed_kernel.numerics.torch.attention.dsv41 import (
dsv41_clean_logits,
dsv41_mask_table_pages,
torch_dsv41_sparse_scores,
)
from tokenspeed_kernel.ops.attention import dsv41
@@ -642,16 +644,6 @@ def test_mask_invalid_table_pages_matches_the_cleaned_copy(dtype):
run(1, float("nan"))
def _mask_table_pages_reference(values, lengths, table, pages, size):
capacity = table.shape[1] * size
column = torch.arange(capacity, device=values.device)
page = table[:, column // size]
hole = (column[None] < lengths.clamp(0, capacity)[:, None]) & (
(page < 0) | (page >= pages)
)
values[:, :capacity].masked_fill_(hole, -torch.inf)
@pytest.mark.parametrize("strided", [False, True])
def test_mask_invalid_table_pages_graph_replay_matches_the_reference(strided):
"""The chunk-parallel paged mask refreshes lengths, tables and logits on replay.
@@ -690,7 +682,7 @@ def test_mask_invalid_table_pages_graph_replay_matches_the_reference(strided):
fill(storage, lengths, table, ends)
expected = storage.clone()
values = storage[:, : width * 64]
_mask_table_pages_reference(expected, lengths, table, pages, 64)
dsv41_mask_table_pages(expected, lengths, table, pages, 64)
if graph is None:
mask_invalid_table_pages(values, lengths, table, pages, 64)
else:
@@ -1385,22 +1377,6 @@ def test_full_metadata_reuses_schedule_and_refreshes_live_inputs(monkeypatch):
torch.testing.assert_close(captured, expected, rtol=0, atol=0)
def _reference_clean(values, lengths, table, pages, capacity, width, page_size):
"""Torch oracle: valid logits, -inf for future columns and invalid pages."""
columns = torch.arange(width, device=values.device)
valid = (columns[None, :] < capacity) & (
columns[None, :] < lengths.clamp(0, capacity)[:, None]
)
page_index = columns // page_size
page = table[:, page_index.clamp(max=table.shape[1] - 1)]
valid &= (page_index < table.shape[1])[None, :] & (page >= 0) & (page < pages)
padded = torch.full(
(values.shape[0], width), -float("inf"), dtype=values.dtype, device="cuda"
)
padded[:, :capacity] = values[:, :capacity]
return torch.where(valid, padded, -float("inf"))
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32])
def test_wide_clean_logits_strides_each_row_over_its_tiles(dtype):
# 256 rows of a 40-tile capacity launch 16 programs per row, each looping.
@@ -1419,7 +1395,7 @@ def test_wide_clean_logits_strides_each_row_over_its_tiles(dtype):
table[1::4, 9::11] = pages + 2
alignment = deep_select_alignment()[0] // values.element_size()
width = triton.cdiv(capacity, alignment) * alignment
expected = _reference_clean(
expected = dsv41_clean_logits(
values, lengths, table, pages, capacity, width, page_size
)
full = clean_logits(values, lengths, table, pages, capacity, page_size)
@@ -18,6 +18,7 @@
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import quantize_fp8_ue8m0_groups
from tokenspeed_kernel.ops.quantization import quantize_fp8
pytestmark = pytest.mark.skipif(
@@ -37,21 +38,11 @@ def quantize(x, pdl):
)
def reference(x):
k = x.shape[-1]
groups = x.float().reshape(-1, k // 128, 128)
raw = groups.abs().amax(-1).clamp_min(1e-10) * (1.0 / 448)
bits = raw.view(torch.int32)
exponent = ((bits >> 23) & 255) + ((bits & 0x7FFFFF) != 0)
scales = (exponent << 23).view(torch.float32)
q = (groups / scales[..., None]).clamp(-448, 448).to(torch.float8_e4m3fn)
return q.reshape(x.shape), exponent
def check(x, q, s):
k = x.shape[-1]
m = x.numel() // k
expected, exponents = reference(x)
expected, exponents = quantize_fp8_ue8m0_groups(x, 128, min_amax=1e-10)
exponents = exponents.reshape(-1, k // 128)
torch.testing.assert_close(
q.view(torch.uint8), expected.view(torch.uint8), rtol=0, atol=0
)
@@ -30,6 +30,7 @@ from pathlib import Path
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import quantize_fp8_ue8m0_groups
from tokenspeed_kernel.ops.attention.dsv41 import rope_quantize_fp8_grouped
from tokenspeed_kernel.ops.gemm import (
fp8_projection,
@@ -81,13 +82,7 @@ def _reference(values, positions, cache, groups):
def _quantize_group32(x):
"""Group-32 UE8M0 quantization of FP32 values with a 1e-4 amax floor."""
blocks = x.unflatten(-1, (x.shape[-1] // 32, 32))
raw = blocks.abs().amax(-1).clamp_min(1e-4) / 448
bits = raw.view(torch.int32)
exponent = ((bits >> 23) & 255) + ((bits & 0x7FFFFF) != 0).to(torch.int32)
scale = (exponent << 23).view(torch.float32)
codes = (blocks / scale[..., None]).flatten(-2).to(torch.float8_e4m3fn)
return codes, exponent
return quantize_fp8_ue8m0_groups(x, 32, min_amax=1e-4)
def _unpack(scales):
@@ -27,6 +27,7 @@ import math
import pytest
import torch
from tokenspeed_kernel.numerics.torch.attention.mha import torch_paged_attention
from tokenspeed_kernel.platform import current_platform
platform = current_platform()
@@ -66,26 +67,6 @@ def _inputs(seq_lens: list[int], q_len: int, seed: int) -> dict:
)
def _reference(inputs: dict) -> torch.Tensor:
"""FP32 causal attention per request: query row i sees keys up to
seq_len - q_len + i."""
q_len = inputs["max_seqlen_q"]
outs = []
for row, seq_len in enumerate(inputs["cache_seqlens"].tolist()):
q = inputs["q"][row * q_len : (row + 1) * q_len].float()
pages = inputs["page_table"][row].long()
k = inputs["k_cache"][pages].flatten(0, 1)[:seq_len].float()
v = inputs["v_cache"][pages].flatten(0, 1)[:seq_len].float()
k = k.repeat_interleave(HEADS_Q // HEADS_KV, dim=1)
v = v.repeat_interleave(HEADS_Q // HEADS_KV, dim=1)
logits = torch.einsum("qhd,khd->hqk", q, k) / math.sqrt(HEAD_DIM)
keys = torch.arange(seq_len, device="cuda")
last = seq_len - q_len + torch.arange(q_len, device="cuda")
logits = logits.masked_fill(keys[None, :] > last[:, None], float("-inf"))
outs.append(torch.einsum("hqk,khd->qhd", logits.softmax(-1), v))
return torch.cat(outs)
@pytest.mark.parametrize(
"seq_lens, q_len",
[
@@ -108,7 +89,18 @@ def test_repeated_and_replayed_decodes_agree(seq_lens: list[int], q_len: int):
)
first = decode()
torch.testing.assert_close(first.float(), _reference(inputs), atol=2e-2, rtol=2e-2)
expected, _ = torch_paged_attention(
inputs["q"],
inputs["k_cache"],
inputs["v_cache"],
inputs["page_table"],
seq_lens,
[q_len] * len(seq_lens),
scale=1 / math.sqrt(HEAD_DIM),
window_left=None,
sinks=None,
)
torch.testing.assert_close(first.float(), expected, atol=2e-2, rtol=2e-2)
for _ in range(2):
assert torch.equal(decode(), first)
@@ -22,30 +22,18 @@
import pytest
import torch
from test_gdn_wy_cute_dsl import make_case, reference
from test_gdn_wy_cute_dsl import make_case, recurrence, reference
from tokenspeed_kernel.ops.attention.gdn import GdnPendingReplay, gdn_decode_mtp
from utils import assert_no_cute_compile, move_pages_past_int32
def accepted_state(case, counts):
k = case["k"].double()
if case["use_qk_l2norm"]:
k = k / (k.square().sum(-1, keepdim=True) + 1e-6).sqrt()
k = k.repeat_interleave(case["v"].shape[2] // k.shape[2], 2)
decay = (
-case["A_log"].double().exp()
* torch.nn.functional.softplus(case["a"].double() + case["dt_bias"].double())
).exp()
beta = case["b"].double().sigmoid()
h = case["initial_state"][case["initial_state_indices"].long()].double()
for t in range(4):
decayed = h * decay[:, t, :, None, None]
update = (
case["v"][:, t].double() - (decayed * k[:, t, :, None, :]).sum(-1)
) * beta[:, t, :, None]
changed = decayed + update[..., None] * k[:, t, :, None, :]
h = torch.where((counts > t)[:, None, None, None], changed, h)
return h
"""FP64 state of each chain request after its first ``counts`` tokens."""
_, states = recurrence(case)
initial = case["initial_state"][case["initial_state_indices"].long()].double()
steps = counts.long().to(states.device)
accepted = states[torch.arange(states.shape[0]), (steps - 1).clamp_min(0)]
return torch.where((steps > 0)[:, None, None, None], accepted, initial)
@pytest.mark.parametrize(
@@ -24,6 +24,11 @@ import json
import pytest
import torch
from tokenspeed_kernel.numerics.torch.attention.gdn import (
gdn_gate,
gdn_l2norm,
torch_gdn_recurrence,
)
from tokenspeed_kernel.platform import current_platform, pdl_enabled
from tokenspeed_kernel.profiling import ShapeCapture, shape_capture
@@ -84,45 +89,40 @@ def make_case(*, batch, tokens, dtype, state_dtype, tree, strided, heads, vheads
)
def reference(case):
def recurrence(case):
"""FP64 token-recurrence outputs and per-node K-last states of ``case``;
a negative state index starts from zeros."""
q, k, v = (case[name].double() for name in ("q", "k", "v"))
if case["use_qk_l2norm"]:
q = q / (q.square().sum(-1, keepdim=True) + 1e-6).sqrt()
k = k / (k.square().sum(-1, keepdim=True) + 1e-6).sqrt()
group = v.shape[2] // q.shape[2]
q, k = (x.repeat_interleave(group, 2) for x in (q, k))
gate = -case["A_log"].double().exp() * torch.nn.functional.softplus(
case["a"].double() + case["dt_bias"].double()
q, k = gdn_l2norm(q, 1e-6), gdn_l2norm(k, 1e-6)
gate = gdn_gate(
case["a"].double(), case["dt_bias"].double(), case["A_log"].double()
)
decay = gate.exp()
beta = case["b"].double().sigmoid()
indices = case["initial_state_indices"].long()
initial = case["initial_state"][indices.clamp_min(0)].double()
initial = torch.where((indices >= 0)[:, None, None, None], initial, 0)
tokens = q.shape[1]
if case["tree_ancestors"] is None:
masks = [
[(1 << (node + 1)) - 1 for node in range(tokens)] for _ in range(q.shape[0])
parents = None
if case["tree_ancestors"] is not None:
# A node's parent is its deepest ancestor other than itself.
parents = [
[(mask ^ (1 << node)).bit_length() - 1 for node, mask in enumerate(row)]
for row in case["tree_ancestors"].cpu().tolist()
]
else:
masks = case["tree_ancestors"].cpu().tolist()
outputs = []
for request in range(q.shape[0]):
states = []
result = []
for node in range(tokens):
parent = (masks[request][node] ^ (1 << node)).bit_length() - 1
h = initial[request] if parent < 0 else states[parent]
h = h * decay[request, node, :, None, None]
delta = (
v[request, node] - (h * k[request, node, :, None, :]).sum(-1)
) * beta[request, node, :, None]
h = h + delta[..., None] * k[request, node, :, None, :]
scale = 128**-0.5 if case["scale"] is None else case["scale"]
result.append((h * q[request, node, :, None, :]).sum(-1) * scale)
states.append(h)
outputs.append(torch.stack(result))
return torch.stack(outputs)
return torch_gdn_recurrence(
q,
k,
v,
gate,
case["b"].double().sigmoid(),
initial,
scale=128**-0.5 if case["scale"] is None else case["scale"],
parents=parents,
compute_dtype=torch.float64,
)
def reference(case):
return recurrence(case)[0]
@pytest.mark.parametrize(
@@ -25,6 +25,7 @@ from types import SimpleNamespace
import pytest
import torch
import torch.nn.functional as F
from tokenspeed_kernel.numerics.torch.quantization import quantize_fp8_ue8m0_groups
from tokenspeed_kernel.ops.residual import (
try_mhc_shifted_post_pre_norm,
try_mhc_shifted_post_pre_norm_quantize_fp8,
@@ -111,17 +112,6 @@ def test_shifted_mhc_matches_reference(tokens, hidden, iters):
torch.testing.assert_close(args[name], original, atol=0, rtol=0)
def _group32_reference(y):
"""UE8M0 exponents and E4M3 codes the group-32 quantizers write for y."""
groups = y.float().unflatten(-1, (-1, 32))
raw = groups.abs().amax(-1).clamp_min(1e-4) * (1.0 / 448.0)
bits = raw.view(torch.int32)
exponent = ((bits >> 23) & 255) + ((bits & 0x7FFFFF) != 0).to(torch.int32)
inverse = (exponent << 23).view(torch.float32)
codes = (groups / inverse[..., None]).flatten(-2).to(torch.float8_e4m3fn)
return exponent, codes
@pytest.mark.parametrize(
"tokens,hidden", [(1, 1024), (17, 5120), (257, 5120), (2048, 5120)]
)
@@ -139,7 +129,7 @@ def test_shifted_mhc_quantize_fp8_matches_group32_reference(tokens, hidden):
assert packed.stride() == (1, (tokens + 3) // 4 * 4)
shifts = torch.arange(4, device=packed.device) * 8
exponent = ((packed[..., None] >> shifts) & 255).flatten(-2).to(torch.int32)
expected_exponent, expected_codes = _group32_reference(y)
expected_codes, expected_exponent = quantize_fp8_ue8m0_groups(y, 32, min_amax=1e-4)
torch.testing.assert_close(exponent, expected_exponent, atol=0, rtol=0)
torch.testing.assert_close(
codes.view(torch.uint8), expected_codes.view(torch.uint8), atol=0, rtol=0
@@ -2,6 +2,7 @@ from __future__ import annotations
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import dequantize_fp8_groups
from tokenspeed_kernel.ops.gemm import (
_online_quantize_mxfp8,
mm,
@@ -133,10 +134,6 @@ def _quantize_mxfp8(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
return q, s.view(x.shape[0], x.shape[1] // 32)
def _dequantize_mxfp8(q: torch.Tensor, s: torch.Tensor) -> torch.Tensor:
return q.float() * torch.exp2(s.float() - 127.0).repeat_interleave(32, dim=1)
@requires_flashinfer_mxfp8
@pytest.mark.parametrize("m", [4, 16, 512])
@pytest.mark.parametrize("n,k", [(2304, 6144), (6144, 2048), (128, 6144)])
@@ -226,7 +223,7 @@ def test_flashinfer_mxfp8_selected_with_online_quant(device: str) -> None:
# mm() quantizes the activation online with the same FlashInfer quantizer;
# dequantizing that result keeps quantization noise out of the comparison.
a_q, a_s = _quantize_mxfp8(a)
ref = _dequantize_mxfp8(a_q, a_s) @ _dequantize_mxfp8(b_q, b_s).t()
ref = dequantize_fp8_groups(a_q, a_s, 32) @ dequantize_fp8_groups(b_q, b_s, 32).t()
torch.testing.assert_close(out.float(), ref, atol=1e-3, rtol=1e-2)
@@ -24,8 +24,10 @@ from dataclasses import replace
import pytest
import torch
from qsa_fp8_prefill_reference import reference as fp8_reference
from tokenspeed_kernel.numerics.torch.attention.qsa import torch_qsa_selected_attention
from tokenspeed_kernel.numerics.torch.attention.qsa import (
qsa_fp8_prefill_attention,
torch_qsa_selected_attention,
)
from tokenspeed_kernel.ops.attention.qsa import (
QSASparseMetadata,
QSAWorkspace,
@@ -160,7 +162,7 @@ def _call(case, *, scales, override):
def _reference(case, scales):
q, k, v, slots, _ = case
return fp8_reference(
return qsa_fp8_prefill_attention(
q,
k,
v,
@@ -24,6 +24,7 @@ batched commit."""
import pytest
import torch
from kda_retained_reference import prepare_history
from tokenspeed_kernel.numerics.torch.attention.kda import kda_delta_rule_steps
from tokenspeed_kernel.ops.attention import kda
from tokenspeed_kernel.ops.metadata import REQUEST_ENDED, REQUEST_ENDED_INCOMPLETE
from tokenspeed_kernel.platform import current_platform
@@ -67,7 +68,7 @@ def _reference_tokens(running, taps, raw, weights, gate, beta, begin, end):
Two heads of dim 128, gate bound -5. Returns the per-token outputs,
corrections, keys and decays as [tokens, heads, dim] and the final state.
"""
outputs, corrections, keys, decays = [], [], [], []
qs, keys, values, decays, betas = [], [], [], [], []
for token in range(begin, end):
window_taps = torch.cat([taps, raw[token, :, None].float()], dim=-1)
convolved = (
@@ -77,20 +78,16 @@ def _reference_tokens(running, taps, raw, weights, gate, beta, begin, end):
)
taps = window_taps[:, 1:]
q, key, value = (x.reshape(2, 128) for x in convolved.chunk(3))
q = q / torch.sqrt(q.square().sum(-1, keepdim=True) + 1e-6) / (128**0.5)
key = key / torch.sqrt(key.square().sum(-1, keepdim=True) + 1e-6)
decay = (-5.0 * torch.sigmoid(gate[token].float().view(2, 128))).exp()
running = running * decay[:, None, :]
correction = (value - (running * key[:, None, :]).sum(-1)) * torch.sigmoid(
beta[token].float()
)[:, None]
running = running + correction[:, :, None] * key[:, None, :]
outputs.append((running * q[:, None, :]).sum(-1))
corrections.append(correction)
keys.append(key)
decays.append(decay)
stacked = [torch.stack(x) for x in (outputs, corrections, keys, decays)]
return (*stacked, running)
qs.append(q / torch.sqrt(q.square().sum(-1, keepdim=True) + 1e-6) / (128**0.5))
keys.append(key / torch.sqrt(key.square().sum(-1, keepdim=True) + 1e-6))
values.append(value)
decays.append((-5.0 * torch.sigmoid(gate[token].float().view(2, 128))).exp())
betas.append(torch.sigmoid(beta[token].float()))
keys, decays = torch.stack(keys), torch.stack(decays)
outputs, states, corrections = kda_delta_rule_steps(
torch.stack(qs), keys, torch.stack(values), decays, torch.stack(betas), running
)
return outputs, corrections, keys, decays, states[-1]
@pytest.mark.parametrize("layout", ["v_major", "k_major"])
@@ -15,6 +15,10 @@ from tokenspeed_kernel.numerics.torch.activation import (
torch_situ_and_mul,
torch_swiglu_oai,
)
from tokenspeed_kernel.numerics.torch.quantization import (
ue8m0_to_float,
unpack_ue8m0_words,
)
from tokenspeed_kernel.ops.activation import silu_and_mul as dispatched_silu_and_mul
from tokenspeed_kernel.ops.activation.triton import (
_moe_finalize_gate_add_kernel,
@@ -759,13 +763,6 @@ def test_situ_and_mul_preallocated_out(device: str) -> None:
# --- fused_swiglu_fp8_ue8m0 tests ---
def _unpack_ue8m0(packed: torch.Tensor, num_groups: int) -> torch.Tensor:
bytes_ = torch.stack(
[(packed >> (8 * i)) & 0xFF for i in range(4)], dim=-1
).flatten(-2)[..., :num_groups]
return torch.exp2(bytes_.float() - 127.0)
@pytest.mark.skipif(not platform.is_nvidia, reason="requires float8_e4m3fn CUDA")
@pytest.mark.parametrize("shape", [(1, 1024), (7, 1024), (128, 3584), (333, 1280)])
@pytest.mark.parametrize("limit,alpha,beta", [(0.0, 1.0, 0.0), (7.0, 1.702, 1.0)])
@@ -785,7 +782,7 @@ def test_fused_swiglu_fp8_ue8m0_matches_reference(
ref_q, ref_scale = torch_fused_swiglu_fp8_ue8m0(gate_up, limit, alpha, beta)
num_groups = out.shape[1] // 128
got_scale = _unpack_ue8m0(packed_scale, num_groups)
got_scale = ue8m0_to_float(unpack_ue8m0_words(packed_scale, num_groups))
torch.testing.assert_close(got_scale, ref_scale, rtol=0, atol=0)
dequant = out.float().view(out.shape[0], num_groups, 128) * got_scale[..., None]
+31 -64
View File
@@ -25,6 +25,7 @@ import sys
import pytest
import torch
from tokenspeed_kernel.numerics.torch.attention.mha import torch_paged_attention
from tokenspeed_kernel.ops.attention import attn_merge_state
from tokenspeed_kernel.ops.attention.mha import (
mha_decode_with_kvcache,
@@ -776,42 +777,6 @@ def _paged_decode_problem(
return q, k_cache, v_cache, page_table, cache_seqlens
def _causal_decode_reference(
q, k_cache, v_cache, page_table, cache_seqlens, rows, window_left, sinks, scale
):
"""fp32 ``(out, natural-log lse)``: row ``t`` of ``rows`` sees the first
``seq_len - (rows - 1 - t)`` keys (the last ``window_left + 1`` of them)."""
_, page_size, num_kv_heads, head_dim = k_cache.shape
group = q.shape[1] // num_kv_heads
outs, lses = [], []
for req, seq_len in enumerate(cache_seqlens.tolist()):
pages = page_table[req, : max(1, -(-seq_len // page_size))].long()
keys = k_cache[pages].reshape(-1, num_kv_heads, head_dim)[:seq_len]
values = v_cache[pages].reshape(-1, num_kv_heads, head_dim)[:seq_len]
keys = keys.float().repeat_interleave(group, dim=1)
values = values.float().repeat_interleave(group, dim=1)
scores = (
torch.einsum("rhd,khd->hrk", q[req * rows : (req + 1) * rows].float(), keys)
* scale
)
pos = torch.arange(seq_len, device=q.device)
end = seq_len - (rows - 1 - torch.arange(rows, device=q.device))
visible = pos[None, :] < end[:, None]
if window_left >= 0:
visible &= pos[None, :] >= end[:, None] - (window_left + 1)
scores = scores.masked_fill(~visible[None], float("-inf"))
lse = torch.logsumexp(scores, dim=-1)
if sinks is not None:
scores = torch.cat(
[scores, sinks.float()[:, None, None].expand(-1, rows, 1)], dim=-1
)
values = torch.cat([values, values.new_zeros(1, *values.shape[1:])])
probs = torch.softmax(scores, dim=-1).nan_to_num(0.0)
outs.append(torch.einsum("hrk,khd->rhd", probs, values))
lses.append(lse.transpose(0, 1))
return torch.cat(outs), torch.cat(lses)
@pytest.mark.parametrize(
"rows,num_q_heads,num_kv_heads,head_dim",
[
@@ -843,8 +808,16 @@ def test_triton_mha_decode_folds_query_rows(
)
sinks = torch.randn(num_q_heads, device=device) if has_sink else None
scale = head_dim**-0.5
expected_out, expected_lse = _causal_decode_reference(
q, k_cache, v_cache, page_table, cache_seqlens, rows, window_left, sinks, scale
expected_out, expected_lse = torch_paged_attention(
q,
k_cache,
v_cache,
page_table,
seq_lens,
[rows] * len(seq_lens),
scale=scale,
window_left=window_left if window_left >= 0 else None,
sinks=sinks,
)
result = mha_decode_with_kvcache(
q=q,
@@ -887,8 +860,16 @@ def test_triton_mha_decode_grouped_heads_read_their_kv_head(
seq_lens, 1, num_q_heads, num_kv_heads, 128, 64, device
)
scale = 128**-0.5
expected, _ = _causal_decode_reference(
q, k_cache, v_cache, page_table, cache_seqlens, 1, -1, None, scale
expected, _ = torch_paged_attention(
q,
k_cache,
v_cache,
page_table,
seq_lens,
[1] * len(seq_lens),
scale=scale,
window_left=None,
sinks=None,
)
out = mha_decode_with_kvcache(
q=q,
@@ -965,28 +946,6 @@ def _paged_cache(
return k.to(device), v.to(device), table.to(device)
def _decode_reference(q, k_cache, v_cache, table, lens, window_left, scale):
"""FP32 decode of one query per request over its last keys, with the LSE."""
page_size, num_kv_heads, head_dim = k_cache.shape[1:]
group = q.shape[1] // num_kv_heads
outs, lses = [], []
for i, n in enumerate(lens):
start = max(0, n - window_left - 1) if window_left >= 0 else 0
rows = table[i].long()
k = k_cache[rows].reshape(-1, num_kv_heads, head_dim)[start:n].float()
v = v_cache[rows].reshape(-1, num_kv_heads, head_dim)[start:n].float()
k = k.repeat_interleave(group, dim=1)
v = v.repeat_interleave(group, dim=1)
logits = torch.einsum("hd,khd->hk", q[i].float(), k) * scale
if n == start:
outs.append(torch.zeros_like(q[i], dtype=torch.float32))
lses.append(torch.full((q.shape[1],), -math.inf, device=q.device))
continue
lses.append(torch.logsumexp(logits, dim=1))
outs.append(torch.einsum("hk,khd->hd", logits.softmax(dim=1), v))
return torch.stack(outs), torch.stack(lses)
@pytest.mark.parametrize("num_q_heads", [4, 16], ids=["mha", "gqa"])
@pytest.mark.parametrize("window_left", [-1, 300], ids=["full", "window"])
def test_triton_mha_decode_returns_lse_at_every_batch_size(
@@ -1011,8 +970,16 @@ def test_triton_mha_decode_returns_lse_at_every_batch_size(
q = torch.randn(
len(lens), num_q_heads, head_dim, device=device, dtype=torch.bfloat16
)
out_ref, lse_ref = _decode_reference(
q, k_cache, v_cache, table, lens, window_left, scale
out_ref, lse_ref = torch_paged_attention(
q,
k_cache,
v_cache,
table,
lens,
[1] * len(lens),
scale=scale,
window_left=window_left if window_left >= 0 else None,
sinks=None,
)
for return_lse in (False, True):
result = mha_decode_with_kvcache(
@@ -25,6 +25,7 @@ import math
import pytest
import torch
from tokenspeed_kernel.numerics.torch.attention.dsa import (
dsa_pack_fp8_sparse_kv,
torch_dsa_logits_topk,
torch_dsa_sparse_attention,
)
@@ -441,28 +442,6 @@ def test_dsa_workspace_conversion_graph_replay(device: str) -> None:
torch.testing.assert_close(captured, expected)
def _pack_sparse_kv(
latent: torch.Tensor,
rope: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
kv_lora_rank = latent.shape[1]
qk_rope_head_dim = rope.shape[1]
scale = latent.float().abs().amax(dim=1, keepdim=True).clamp_min(1.0e-6) / 448.0
latent_fp8 = (latent.float() / scale).clamp(-448.0, 448.0).to(torch.float8_e4m3fn)
row_bytes = kv_lora_rank + kv_lora_rank // 128 * 4 + qk_rope_head_dim * 2
sparse = torch.empty(
(latent.shape[0], row_bytes),
dtype=torch.uint8,
device=latent.device,
)
sparse[:, :kv_lora_rank].copy_(latent_fp8.view(torch.uint8))
scale_start = kv_lora_rank
scale_end = scale_start + kv_lora_rank // 128 * 4
sparse[:, scale_start:scale_end].view(torch.float32).copy_(scale)
sparse[:, scale_end:].view(torch.bfloat16).copy_(rope)
return sparse, latent_fp8.float() * scale
@pytest.mark.parametrize(
"mode,api_name",
[
@@ -506,7 +485,7 @@ def test_dsa_with_kvcache(
q = q_bf16.to(q_dtype)
latent = torch.randn(num_slots, kv_lora_rank, device=device, dtype=torch.bfloat16)
rope = torch.randn(num_slots, qk_rope_head_dim, device=device, dtype=torch.bfloat16)
sparse_kv, dequant_latent = _pack_sparse_kv(latent, rope)
sparse_kv, dequant_latent = dsa_pack_fp8_sparse_kv(latent, rope)
topk_slots = torch.full((tokens, topk), -1, device=device, dtype=torch.int32)
topk_lens = torch.tensor([5, 7, 4], device=device, dtype=torch.int32)
for token in range(tokens):
@@ -620,7 +599,7 @@ def test_dsa_lse_partials_reconstruct_full_attention(packed, degree):
query = torch.randn((3, 4, 576), device="cuda", dtype=torch.bfloat16)
dense = torch.cat((latent, rope), dim=-1)
sparse, reference_latent = (
_pack_sparse_kv(latent, rope) if packed else (None, latent)
dsa_pack_fp8_sparse_kv(latent, rope) if packed else (None, latent)
)
slots = torch.full((3, 512), -1, device="cuda", dtype=torch.int32)
slots[0, :4] = torch.tensor([64, 65, 128, 193], device="cuda")
@@ -1279,7 +1258,7 @@ def test_dsa_tensor_core_tiles(
tokens, heads, rank + rope_dim, device=device, dtype=torch.bfloat16
).to(q_dtype)
sparse, reference_latent = (
_pack_sparse_kv(latent, rope) if packed else (None, latent)
dsa_pack_fp8_sparse_kv(latent, rope) if packed else (None, latent)
)
slots = torch.randperm(width, device=device).int().repeat(tokens, 1)
slots[:, 11::17] = -1
@@ -1348,7 +1327,7 @@ def test_dsa_batch_shapes_reuse_compilation(device, packed):
latent = torch.randn(64, 128, device=device, dtype=torch.bfloat16)
rope = torch.empty(64, 0, device=device, dtype=torch.bfloat16)
sparse = _pack_sparse_kv(latent, rope)[0] if packed else None
sparse = dsa_pack_fp8_sparse_kv(latent, rope)[0] if packed else None
query = torch.randn(1024, 2, 128, device=device, dtype=torch.bfloat16)
slots = torch.full((1024, 512), -1, device=device, dtype=torch.int32)
slots[:, :64] = torch.arange(64, device=device)
@@ -27,6 +27,8 @@ from unittest.mock import patch
import pytest
import torch
from tokenspeed_kernel.numerics.torch.attention.dsv41 import (
dsv41_clean_logits_for_selection,
dsv41_mask_table_pages,
torch_dsv41_cache_quantize,
torch_dsv41_compressor_pairs,
)
@@ -1839,30 +1841,6 @@ def test_indexer_rope_weight_dispatch_graph_replay(device, rows):
torch.testing.assert_close(actual_w, initial_w * scale, rtol=0, atol=0)
def _clean_selection_reference(values, lengths, table, pages, capacity, size, align):
"""clean_logits_for_selection on [0, end); NaN marks what it leaves unspecified."""
width = (capacity + align - 1) // align * align
out = torch.full((values.shape[0], width), torch.nan, dtype=values.dtype)
column = torch.arange(capacity)
page = table[:, column // size]
valid = (column[None] < lengths.clamp(0, capacity)[:, None]) & (
(page >= 0) & (page < pages)
)
out[:, :capacity] = values[:, :capacity].masked_fill(~valid, -torch.inf)
return out
def _mask_table_pages_reference(values, lengths, table, pages, size):
capacity = table.shape[1] * size
column = torch.arange(capacity)
page = table[:, column // size]
hole = (column[None] < lengths.clamp(0, capacity)[:, None]) & (
(page < 0) | (page >= pages)
)
values[:, :capacity].masked_fill_(hole, -torch.inf)
return values
@pytest.mark.parametrize("alignment_bytes", [256, 2048])
def test_paged_scores_mask_native_rows_in_place(monkeypatch, alignment_bytes):
"""Paged scoring selects from DeepGEMM's rows masked in place.
@@ -1897,11 +1875,11 @@ def test_paged_scores_mask_native_rows_in_place(monkeypatch, alignment_bytes):
def clean(*args):
calls.append("clean")
return _clean_selection_reference(*args)
return dsv41_clean_logits_for_selection(*args)
def mask(*args):
calls.append("mask")
return _mask_table_pages_reference(*args)
return dsv41_mask_table_pages(*args)
monkeypatch.setattr(native, "_api", lambda queries: Api())
monkeypatch.setattr(
@@ -1935,7 +1913,7 @@ def test_paged_scores_mask_native_rows_in_place(monkeypatch, alignment_bytes):
native_rows = 512 * 2 % alignment_bytes == 0
assert calls == (["mask"] if native_rows else ["clean"])
assert blocks is None and ends.tolist() == [200, 320, 0]
expected = _clean_selection_reference(
expected = dsv41_clean_logits_for_selection(
original, ends, table, pages, capacity, 64, alignment
)
assert scores.shape == expected.shape
@@ -2034,9 +2012,7 @@ def test_mask_invalid_table_pages_chunks_match_the_reference(
storage[:, capacity:] = torch.nan
reference = storage.to("cpu", copy=True)
_mask_table_pages_reference(
reference[:, :capacity], lengths.cpu(), table, pages, 64
)
dsv41_mask_table_pages(reference[:, :capacity], lengths.cpu(), table, pages, 64)
out = implementation.mask_invalid_table_pages(
storage[:, :capacity], lengths, device_table, pages, 64
)
@@ -2205,7 +2181,7 @@ def test_mask_invalid_table_pages_rows_past_int32(triton_device):
table = torch.tensor([[0, 1, 2, 3], [4, 5, 6, 7], [1, -1, 3, 9]], dtype=torch.int32)
lengths = torch.full((3,), capacity, dtype=torch.int32, device=device)
reference = values.to("cpu", copy=True)
_mask_table_pages_reference(reference, lengths.cpu(), table, 8, 64)
dsv41_mask_table_pages(reference, lengths.cpu(), table, 8, 64)
implementation.mask_invalid_table_pages(values, lengths, table.to(device), 8, 64)
assert torch.equal(_bits(values).cpu(), _bits(reference))
@@ -2523,7 +2499,7 @@ def test_native_index_topk_fused_selection_matches_the_separate_passes(
monkeypatch.setattr(indexer, "_warmup_sparse_mqa", lambda *args: None)
# _clean_logits strides its tiles with a loop the interpreter cannot run.
monkeypatch.setattr(
native, "clean_logits_for_selection", _clean_selection_reference
native, "clean_logits_for_selection", dsv41_clean_logits_for_selection
)
for module in (native, deep_select, indexer):
monkeypatch.setattr(module, "deep_select_alignment", lambda: (256, 32))
@@ -20,6 +20,7 @@
import pytest
import torch
from tokenspeed_kernel.numerics.torch.quantization import quantize_fp8_ue8m0_groups
from tokenspeed_kernel.ops.embedding import host_gather, triton_host_gather
from utils import assert_no_triton_compile
@@ -87,11 +88,8 @@ def _quantized_rows(table: torch.Tensor, indices: torch.Tensor):
codes = rows[..., :dim].view(torch.float8_e4m3fn).float()
scales = rows[..., dim:].view(torch.float8_e8m0fnu).float()
values = (codes.unflatten(-1, (-1, 32)) * scales[..., None]).bfloat16().float()
amax = values.abs().amax(-1).clamp_min(1e-4)
bits = (amax * (1.0 / 448.0)).view(torch.int32)
exponent = ((bits >> 23) & 255) + ((bits & 0x7FFFFF) != 0).int()
quantized = (values / (exponent << 23).view(torch.float32)[..., None]).to(
torch.float8_e4m3fn
quantized, exponent = quantize_fp8_ue8m0_groups(
values.flatten(-2), 32, min_amax=1e-4
)
tokens = ids.shape[0]
return quantized.view(torch.uint8).reshape(tokens, -1), exponent.to(
@@ -1,115 +0,0 @@
# Copyright (c) 2026 LightSeek Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Independent reference for explicit FP8 approximation; caller sets IEEE matmul."""
import math
import torch
def reference(q, k, v, slots, positions, ids, *, attention_scale, k_scale, v_scale):
"""Evaluate selected rows with explicit Q/P FP8 rounding and FP32 accumulation.
Uses per-head maxabs/448 Q scales and 128-token online-softmax tiles with
FP8-rounded probabilities. The caller configures IEEE matmul precision;
this function does not change global precision settings.
Args:
q: Queries [rows, 12 * kv_heads, 256], converted to FP32 before quantizing.
k: Key-cache values [cache_slots, kv_heads, 256].
v: Value-cache values with the same shape as k.
slots: Physical slots [rows, 2051]. Complete four-token blocks occupy
the prefix (up to 2048 entries); up to three causal tail tokens
occupy columns starting at 2048. Nonpositive slots are masked.
positions: Zero-based query positions [rows], bounding each row's
complete-block prefix and tail; negative positions give empty rows.
ids: One-dimensional indices of the query rows to evaluate, in output order.
attention_scale: Scalar multiplier for query-key scores.
k_scale: Scalar key-cache descale applied to scores.
v_scale: Scalar value-cache descale applied to the normalized output.
Returns:
FP32 attention values [len(ids), 12 * kv_heads, 256], with zero for
fully masked rows. Final BF16 rounding is left to the caller.
"""
kv_heads = k.shape[1]
queries = q[ids].float().reshape(len(ids), kv_heads, 12, 256)
selected, pos = slots[ids], positions[ids]
visible = (pos + 1).clamp_min(0)
complete = (visible // 4).clamp_max(512) * 4
length = complete + visible % 4
logical = torch.arange(2051, device=q.device)[None, :]
columns = torch.where(
logical < complete[:, None], logical, 2048 + logical - complete[:, None]
).clamp_max(2050)
physical = selected.gather(1, columns.long()).long()
valid = (logical < length[:, None]) & (physical > 0)
physical = torch.where(valid, physical, torch.zeros_like(physical))
operands = []
for cache in (k, v):
x = cache[physical].float().permute(0, 2, 1, 3).contiguous()
operands.append(torch.where(valid[:, None, :, None], x, torch.zeros_like(x)))
keys, values = operands
maximum = queries.abs().amax(-1, keepdim=True)
# Use correctly rounded FP32 division; Torch scalar division can instead
# multiply by a rounded reciprocal and change FP8 midpoint decisions.
scale = torch.where(
maximum > 0, (maximum.double() / 448.0).float(), torch.ones_like(maximum)
)
quantized = (
(queries.double() / scale.double())
.float()
.clamp(-448, 448)
.to(torch.float8_e4m3fn)
.float()
)
scores = (
(quantized @ keys.transpose(-1, -2))
* (
scale
* (
float(k_scale)
* float(
torch.tensor(
math.log2(math.e) * attention_scale, dtype=torch.float32
)
)
)
)
).masked_fill(~valid[:, None, None, :], -torch.inf)
running_max = torch.full(scores.shape[:-1], -torch.inf, device=q.device)
denominator = torch.zeros_like(running_max)
numerator = torch.zeros((*running_max.shape, 256), device=q.device)
for start in range(0, 2051, 128):
tile = scores[..., start : start + 128]
updated = torch.maximum(running_max, tile.amax(-1))
safe = torch.where(torch.isneginf(updated), torch.zeros_like(updated), updated)
alpha = torch.exp2(running_max - safe)
probability = torch.exp2(tile - safe[..., None])
denominator = denominator * alpha + probability.sum(-1)
rounded = (probability * 448.0).to(torch.float8_e4m3fn).float()
numerator = (
numerator * alpha[..., None] + rounded @ values[..., start : start + 128, :]
)
running_max = updated
return (
numerator * (v_scale / (denominator.clamp_min(1e-30)[..., None] * 448.0))
).reshape(len(ids), kv_heads * 12, 256)
@@ -21,7 +21,7 @@
"""CPU regression for numerical-reference isolation."""
import torch
from qsa_fp8_prefill_reference import reference
from tokenspeed_kernel.numerics.torch.attention.qsa import qsa_fp8_prefill_attention
def test_fp8_reference_preserves_matmul_precision():
@@ -34,7 +34,7 @@ def test_fp8_reference_preserves_matmul_precision():
v = torch.ones_like(k)
slots = torch.full((1, 2051), -1, dtype=torch.int32)
slots[0, 2048] = 1
reference(
qsa_fp8_prefill_attention(
q,
k,
v,