Skip to content
This repository was archived by the owner on Oct 6, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions sparkinfer/attention/_shared/mla/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@ def sparse_mla_decode_forward(
forced_num_splits: int | None = None,
scale_format: int | None = None,
fp8_rope: bool | None = None,
latent_scale_per_token: bool = False,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
q_all, page_table_1, cache_seqlens_int32, nsa_cache_seqlens_int32, workspace = (
_resolve_sparse_mla_binding(
Expand Down Expand Up @@ -419,6 +420,7 @@ def sparse_mla_decode_forward(
forced_num_splits=forced_num_splits,
scale_format=scale_format,
fp8_rope=fp8_rope,
latent_scale_per_token=latent_scale_per_token,
)


Expand All @@ -438,6 +440,7 @@ def sparse_mla_extend_forward(
identity_page_table: bool = False,
scale_format: int | None = None,
fp8_rope: bool | None = None,
latent_scale_per_token: bool = False,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
(
q_all,
Expand Down Expand Up @@ -470,6 +473,7 @@ def sparse_mla_extend_forward(
identity_page_table=identity_page_table,
scale_format=scale_format,
fp8_rope=fp8_rope,
latent_scale_per_token=latent_scale_per_token,
)


Expand All @@ -492,6 +496,7 @@ def _run_sparse_mla(
forced_num_splits: int | None = None,
scale_format: int | None = None,
fp8_rope: bool | None = None,
latent_scale_per_token: bool = False,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if q_all.ndim != 3:
raise ValueError(f"q_all must be rank-3, got {tuple(q_all.shape)}")
Expand Down Expand Up @@ -613,6 +618,19 @@ def _run_sparse_mla(
raise NotImplementedError(
"NVFP4 sparse MLA requires the active SM120 kernel path"
)
# FAIL-CLOSED: the per-token fp32 latent scale lives at bytes [292, 296) of
# the NVFP4 fp8-rope 368-byte record ONLY.
if latent_scale_per_token:
if int(scale_format_for_call or -1) != 2:
raise ValueError(
"sparse MLA latent_scale_per_token requires the NVFP4 cache "
f"(scale_format=2); got scale_format={scale_format_for_call!r}"
)
if int(kv_cache.shape[-1]) != 368:
raise ValueError(
"sparse MLA latent_scale_per_token requires the fp8-rope "
f"368-byte NVFP4 record; got {int(kv_cache.shape[-1])} bytes"
)
if attn_sink is not None:
attn_sink = attn_sink.detach()
if not _sm120_route:
Expand Down Expand Up @@ -686,6 +704,7 @@ def _run_sparse_mla(
lse_scale=lse_scale,
scale_format=scale_format_for_call,
fp8_rope=fp8_rope_for_call,
latent_scale_per_token=latent_scale_per_token,
)
from .kernel import run_unified_decode

Expand All @@ -704,6 +723,7 @@ def _run_sparse_mla(
forced_num_splits=forced_num_splits,
scale_format_override=scale_format_for_call,
fp8_rope_override=fp8_rope_for_call,
latent_scale_per_token=latent_scale_per_token,
)
if _is_cuda_graph_capture_active(q_all.device):
raise RuntimeError(
Expand Down Expand Up @@ -749,6 +769,7 @@ def _run_sm120_prefill(
lse_scale: Literal["base2", "natural"],
scale_format: int | None = None,
fp8_rope: bool | None = None,
latent_scale_per_token: bool = False,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""Route a prefill-like call to the active SM120 single-pass prefill."""
from .kernel import run_unified_prefill
Expand All @@ -770,6 +791,7 @@ def _run_sm120_prefill(
output=output,
scale_format=scale_format,
fp8_rope=fp8_rope,
latent_scale_per_token=latent_scale_per_token,
)
if not return_lse:
return output
Expand Down
49 changes: 44 additions & 5 deletions sparkinfer/attention/_shared/mla/decode_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@ def s1_qk_nope_block_scaled(
scale_bytes_per_token: cutlass.Constexpr, # 8
scale_format: cutlass.Constexpr = 0, # ScaleFormat.UE8M0_BYTE (0) / ARBITRARY_FP32 (1)
valid_hpb: cutlass.Constexpr = 16,
latent_scale_per_token: cutlass.Constexpr = False, # NVFP4_E4M3 only
):
"""S1: accumulate Q_nope . K_nope into qk[0..3] via NUM_SCALES*(QUANT_TILE/32)
block-scaled MMAs (14 DSV4 / 16 GLM).
Expand Down Expand Up @@ -619,6 +620,8 @@ def s1_qk_nope_block_scaled(
quant_tile=quant_tile,
q_nope_bf16_stride=q_nope_stride,
kv_smem_stride=kv_smem_stride,
latent_scale_per_token=latent_scale_per_token,
kv_sc_base_addr=kv_sc_base_addr,
)

gid = lane >> Int32(2)
Expand Down Expand Up @@ -743,18 +746,26 @@ def s1_qk_nope_nvfp4_bf16(
quant_tile: cutlass.Constexpr, # 64
q_nope_bf16_stride: cutlass.Constexpr, # 520 elems
kv_smem_stride: cutlass.Constexpr, # 288 bytes
latent_scale_per_token: cutlass.Constexpr = False,
kv_sc_base_addr: Int32 = Int32(0),
):
"""S1 (NVFP4): BF16 QK-NoPE over in-register dequantized E2M1 K.

Storage has 32 E4M3 scales per token (group-16). The outer loop keeps the
logical FP4 K-step count at 512/64=8, and the inner loop feeds four BF16
m16n8k16 MMAs per 64-dim step.

``latent_scale_per_token``: this lane's candidate row is fixed
(``kv_gid_row``), so its record scale is hoisted once from kv_sc and fed
through the unchanged per-pair dequant path.
"""
gid = lane >> Int32(2)
tid = lane & Int32(3)
a_row = (lane & Int32(7)) + ((lane >> Int32(3)) & Int32(1)) * Int32(8)
a_col = (lane >> Int32(4)) * Int32(8)
kv_gid_row = warp_first_cand + gid
if cutlass.const_expr(latent_scale_per_token):
latent_scale = ld_shared_f32(kv_sc_base_addr + kv_gid_row * Int32(4))

for blk in cutlass.range_constexpr(num_scales):
for ks in cutlass.range_constexpr(quant_tile // 16):
Expand Down Expand Up @@ -1297,8 +1308,16 @@ def _nvfp4_pair_bfloat2(
latent_scale: Float32,
*,
kv_smem_stride: cutlass.Constexpr,
latent_scale_per_token: cutlass.Constexpr = False,
kv_sc_base_addr: Int32 = Int32(0),
) -> Uint32:
"""Dequant E2M1 * inline E4M3 * per-layer outer scale to bf16x2."""
"""Dequant E2M1 * inline E4M3 * outer scale to bf16x2.

The outer scale is the per-layer launch scalar (``latent_scale``), or --
``latent_scale_per_token`` -- the record's own fp32 second-level scale,
staged per candidate into the contiguous kv_sc buffer by the IO gather
(record bytes [292, 296)).
"""
data_byte = _ld_u8_zext(
kv_fp4_base_addr,
entry * Int32(kv_smem_stride) + (dim_even // Int32(2)),
Expand All @@ -1311,12 +1330,15 @@ def _nvfp4_pair_bfloat2(
entry * Int32(kv_smem_stride) + Int32(_NVFP4_SCALE_OFFSET) + scale_group,
)
scale_f = cvt_e4m3_to_f32_via_f16(scale_byte)
outer = latent_scale
if cutlass.const_expr(latent_scale_per_token):
outer = ld_shared_f32(kv_sc_base_addr + entry * Int32(4))
# This is the single NVFP4 decode dequant point shared by QK and P.V.
# Apply s_l before BF16 packing so both MMAs consume the same true-magnitude
# latent; the separate BF16 RoPE path never calls this helper.
# Apply the outer scale before BF16 packing so both MMAs consume the same
# true-magnitude latent; the separate RoPE path never calls this helper.
return pack_f32x2_to_bfloat2(
(v0 * scale_f) * latent_scale,
(v1 * scale_f) * latent_scale,
(v0 * scale_f) * outer,
(v1 * scale_f) * outer,
)


Expand All @@ -1328,13 +1350,17 @@ def _nvfp4_scalar_bf16_u16(
latent_scale: Float32,
*,
kv_smem_stride: cutlass.Constexpr,
latent_scale_per_token: cutlass.Constexpr = False,
kv_sc_base_addr: Int32 = Int32(0),
) -> Uint32:
pair = _nvfp4_pair_bfloat2(
kv_fp4_base_addr,
entry,
dim & ~Int32(1),
latent_scale,
kv_smem_stride=kv_smem_stride,
latent_scale_per_token=latent_scale_per_token,
kv_sc_base_addr=kv_sc_base_addr,
)
return _bf16x2_extract_lane_u16(pair, dim & Int32(1))

Expand Down Expand Up @@ -1734,6 +1760,7 @@ def s6_xv_nope(
pack_hilo_rows: cutlass.Constexpr = False,
sm_p_full_addr: Int32 = None, # NVFP4 BF16 PV only
sm_p_stride: cutlass.Constexpr = 0, # NVFP4: bf16 elems per sm_p row (0 -> BI)
latent_scale_per_token: cutlass.Constexpr = False, # NVFP4_E4M3 only
):
"""S6: accumulate W . V_nope into acc_nope[vc*NT+nt][0..3] via PLAIN fp8 MMAs
(14 DSV4 / 16 GLM = N_V_CHUNKS * NT_PER_WARP_XV * (BI/32)).
Expand Down Expand Up @@ -1787,6 +1814,8 @@ def s6_xv_nope(
n_warps=n_warps,
nt_per_warp_xv=nt_per_warp_xv,
sm_p_stride=(sm_p_stride if sm_p_stride else bi),
latent_scale_per_token=latent_scale_per_token,
kv_sc_base_addr=kv_sc_base_addr,
)

bar_kw = dict(barrier_id=barrier_id, number_of_threads=num_threads)
Expand Down Expand Up @@ -2085,6 +2114,8 @@ def s6_xv_nope_nvfp4_bf16(
n_warps: cutlass.Constexpr, # 8
nt_per_warp_xv: cutlass.Constexpr, # 1
sm_p_stride: cutlass.Constexpr = 0, # bf16 elems per sm_p row (0 -> BI)
latent_scale_per_token: cutlass.Constexpr = False,
kv_sc_base_addr: Int32 = Int32(0),
):
"""S6 (NVFP4): BF16 P.V over in-register dequantized E2M1 V.

Expand Down Expand Up @@ -2120,27 +2151,35 @@ def s6_xv_nope_nvfp4_bf16(
col,
latent_scale,
kv_smem_stride=kv_smem_stride,
latent_scale_per_token=latent_scale_per_token,
kv_sc_base_addr=kv_sc_base_addr,
)
v1 = _nvfp4_scalar_bf16_u16(
kv_fp4_base_addr,
ent0 + Int32(1),
col,
latent_scale,
kv_smem_stride=kv_smem_stride,
latent_scale_per_token=latent_scale_per_token,
kv_sc_base_addr=kv_sc_base_addr,
)
v8 = _nvfp4_scalar_bf16_u16(
kv_fp4_base_addr,
ent0 + Int32(8),
col,
latent_scale,
kv_smem_stride=kv_smem_stride,
latent_scale_per_token=latent_scale_per_token,
kv_sc_base_addr=kv_sc_base_addr,
)
v9 = _nvfp4_scalar_bf16_u16(
kv_fp4_base_addr,
ent0 + Int32(9),
col,
latent_scale,
kv_smem_stride=kv_smem_stride,
latent_scale_per_token=latent_scale_per_token,
kv_sc_base_addr=kv_sc_base_addr,
)
b0 = v0 | (v1 << Uint32(16))
b1 = v8 | (v9 << Uint32(16))
Expand Down
21 changes: 21 additions & 0 deletions sparkinfer/attention/_shared/mla/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ def io_issue_gather(
packed_dsv4: cutlass.Constexpr = False,
split_mbar_arrival: cutlass.Constexpr = False,
overlap_footer_gather: cutlass.Constexpr = False,
per_token_latent_scale: cutlass.Constexpr = False,
):
"""Producer body for ONE chunk into buffer ``buf`` (caller selects the dst
addrs + full_mbar_ptr for ``buf``). Mirrors FlashInfer ``issue_gather``:
Expand Down Expand Up @@ -338,6 +339,26 @@ def _issue_payload():
s_byte = entry * _FOOT
st_shared_u32(kv_sc_dst_addr + s_byte, f0)
st_shared_u32(kv_sc_dst_addr + s_byte + Int32(4), f1)
elif cutlass.const_expr(
scale_format == 2 and fp8_rope and per_token_latent_scale
):
# NVFP4 two-level record: the per-token fp32 latent scale sits
# at [292, 296). 292 is not 8B-aligned, so load the 8-aligned
# pair at [288, 296) (rope scale, latent scale) and keep the
# second word -- same nc.v2 pattern as the DSV4 footer.
f1 = Uint32(0)
if idx_raw >= Int32(0):
block_idx = idx_raw // _section_pbs
local_idx = idx_raw - block_idx * _section_pbs
scale_base_off = (
Int64(block_idx) * _section_stride
+ Int64(local_idx) * _IOS
+ Int64(_NVFP4_FP8_ROPE_TAIL_SRC)
)
_, f1 = ld_global_nc_v2_u32(
get_ptr_as_int64(_section_kv, scale_base_off)
)
st_shared_u32(kv_sc_dst_addr + entry * Int32(4), f1)
eo += Int32(io_threads)

# --- (2) CTA-scope fence: footer/index stores visible before release. ---
Expand Down
34 changes: 34 additions & 0 deletions sparkinfer/attention/_shared/mla/io_mg.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@ def io_issue_gather_glm_mg(
io_threads: cutlass.Constexpr = _IO_THREADS,
scale_format: cutlass.Constexpr = 1,
fp8_rope: cutlass.Constexpr = False,
per_token_latent_scale: cutlass.Constexpr = False,
kv_sc_dst_addr: Int32 = Int32(0),
):
"""Gather one BI=64 GLM prefill tile into MG smem.

Expand All @@ -169,6 +171,38 @@ def io_issue_gather_glm_mg(
_ios = Int64(_GLM_IO_STRIDE)
_nope = Int32(_GLM_NOPE_SCALE_BYTES)

if cutlass.const_expr(
scale_format == 2 and fp8_rope and per_token_latent_scale
):
# NVFP4 two-level record: scalar-gather the per-token fp32 latent
# scale ([292, 296); loaded as the second word of the 8-aligned pair
# at [288, 296)) into the contiguous smem kv_sc buffer -- the MG
# analogue of the DSV4 footer gather above. The fence orders these
# stores before the leader's arrive, exactly like the DSV4 path.
eo = Int32(0)
for _ in cutlass.range_constexpr((bi + io_threads - 1) // io_threads):
entry = eo + io_lane
if entry < Int32(bi):
cand_pos = g_start + entry
idx_raw = Int32(-1)
if cand_pos < g_end:
idx_raw = Int32(topk_indices[cand_pos])
f1 = Uint32(0)
if idx_raw >= Int32(0):
block_idx = idx_raw // page_block_size
local_idx = idx_raw - block_idx * page_block_size
scale_base_off = (
Int64(block_idx) * stride_kv_block
+ Int64(local_idx) * _ios
+ Int64(288)
)
_, f1 = ld_global_nc_v2_u32(
get_ptr_as_int64(kv_cache_u8, scale_base_off)
)
st_shared_u32(kv_sc_dst_addr + entry * Int32(4), f1)
eo += Int32(io_threads)
cute.arch.fence_acq_rel_cta()

if io_lane == Int32(0):
cute.arch.mbarrier_arrive_and_expect_tx(full_mbar_ptr, Int32(bi) * _nope)

Expand Down
Loading