From 4f3d68dcc3f915ecb42482e4d1297ea7fe9c6c8b Mon Sep 17 00:00:00 2001 From: derek Date: Mon, 27 Jul 2026 19:50:13 -0400 Subject: [PATCH 1/3] mla: self-describing two-level NVFP4 records (per-token latent scale) The nvfp4_ds_mla writer quantizes at an implicit outer scale of 1.0, which parks small-magnitude tokens' E4M3 group scales in subnormals (GLM-5.2 kv_c spans ~240x across layers; shallow layers land at max_abs ~0.02). The static per-layer calibration file corrects the positioning but is checkpoint-specific and goes stale. This mode makes the record self-describing instead: writer (per_token_scale=True): s_t = token_amax / (6*448) # warp-bfly reduce over group amaxes stored fp32 at record bytes [292, 296) (existing zero pad; the record stays 368 bytes) and every group scale byte is encoded relative to s_t, so the largest group's E4M3 scale sits at the top of range by construction -- no calibration artifact, for any checkpoint, ever. readers (latent_scale_per_token=True): value = e2m1 * e4m3(group scale) * s_t, with s_t scalar-gathered per candidate into the kv_sc smem buffer (decode io + MG io, same idiom as the DSV4 footer gather; 8-aligned nc.v2 load at [288, 296), second word). QK hoists per candidate row; the launch-scalar latent_scale is dead in this mode. Threading: traits field + central fail-closed checks (NVFP4_E4M3 + 368-byte fp8-rope record only), decode/MG smem kv_sc allocation (BI x 4 per buffer), api/kernel entry kwargs (default off), compile spec bumps (writer 2->3, decode 18->19, MG prefill 4->5) so stale cubins can never run against the new record semantics. Mode off keeps every specialization byte-identical. Tests: tests/attention/test_mla_kv_cache_per_token_scale.py -- record ABI (bit-exact s_t, pad, mode-independent rope lane), the positioning invariant (max group scale >= 256 per token; the static writer's shallow-magnitude subnormal defect reproduced as a unit test), accuracy dominance at shallow magnitudes, zero-token edge. DRAFT: authored without CUDA; not yet compiled. Validation runbook: glm52-opt design/nvfp4-dynamic-second-level-scale-phaseA-addendum.md. Co-authored-by: Fable Claude-Session: https://claude.ai/code/session_01YHuYXXq9krPdvcgpzY4EfE --- sparkinfer/attention/_shared/mla/api.py | 22 ++ .../attention/_shared/mla/decode_math.py | 49 +++- sparkinfer/attention/_shared/mla/io.py | 21 ++ sparkinfer/attention/_shared/mla/io_mg.py | 34 +++ sparkinfer/attention/_shared/mla/kernel.py | 42 +++- sparkinfer/attention/_shared/mla/kv_cache.py | 153 +++++++++--- sparkinfer/attention/_shared/mla/prefill.py | 16 +- .../attention/_shared/mla/prefill_mg.py | 89 ++++++- sparkinfer/attention/_shared/mla/smem.py | 12 +- sparkinfer/attention/_shared/mla/smem_mg.py | 18 +- sparkinfer/attention/_shared/mla/traits.py | 20 ++ .../test_mla_kv_cache_per_token_scale.py | 224 ++++++++++++++++++ 12 files changed, 640 insertions(+), 60 deletions(-) create mode 100644 tests/attention/test_mla_kv_cache_per_token_scale.py diff --git a/sparkinfer/attention/_shared/mla/api.py b/sparkinfer/attention/_shared/mla/api.py index 2e7299683..2cf58b803 100644 --- a/sparkinfer/attention/_shared/mla/api.py +++ b/sparkinfer/attention/_shared/mla/api.py @@ -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( @@ -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, ) @@ -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, @@ -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, ) @@ -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)}") @@ -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: @@ -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 @@ -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( @@ -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 @@ -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 diff --git a/sparkinfer/attention/_shared/mla/decode_math.py b/sparkinfer/attention/_shared/mla/decode_math.py index d44f67af3..670386016 100644 --- a/sparkinfer/attention/_shared/mla/decode_math.py +++ b/sparkinfer/attention/_shared/mla/decode_math.py @@ -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). @@ -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) @@ -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): @@ -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)), @@ -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, ) @@ -1328,6 +1350,8 @@ 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, @@ -1335,6 +1359,8 @@ def _nvfp4_scalar_bf16_u16( 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)) @@ -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)). @@ -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) @@ -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. @@ -2120,6 +2151,8 @@ 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, @@ -2127,6 +2160,8 @@ 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, ) v8 = _nvfp4_scalar_bf16_u16( kv_fp4_base_addr, @@ -2134,6 +2169,8 @@ 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, ) v9 = _nvfp4_scalar_bf16_u16( kv_fp4_base_addr, @@ -2141,6 +2178,8 @@ 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, ) b0 = v0 | (v1 << Uint32(16)) b1 = v8 | (v9 << Uint32(16)) diff --git a/sparkinfer/attention/_shared/mla/io.py b/sparkinfer/attention/_shared/mla/io.py index 2ca2f6682..2e9dbc4f7 100644 --- a/sparkinfer/attention/_shared/mla/io.py +++ b/sparkinfer/attention/_shared/mla/io.py @@ -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``: @@ -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. --- diff --git a/sparkinfer/attention/_shared/mla/io_mg.py b/sparkinfer/attention/_shared/mla/io_mg.py index 94f7992c4..c5b558a8b 100644 --- a/sparkinfer/attention/_shared/mla/io_mg.py +++ b/sparkinfer/attention/_shared/mla/io_mg.py @@ -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. @@ -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) diff --git a/sparkinfer/attention/_shared/mla/kernel.py b/sparkinfer/attention/_shared/mla/kernel.py index 93f34661f..0568a3cd6 100644 --- a/sparkinfer/attention/_shared/mla/kernel.py +++ b/sparkinfer/attention/_shared/mla/kernel.py @@ -700,7 +700,7 @@ def kernel( q_fp8_addr = shared_ptr_to_u32(st.q_fp8.data_ptr()) q_rope_addr = shared_ptr_to_u32(st.q_rope.data_ptr()) kv_fp8_addr = shared_ptr_to_u32(st.kv_fp8.data_ptr()) - if cutlass.const_expr(t.has_extra_cache): + if cutlass.const_expr(t.has_extra_cache or t.latent_scale_per_token): kv_sc_addr = shared_ptr_to_u32(st.kv_sc.data_ptr()) else: kv_sc_addr = Int32(0) @@ -816,6 +816,7 @@ def kernel( fp8_rope=t.fp8_rope, packed_glm=self.native_glm_h8, packed_dsv4=self.native_dsv4_h8, + per_token_latent_scale=t.latent_scale_per_token, ) prod_idx += Int32(1) if prod_idx == Int32(n_buf): @@ -1067,6 +1068,7 @@ def kernel( kv_smem_stride=t.kv_smem_stride, scale_bytes_per_token=8, scale_format=t.scale_format, + latent_scale_per_token=t.latent_scale_per_token, ) qk = s2_qk_rope_bf16( qk, @@ -1156,6 +1158,7 @@ def kernel( barrier_id=3, sm_p_full_addr=sm_p_full_addr, sm_p_stride=L.sm_p_full_stride, + latent_scale_per_token=t.latent_scale_per_token, ) # S6b (XV-RoPE) is DSV4-only (V_HAS_ROPE). const_expr-elided for GLM. @@ -1514,7 +1517,7 @@ def _kernel_body( q_fp8_addr = shared_ptr_to_u32(st.q_fp8.data_ptr()) q_rope_addr = shared_ptr_to_u32(st.q_rope.data_ptr()) kv_fp8_addr = shared_ptr_to_u32(st.kv_fp8.data_ptr()) - if cutlass.const_expr(t.has_extra_cache): + if cutlass.const_expr(t.has_extra_cache or t.latent_scale_per_token): kv_sc_addr = shared_ptr_to_u32(st.kv_sc.data_ptr()) else: kv_sc_addr = Int32(0) @@ -1655,6 +1658,7 @@ def _kernel_body( packed_glm=self.native_glm_h8, packed_dsv4=self.native_dsv4_h8 or self.native_dsv4_h16, overlap_footer_gather=self.native_dsv4_h16, + per_token_latent_scale=t.latent_scale_per_token, ) # Per-chunk section dispatch (DSV4 dual-cache; FlashInfer # decode_dsv4 :243-322). chunks [0, num_main_chunks) gather from the @@ -2035,6 +2039,7 @@ def _kernel_body( kv_smem_stride=t.kv_smem_stride, scale_bytes_per_token=8, scale_format=t.scale_format, + latent_scale_per_token=t.latent_scale_per_token, ) qk = s2_qk_rope_bf16( qk, @@ -2151,6 +2156,7 @@ def _kernel_body( barrier_id=3, sm_p_full_addr=sm_p_full_addr, sm_p_stride=L.sm_p_full_stride, + latent_scale_per_token=t.latent_scale_per_token, ) # S6b (XV-RoPE) is DSV4-only (V_HAS_ROPE). const_expr-elided for GLM. @@ -2374,6 +2380,7 @@ def _sparse_mla_decode_grid_flat_launch( head_block_offset: int, has_extra: bool, per_token_len: bool, + latent_scale_per_token: bool = False, ) -> None: q_head_dim = int(q_all.shape[-1]) rows = int(q_all.shape[0]) @@ -2408,6 +2415,7 @@ def _sparse_mla_decode_grid_flat_launch( int(compute_mode), int(scale_format), fp8_rope=bool(fp8_rope), + latent_scale_per_token=bool(latent_scale_per_token), ) if native_h8: # Four warps cover 4*16 candidates in swapped QK. PV keeps the same @@ -2509,6 +2517,7 @@ def _sparse_mla_decode_grid_flat_launch( key_field("compute_mode", traits.compute_mode), key_field("scale_format", traits.scale_format), key_field("fp8_rope", int(traits.fp8_rope)), + key_field("latent_scale_per_token", int(traits.latent_scale_per_token)), key_field("num_heads", heads), key_field("hpb", hpb), key_field("valid_hpb", int(valid_hpb)), @@ -2584,8 +2593,14 @@ def _sparse_mla_decode_grid_flat_launch( # v18: latent_scale == 1.0 is folded out at trace time, producing a # cubin without the outer-scale multiply; the identity and dynamic # variants must not share a cache entry. - 18, - key_field("latent_scale_identity", int(float(latent_scale) == 1.0)), + # v19: latent_scale_per_token joins the key (per-candidate fp32 scale + # read from kv_sc smem). In that mode the launch scalar is dead, so the + # identity fold is forced ON -- no per-scalar variants get compiled. + 19, + key_field( + "latent_scale_identity", + int(float(latent_scale) == 1.0 or bool(latent_scale_per_token)), + ), *spec_fields, ) if per_token_len: @@ -2634,6 +2649,7 @@ def _sparse_mla_decode_grid_op( head_block_offset: int, has_extra: bool, per_token_len: bool, + latent_scale_per_token: bool = False, ) -> None: _sparse_mla_decode_grid_flat_launch( q_all, @@ -2665,6 +2681,7 @@ def _sparse_mla_decode_grid_op( head_block_offset, has_extra, per_token_len, + latent_scale_per_token, ) @@ -2699,6 +2716,7 @@ def _sparse_mla_decode_grid_fake( head_block_offset: int, has_extra: bool, per_token_len: bool, + latent_scale_per_token: bool = False, ) -> None: return None @@ -2725,6 +2743,7 @@ def run_unified_decode( out: torch.Tensor | None = None, scale_format_override: int | None = None, fp8_rope_override: bool | None = None, + latent_scale_per_token: bool = False, ): """Active SM120 sparse-MLA decode: kernel (split-K partials) + merge. @@ -2839,11 +2858,25 @@ def run_unified_decode( f"NVFP4 cache record must be 368 or 432 bytes, got {record_bytes}" ) fp8_rope_override = record_bytes == 368 + # 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 scale_format != ScaleFormat.NVFP4_E4M3: + raise ValueError( + "SM120 sparse MLA decode latent_scale_per_token requires " + f"ScaleFormat.NVFP4_E4M3; got scale_format={int(scale_format)}" + ) + if not bool(fp8_rope_override): + raise ValueError( + "SM120 sparse MLA decode latent_scale_per_token requires the " + "fp8-rope 368-byte NVFP4 record; got the 432-byte record" + ) traits = make_unified_traits( model_type, compute_mode, scale_format, fp8_rope=fp8_rope_override, + latent_scale_per_token=bool(latent_scale_per_token), ) if scale_format == ScaleFormat.NVFP4_E4M3 and int(swa_k_cache.shape[-1]) != int( traits.kv_gmem_stride @@ -3140,6 +3173,7 @@ def _launch_grid(grid_h_blocks: int, valid_hpb: int, head_block_offset: int): int(head_block_offset), bool(has_extra), bool(per_token_len), + bool(latent_scale_per_token), ) if h_blocks_full > 0: diff --git a/sparkinfer/attention/_shared/mla/kv_cache.py b/sparkinfer/attention/_shared/mla/kv_cache.py index 243672a18..b57cc1769 100644 --- a/sparkinfer/attention/_shared/mla/kv_cache.py +++ b/sparkinfer/attention/_shared/mla/kv_cache.py @@ -30,6 +30,24 @@ ``cvt.rn.satfinite.e4m3x2(v / scale)`` bytes at [304, 368); the readers reconstruct ``e4m3_decode(byte) * scale`` (``prefill_mg._ld_global_nvfp4_fp8_rope_bfloat2``). + +``per_token_scale=True`` selects the self-describing two-level variant: the +NoPE lane derives its own per-token second-level scale instead of assuming +the implicit global 1.0 (which parks small-magnitude tokens' group scales in +E4M3 subnormals -- the defect the static per-layer +``VLLM_NVFP4_MLA_SCALES_FILE`` calibration papers over). Warp 0 reduces the +32 group amaxes to the token amax (butterfly shuffle), stores + + s_t = token_amax / (6.0 * 448.0) + +as fp32 at [292, 296) (the first 4 bytes of the pad; [296, 304) stays zero), +and every group scale byte is encoded relative to ``s_t`` so the largest +group's E4M3 scale lands at the top of the E4M3 range by construction. The +readers reconstruct ``e2m1 * e4m3_decode(scale_byte) * s_t`` -- the same +expression as the static path with ``latent_scale := s_t`` sourced from the +record instead of the launch. The record width, RoPE lane, and all offsets +are unchanged; legacy records (zero at [292, 296)) are NOT readable in this +mode, so the mode is server-static and joins the kernel compile identity. """ from __future__ import annotations @@ -84,6 +102,12 @@ # E4M3 rope scale: exact compile-time f32 constant (double 1/448 rounded to # f32 once), NOT a runtime rcp.approx -- torch references must mirror this. _E4M3_MAX_RCP = 1.0 / 448.0 +# Per-token second-level (NVFP4 two-level) scale: fp32 at [292, 296), value +# token_amax / (E2M1_MAX * E4M3_MAX). Same exact-constant contract as +# _E4M3_MAX_RCP -- torch references must mirror this. +_LATENT_SCALE_OFFSET = _PAD_OFFSET # 292 +_LATENT_SCALE_BYTES = 4 +_TWO_LEVEL_RCP = 1.0 / (6.0 * 448.0) @dsl_user_op @@ -142,9 +166,10 @@ class ConcatAndCacheNvfp4MlaFp8RopeKernel: 32 quantizes the RoPE lane to E4M3 with one fp32 per-token scale. """ - def __init__(self, block_size: int, is_bf16: bool): + def __init__(self, block_size: int, is_bf16: bool, per_token_scale: bool = False): self.block_size = int(block_size) self.is_bf16 = bool(is_bf16) + self.per_token_scale = bool(per_token_scale) @cute.jit def __call__( @@ -223,31 +248,83 @@ def kernel( vals[2 * i] = f0 vals[2 * i + 1] = f1 - # NVFP4 block quant at global scale 1.0: scale byte = - # e4m3(amax/6); values scaled by rcp.approx.ftz of the - # hardware-exact decode of that byte (what the reader - # multiplies back), then satfinite E2M1. group_amax = max_abs_16(vals) - scale_f32 = group_amax * rcp_approx_ftz(Float32(6.0)) - scale_u32 = cvt_f32_to_e4m3(scale_f32) - decoded_scale = cvt_e4m3_to_f32_via_f16(scale_u32) - packed64 = Uint64(0) - if decoded_scale != Float32(0.0): - packed64 = quantize_and_pack_16_fast( - vals, rcp_approx_ftz(decoded_scale) + if cutlass.const_expr(self.per_token_scale): + # Two-level NVFP4: warp-reduce the 32 group amaxes to the + # token amax (threads 0-31 are exactly warp 0), derive + # s_t = token_amax/(6*448) so the largest group's E4M3 + # scale byte encodes 448 (top of range, no subnormals), + # and quantize every group relative to s_t. Lane 0 + # stores s_t fp32 at [292, 296) for the readers. + token_amax = group_amax + tmp = cute.arch.shuffle_sync_bfly(token_amax, offset=1) + token_amax = fmax_f32(token_amax, tmp) + tmp = cute.arch.shuffle_sync_bfly(token_amax, offset=2) + token_amax = fmax_f32(token_amax, tmp) + tmp = cute.arch.shuffle_sync_bfly(token_amax, offset=4) + token_amax = fmax_f32(token_amax, tmp) + tmp = cute.arch.shuffle_sync_bfly(token_amax, offset=8) + token_amax = fmax_f32(token_amax, tmp) + tmp = cute.arch.shuffle_sync_bfly(token_amax, offset=16) + token_amax = fmax_f32(token_amax, tmp) + latent_scale = token_amax * Float32(_TWO_LEVEL_RCP) + if tid == Int32(0): + st_global_f32( + dst + Int64(_LATENT_SCALE_OFFSET), latent_scale + ) + scale_u32 = Uint32(0) + packed64 = Uint64(0) + if latent_scale != Float32(0.0): + inv_latent = rcp_approx_ftz(latent_scale) + scale_f32 = (group_amax * inv_latent) * rcp_approx_ftz( + Float32(6.0) + ) + scale_u32 = cvt_f32_to_e4m3(scale_f32) + decoded_scale = cvt_e4m3_to_f32_via_f16(scale_u32) + if decoded_scale != Float32(0.0): + packed64 = quantize_and_pack_16_fast( + vals, rcp_approx_ftz(decoded_scale) * inv_latent + ) + st_global_u64(dst + (tid * Int32(8)).to(Int64), packed64) + st_global_u8( + dst + Int64(_NOPE_BYTES) + tid.to(Int64), + cutlass.Uint8(scale_u32 & Uint32(0xFF)), + ) + else: + # NVFP4 block quant at global scale 1.0: scale byte = + # e4m3(amax/6); values scaled by rcp.approx.ftz of the + # hardware-exact decode of that byte (what the reader + # multiplies back), then satfinite E2M1. + scale_f32 = group_amax * rcp_approx_ftz(Float32(6.0)) + scale_u32 = cvt_f32_to_e4m3(scale_f32) + decoded_scale = cvt_e4m3_to_f32_via_f16(scale_u32) + packed64 = Uint64(0) + if decoded_scale != Float32(0.0): + packed64 = quantize_and_pack_16_fast( + vals, rcp_approx_ftz(decoded_scale) + ) + st_global_u64(dst + (tid * Int32(8)).to(Int64), packed64) + st_global_u8( + dst + Int64(_NOPE_BYTES) + tid.to(Int64), + cutlass.Uint8(scale_u32 & Uint32(0xFF)), + ) + + # --- Zero pad: [292, 304) in static mode; [296, 304) when the + # per-token latent scale occupies [292, 296). + if cutlass.const_expr(self.per_token_scale): + if tid < Int32(_PAD_BYTES - _LATENT_SCALE_BYTES): + st_global_u8( + dst + + Int64(_PAD_OFFSET + _LATENT_SCALE_BYTES) + + tid.to(Int64), + cutlass.Uint8(0), + ) + else: + if tid < Int32(_PAD_BYTES): + st_global_u8( + dst + Int64(_PAD_OFFSET) + tid.to(Int64), + cutlass.Uint8(0), ) - st_global_u64(dst + (tid * Int32(8)).to(Int64), packed64) - st_global_u8( - dst + Int64(_NOPE_BYTES) + tid.to(Int64), - cutlass.Uint8(scale_u32 & Uint32(0xFF)), - ) - - # --- Zero pad [292, 304). - if tid < Int32(_PAD_BYTES): - st_global_u8( - dst + Int64(_PAD_OFFSET) + tid.to(Int64), - cutlass.Uint8(0), - ) # --- RoPE lane: amax -> fp32 scale at [288, 292) -> satfinite # E4M3 bytes at [304, 368). @@ -290,9 +367,9 @@ def kernel( @lru_cache(maxsize=None) def _build_concat_and_cache_nvfp4_mla_fp8_rope_kernel( - block_size: int, is_bf16: bool + block_size: int, is_bf16: bool, per_token_scale: bool = False ) -> ConcatAndCacheNvfp4MlaFp8RopeKernel: - return ConcatAndCacheNvfp4MlaFp8RopeKernel(block_size, is_bf16) + return ConcatAndCacheNvfp4MlaFp8RopeKernel(block_size, is_bf16, per_token_scale) def clear_nvfp4_mla_fp8_rope_kv_cache_kernel_cache() -> None: @@ -327,6 +404,7 @@ def _concat_and_cache_nvfp4_mla_fp8_rope_flat_launch( k_pe: torch.Tensor, kv_cache: torch.Tensor, slot_mapping: torch.Tensor, + per_token_scale: bool = False, ) -> None: num_tokens = int(slot_mapping.shape[0]) if num_tokens == 0: @@ -334,7 +412,9 @@ def _concat_and_cache_nvfp4_mla_fp8_rope_flat_launch( block_size = int(kv_cache.shape[1]) slot_capacity = int(kv_cache.shape[0]) * block_size is_bf16 = kv_c.dtype == torch.bfloat16 - kernel = _build_concat_and_cache_nvfp4_mla_fp8_rope_kernel(block_size, is_bf16) + kernel = _build_concat_and_cache_nvfp4_mla_fp8_rope_kernel( + block_size, is_bf16, per_token_scale + ) args = ( _to_kernel_tensor(kv_c, assumed_align=4, leading_dim=1), @@ -361,10 +441,13 @@ def _concat_and_cache_nvfp4_mla_fp8_rope_flat_launch( tensor_compile_fact("slot_mapping", slot_mapping, dynamic_dims=(0,)), str(kv_c.dtype), block_size, + bool(per_token_scale), ) + # Version 3: per_token_scale joined the record semantics (fp32 second-level + # scale at [292, 296)); a v2 cubin must never run against v3 records. spec = KernelCompileSpec.from_key( "attention.mla.nvfp4_fp8_rope_kv_cache", - 2, + 3, cache_key, labels=( "kv_c", @@ -373,6 +456,7 @@ def _concat_and_cache_nvfp4_mla_fp8_rope_flat_launch( "slot_mapping", "kv_dtype", "block_size", + "per_token_scale", ), ) sparkinfer_launch( @@ -392,8 +476,11 @@ def _concat_and_cache_nvfp4_mla_fp8_rope_op( k_pe: torch.Tensor, kv_cache: torch.Tensor, slot_mapping: torch.Tensor, + per_token_scale: bool = False, ) -> None: - _concat_and_cache_nvfp4_mla_fp8_rope_flat_launch(kv_c, k_pe, kv_cache, slot_mapping) + _concat_and_cache_nvfp4_mla_fp8_rope_flat_launch( + kv_c, k_pe, kv_cache, slot_mapping, per_token_scale + ) @_concat_and_cache_nvfp4_mla_fp8_rope_op.register_fake @@ -402,6 +489,7 @@ def _concat_and_cache_nvfp4_mla_fp8_rope_fake( k_pe: torch.Tensor, kv_cache: torch.Tensor, slot_mapping: torch.Tensor, + per_token_scale: bool = False, ) -> None: return None @@ -412,6 +500,7 @@ def concat_and_cache_nvfp4_mla_fp8_rope( kv_cache: torch.Tensor, slot_mapping: torch.Tensor, scale: torch.Tensor | None = None, + per_token_scale: bool = False, ) -> None: """Write ``num_tokens`` KV_FP8_ROPE=1 nvfp4_ds_mla records. @@ -424,6 +513,10 @@ def concat_and_cache_nvfp4_mla_fp8_rope( :param scale: accepted for signature parity with the fp8 cache-op family; the nvfp4_ds_mla record has an implicit global scale of 1.0 (group scales carry all magnitude), so it is unused. + :param per_token_scale: write self-describing two-level records: the + per-token second-level scale ``token_amax/(6*448)`` is stored fp32 at + record bytes [292, 296) and group scales are encoded relative to it. + Readers must run in the matching ``latent_scale_per_token`` mode. """ del scale if kv_c.ndim != 2 or int(kv_c.shape[1]) != _KV_LORA_RANK: @@ -485,5 +578,5 @@ def concat_and_cache_nvfp4_mla_fp8_rope( raise ValueError("all tensors must be on the same device") torch.ops.sparkinfer.concat_and_cache_nvfp4_mla_fp8_rope( - kv_c, k_pe, kv_cache, slot_mapping + kv_c, k_pe, kv_cache, slot_mapping, per_token_scale ) diff --git a/sparkinfer/attention/_shared/mla/prefill.py b/sparkinfer/attention/_shared/mla/prefill.py index 98d6750b3..b5f396fc1 100644 --- a/sparkinfer/attention/_shared/mla/prefill.py +++ b/sparkinfer/attention/_shared/mla/prefill.py @@ -118,6 +118,7 @@ def run_unified_prefill( scale_format: int | None = None, latent_scale: float = 1.0, fp8_rope: bool | None = None, + latent_scale_per_token: bool = False, ): """Unified SM120 sparse-MLA single-pass prefill -> BF16 O + base-2 LSE. @@ -195,8 +196,20 @@ def run_unified_prefill( f"q_head_dim={q_head_dim}, inferred={int(inferred_scale_format)}, " f"override={int(scale_format)}" ) + # FAIL-CLOSED: the per-token fp32 latent scale lives at bytes [292, 296) of + # the NVFP4 fp8-rope 368-byte record ONLY (fp8_rope agreement is enforced + # by make_unified_traits and the MG record-width validation). + if latent_scale_per_token and scale_format != ScaleFormat.NVFP4_E4M3: + raise ValueError( + "SM120 sparse MLA prefill latent_scale_per_token requires " + f"ScaleFormat.NVFP4_E4M3; got scale_format={int(scale_format)}" + ) traits = make_unified_traits( - model_type, compute_mode, scale_format, fp8_rope=fp8_rope + model_type, + compute_mode, + scale_format, + fp8_rope=fp8_rope, + latent_scale_per_token=bool(latent_scale_per_token), ) d_v = int(traits.d_v) @@ -284,6 +297,7 @@ def _run_partitioned_mg( model_type=model_type, scale_format=scale_format, fp8_rope=bool(traits.fp8_rope), + latent_scale_per_token=bool(latent_scale_per_token), ) if extra_kv_cache is not None: kwargs.update( diff --git a/sparkinfer/attention/_shared/mla/prefill_mg.py b/sparkinfer/attention/_shared/mla/prefill_mg.py index dfce49c01..ea0f89873 100644 --- a/sparkinfer/attention/_shared/mla/prefill_mg.py +++ b/sparkinfer/attention/_shared/mla/prefill_mg.py @@ -816,8 +816,15 @@ def _nvfp4_pair_bfloat2_mg( 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, or -- + ``latent_scale_per_token`` -- the record's own fp32 second-level scale + ([292, 296)), staged per candidate into kv_sc by the MG IO gather. + """ data_byte = _ld_u8_zext( kv_fp4_base_addr, entry * Int32(kv_smem_stride) + (dim_even // Int32(2)), @@ -830,11 +837,15 @@ def _nvfp4_pair_bfloat2_mg( entry * Int32(kv_smem_stride) + Int32(_NVFP4_SCALE_OFFSET) + scale_group, ) scale_f = cvt_e4m3_to_f32_via_f16(scale_byte) - # Prefill QK has its own MG B-operand loader. Restore s_l here, before - # BF16 packing/MMA, to match decode QK and the shared decode P.V helper. + outer = latent_scale + if cutlass.const_expr(latent_scale_per_token): + outer = ld_shared_f32(kv_sc_base_addr + entry * Int32(4)) + # Prefill QK has its own MG B-operand loader. Restore the outer scale + # here, before BF16 packing/MMA, to match decode QK and the shared decode + # P.V helper. return pack_f32x2_to_bfloat2( - (v0 * scale_f) * latent_scale, - (v1 * scale_f) * latent_scale, + (v0 * scale_f) * outer, + (v1 * scale_f) * outer, ) @@ -854,17 +865,24 @@ def s1_qk_nope_nvfp4_bf16_mg2( q_nope_bf16_stride: cutlass.Constexpr, kv_smem_stride: cutlass.Constexpr, n_hg: cutlass.Constexpr = 2, + latent_scale_per_token: cutlass.Constexpr = False, + kv_sc_base_addr: Int32 = Int32(0), ): """S1 (NVFP4): MG BF16 QK-NoPE with native E2M1/E4M3 in-register dequant. Same MMA packing as ``s1_qk_nope_bf16_mg2`` but the K/B operand comes from the packed 288-byte NVFP4 row (256B E2M1 + 32B E4M3 group-16 scales); the - same math path as the validated NVFP4 decode ``s1_qk_nope_nvfp4_bf16``.""" + same math path as the validated NVFP4 decode ``s1_qk_nope_nvfp4_bf16``. + + ``latent_scale_per_token``: this lane's candidate row is fixed, so its + record scale is hoisted once from kv_sc.""" 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): @@ -2347,9 +2365,11 @@ def _body( kv_fp8_addr = shared_ptr_to_u32(st.kv_fp8.data_ptr()) reduce_addr = shared_ptr_to_u32(st.reduce.data_ptr()) w_fp8_addr = shared_ptr_to_u32(st.w_fp8.data_ptr()) - # GLM has no kv_sc footer (its fp32 scales are inline). DSV4 stages - # XV-RoPE weights into the W_FP8 region after XV-NoPE consumes it. - if cutlass.const_expr(is_glm): + # GLM has no kv_sc footer (its fp32 scales are inline), EXCEPT the + # NVFP4 per-token latent-scale mode, which stages one fp32 per + # candidate. DSV4 stages XV-RoPE weights into the W_FP8 region after + # XV-NoPE consumes it. + if cutlass.const_expr(is_glm and not t.latent_scale_per_token): kv_sc_addr = Int32(0) else: kv_sc_addr = shared_ptr_to_u32(st.kv_sc.data_ptr()) @@ -2520,6 +2540,8 @@ def _body( io_threads=_PREFILL_IO_THREADS, scale_format=t.scale_format, fp8_rope=t.fp8_rope, + per_token_latent_scale=t.latent_scale_per_token, + kv_sc_dst_addr=kv_sc_addr, ) else: io_issue_gather_dsv4_nope( @@ -2618,6 +2640,8 @@ def _body( io_threads=_PREFILL_IO_THREADS, scale_format=t.scale_format, fp8_rope=t.fp8_rope, + per_token_latent_scale=t.latent_scale_per_token, + kv_sc_dst_addr=kv_sc_addr + buf * kv_sc_buf, ) else: io_issue_gather_dsv4_nope( @@ -2914,6 +2938,8 @@ def _body( q_nope_bf16_stride=L.q_nope_bf16_stride, kv_smem_stride=L.kv_smem_stride, n_hg=n_hg, + latent_scale_per_token=t.latent_scale_per_token, + kv_sc_base_addr=kv_sc_b, ) qk0, qk1 = s2_qk_rope_regs_mg_glm( qk0, @@ -3226,6 +3252,7 @@ def _body( barrier_id=3, sm_p_full_addr=sm_p_g0, sm_p_stride=L.sm_p_full_stride, + latent_scale_per_token=t.latent_scale_per_token, ) if cutlass.const_expr(n_hg == 2): acc1 = s6_xv_nope( @@ -3253,6 +3280,7 @@ def _body( barrier_id=3, sm_p_full_addr=sm_p_g1, sm_p_stride=L.sm_p_full_stride, + latent_scale_per_token=t.latent_scale_per_token, ) elif cutlass.const_expr(is_glm): # GLM XV-NoPE: the per-group decode s6_xv_nope (raw-e4m3 V + @@ -3680,9 +3708,14 @@ def _sparse_mla_prefill_mg_flat_launch( *, active_heads: int | None = None, head_offset: int = 0, + latent_scale_per_token: bool = False, ) -> None: traits = make_unified_traits( - int(model_type), compute_mode, int(scale_format), fp8_rope=bool(fp8_rope) + int(model_type), + compute_mode, + int(scale_format), + fp8_rope=bool(fp8_rope), + latent_scale_per_token=bool(latent_scale_per_token), ) layout = make_smem_layout_mg(traits, int(mg_n_hg)) q_head_dim = int(q.shape[2]) @@ -3783,6 +3816,7 @@ def _sparse_mla_prefill_mg_flat_launch( key_field("compute_mode", int(compute_mode)), key_field("scale_format", int(scale_format)), key_field("fp8_rope", int(traits.fp8_rope)), + key_field("latent_scale_per_token", int(traits.latent_scale_per_token)), key_field("num_heads", total_heads), key_field("heads_per_cta", heads_per_cta), key_field("mg_n_hg", int(mg_n_hg)), @@ -3843,8 +3877,14 @@ def _sparse_mla_prefill_mg_flat_launch( # v4: latent_scale == 1.0 is folded out at trace time, producing a # cubin without the outer-scale multiply; the identity and dynamic # variants must not share a cache entry. - 4, - key_field("latent_scale_identity", int(float(latent_scale) == 1.0)), + # v5: latent_scale_per_token joins the key (per-candidate fp32 scale + # read from kv_sc smem). In that mode the launch scalar is dead, so the + # identity fold is forced ON -- no per-scalar variants get compiled. + 5, + key_field( + "latent_scale_identity", + int(float(latent_scale) == 1.0 or bool(latent_scale_per_token)), + ), *spec_fields, ) entry = kernel.call_dual if has_extra else kernel @@ -3875,6 +3915,7 @@ def _sparse_mla_prefill_mg_op( model_type: int, scale_format: int, fp8_rope: bool, + latent_scale_per_token: bool = False, ) -> None: # SINGLE-CACHE op (DSV4 main / DSV4-BF16 / GLM MG). It carries the new # latent_scale runtime scalar and passes has_extra=False with extra device @@ -3908,6 +3949,7 @@ def _sparse_mla_prefill_mg_op( 1, # pbs_extra 0, # stride_extra_kv_block False, # row_xor + latent_scale_per_token=latent_scale_per_token, ) @@ -3932,6 +3974,7 @@ def _sparse_mla_prefill_mg_fake( model_type: int, scale_format: int, fp8_rope: bool, + latent_scale_per_token: bool = False, ) -> None: return None @@ -4053,6 +4096,7 @@ def run_unified_prefill_mg( scale_format: int | None = None, latent_scale: float = 1.0, fp8_rope: bool | None = None, + latent_scale_per_token: bool = False, extra_kv_cache: torch.Tensor | None = None, extra_indices: torch.Tensor | None = None, extra_topk_length: torch.Tensor | None = None, @@ -4120,8 +4164,25 @@ def run_unified_prefill_mg( "NVFP4 sparse MLA MG cache record disagrees with fp8_rope: " f"got {record_bytes} bytes, expected {expected_record_bytes}" ) + # 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 scale_format != ScaleFormat.NVFP4_E4M3: + raise ValueError( + "SM120 sparse MLA MG prefill latent_scale_per_token requires " + f"ScaleFormat.NVFP4_E4M3; got scale_format={int(scale_format)}" + ) + if not bool(fp8_rope): + raise ValueError( + "SM120 sparse MLA MG prefill latent_scale_per_token requires " + "the fp8-rope 368-byte NVFP4 record; got the 432-byte record" + ) traits = make_unified_traits( - model_type, int(compute_mode), scale_format, fp8_rope=fp8_rope + model_type, + int(compute_mode), + scale_format, + fp8_rope=fp8_rope, + latent_scale_per_token=bool(latent_scale_per_token), ) # heads_per_cta = mg_n_hg * HPB. mg_n_hg==2 covers paired head groups; mg_n_hg==1 # covers a single-group launch, including 16-head tails and the heads==8 @@ -4280,6 +4341,7 @@ def run_unified_prefill_mg( model_type, scale_format, bool(traits.fp8_rope), + bool(latent_scale_per_token), ) else: _sparse_mla_prefill_mg_flat_launch( @@ -4313,5 +4375,6 @@ def run_unified_prefill_mg( False, # row_xor active_heads=active_heads, head_offset=head_offset, + latent_scale_per_token=bool(latent_scale_per_token), ) return output, lse_out diff --git a/sparkinfer/attention/_shared/mla/smem.py b/sparkinfer/attention/_shared/mla/smem.py index 90bc52b58..5539ba9ab 100644 --- a/sparkinfer/attention/_shared/mla/smem.py +++ b/sparkinfer/attention/_shared/mla/smem.py @@ -244,6 +244,13 @@ def make_smem_layout(traits: UnifiedMLATraits) -> SmemLayout: kv_sc_stride = 8 # SCALE_BYTES_PER_TOKEN kv_sc_buf_bytes = bi * kv_sc_stride off = kv_sc_off + kv_sc_buf_bytes * bufs + elif traits.latent_scale_per_token: + # NVFP4 per-token mode: one fp32 second-level latent scale per + # candidate ([292, 296) of the 368B record), scalar-gathered like the + # DSV4 footer into a double-buffered BI x 4 region. + kv_sc_stride = 4 + kv_sc_buf_bytes = bi * kv_sc_stride + off = kv_sc_off + kv_sc_buf_bytes * bufs else: # GLM: scales are INLINE in the kv_fp8 KV_SMEM_STRIDE row (no footer buf). kv_sc_stride = 0 @@ -386,7 +393,7 @@ class SharedStorage: int(layout.kv_sc_buf_bytes * layout.kv_bufs), ] } - if traits.has_extra_cache + if (traits.has_extra_cache or traits.latent_scale_per_token) else {} ) w_head_sc2_field = ( @@ -472,8 +479,9 @@ class SharedStorage: "token_idx": layout.token_idx_off, "sm_p_full": layout.sm_p_full_off, } - if traits.has_extra_cache: + if traits.has_extra_cache or traits.latent_scale_per_token: expected_offsets["kv_sc"] = layout.kv_sc_off + if traits.has_extra_cache: expected_offsets["w_head_sc2"] = layout.w_head_sc2_off actual_offsets = dict(storage_cls._offsets) if actual_offsets != expected_offsets: diff --git a/sparkinfer/attention/_shared/mla/smem_mg.py b/sparkinfer/attention/_shared/mla/smem_mg.py index 2e0ad35b1..c045d4cb1 100644 --- a/sparkinfer/attention/_shared/mla/smem_mg.py +++ b/sparkinfer/attention/_shared/mla/smem_mg.py @@ -200,9 +200,17 @@ def make_smem_layout_mg( kv_sc_off = off if is_glm: - # GLM: scales are INLINE in the kv_fp8 KV_SMEM_STRIDE row (no footer buf). - kv_sc_stride = 0 - kv_sc_buf_bytes = 0 + if traits.latent_scale_per_token: + # NVFP4 per-token mode: one fp32 second-level latent scale per + # candidate ([292, 296) of the 368B record), scalar-gathered like + # the DSV4 footer into a double-buffered BI x 4 region. + kv_sc_stride = 4 + kv_sc_buf_bytes = bi * kv_sc_stride + off = kv_sc_off + kv_sc_buf_bytes * bufs + else: + # GLM: scales are INLINE in the kv_fp8 row (no footer buf). + kv_sc_stride = 0 + kv_sc_buf_bytes = 0 else: kv_sc_stride = 8 kv_sc_buf_bytes = bi * kv_sc_stride @@ -339,7 +347,7 @@ class SharedStorageMG: # reads rope from global/L2, so it allocates NEITHER kv_sc nor kv_rope. Each # model is its own compiled specialization, so the GLM struct cannot perturb # the DSV4 struct. - if is_glm: + if is_glm and not traits.latent_scale_per_token: kv_scale_field = {} else: kv_scale_field = { @@ -417,7 +425,7 @@ class SharedStorageMG: "q_sc": layout.q_sc_off, } expected_offsets["kv_fp8"] = layout.kv_fp8_off - if not is_glm: + if not is_glm or traits.latent_scale_per_token: expected_offsets["kv_sc"] = layout.kv_sc_off expected_offsets.update( { diff --git a/sparkinfer/attention/_shared/mla/traits.py b/sparkinfer/attention/_shared/mla/traits.py index 413fc8120..bd395e066 100644 --- a/sparkinfer/attention/_shared/mla/traits.py +++ b/sparkinfer/attention/_shared/mla/traits.py @@ -77,6 +77,10 @@ class UnifiedMLATraits: rope_gmem_offset: int rope_payload_bytes: int rope_scale_offset: int + # NVFP4-only per-token second-level fp32 latent scale (record bytes + # [292, 296) of the 368-byte fp8-rope record). False keeps every existing + # specialization (and its smem layout / PTX) byte-identical. + latent_scale_per_token: bool = False def make_unified_traits( @@ -84,6 +88,7 @@ def make_unified_traits( compute_mode: int, scale_format: int, fp8_rope: bool | None = None, + latent_scale_per_token: bool = False, ) -> UnifiedMLATraits: """Build the trait bundle for one specialization tuple. @@ -102,6 +107,15 @@ def make_unified_traits( if compute_mode not in (ComputeMode.FP8, ComputeMode.BF16): raise ValueError(f"unsupported compute_mode {compute_mode!r}") + # FAIL-CLOSED: the per-token fp32 latent scale lives at bytes [292, 296) of + # the NVFP4 368-byte fp8-rope record ONLY. Any other (model, scale, rope) + # tuple has no such field, so the mode must never silently build there. + if latent_scale_per_token and scale_format != ScaleFormat.NVFP4_E4M3: + raise ValueError( + "latent_scale_per_token requires ScaleFormat.NVFP4_E4M3; " + f"got scale_format={scale_format!r}" + ) + if model_type == ModelType.DSV4: if scale_format != ScaleFormat.UE8M0_BYTE: raise ValueError( @@ -142,6 +156,11 @@ def make_unified_traits( # group-16 scales + 16B pad + 128B BF16 RoPE. Decode stages Q-NoPE # as BF16 and dequants FP4 K/V in-register for BF16 QK/PV MMAs. use_fp8_rope = fp8_rope_requested + if latent_scale_per_token and not use_fp8_rope: + raise ValueError( + "latent_scale_per_token requires the NVFP4 fp8-rope " + "368-byte record (fp8_rope=True); got the 432-byte record" + ) return UnifiedMLATraits( model_type=ModelType.GLM_NSA, compute_mode=ComputeMode.BF16, @@ -169,6 +188,7 @@ def make_unified_traits( rope_gmem_offset=304, rope_payload_bytes=64 if use_fp8_rope else 128, rope_scale_offset=288 if use_fp8_rope else -1, + latent_scale_per_token=bool(latent_scale_per_token), ) if scale_format != ScaleFormat.ARBITRARY_FP32: raise ValueError( diff --git a/tests/attention/test_mla_kv_cache_per_token_scale.py b/tests/attention/test_mla_kv_cache_per_token_scale.py new file mode 100644 index 000000000..214941832 --- /dev/null +++ b/tests/attention/test_mla_kv_cache_per_token_scale.py @@ -0,0 +1,224 @@ +"""Two-level (per-token second-level scale) nvfp4_ds_mla record tests. + +``per_token_scale=True`` stores ``s_t = token_amax/(6*448)`` as fp32 at record +bytes [292, 296) and encodes every group scale relative to it, so the largest +group's E4M3 scale byte lands at the top of the E4M3 range by construction. +These tests pin the record ABI, the positioning invariant that motivates the +mode (no E4M3-subnormal group scales for small-magnitude tokens), and the +accuracy win over the implicit-1.0 static writer at shallow-layer magnitudes. +""" + +from __future__ import annotations + +import pytest +import torch + +from sparkinfer.attention._shared.mla.kv_cache import ( + clear_nvfp4_mla_fp8_rope_kv_cache_kernel_cache, + concat_and_cache_nvfp4_mla_fp8_rope, +) + +from .._reference.helpers import E2M1_TO_FLOAT32 +from ..conftest import require_sparkinfer as require_sm120 + + +_RECORD_BYTES = 368 +_NOPE_BYTES = 256 +_GROUP_SCALES_OFFSET = 256 +_ROPE_SCALE_OFFSET = 288 +_LATENT_SCALE_OFFSET = 292 +_PAD_OFFSET = 296 +_ROPE_OFFSET = 304 +_PAGE_SIZE = 64 +_V_HEAD_DIM = 512 +_PE_DIM = 64 +# Exact-constant contract shared with the writer (kv_cache._TWO_LEVEL_RCP). +_TWO_LEVEL_RCP = torch.tensor(1.0 / (6.0 * 448.0), dtype=torch.float32) +# Smallest normal E4M3 value; group scales at or below this are subnormal. +_E4M3_MIN_NORMAL = 2.0**-6 + + +@pytest.fixture(scope="module", autouse=True) +def _isolate_writer_kernel_cache(): + clear_nvfp4_mla_fp8_rope_kv_cache_kernel_cache() + yield + clear_nvfp4_mla_fp8_rope_kv_cache_kernel_cache() + + +def _write_records( + kv_c: torch.Tensor, + k_pe: torch.Tensor, + *, + per_token_scale: bool, +) -> torch.Tensor: + num_tokens = kv_c.shape[0] + cache = torch.zeros( + (2, _PAGE_SIZE, _RECORD_BYTES), dtype=torch.uint8, device=kv_c.device + ) + slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=kv_c.device) + concat_and_cache_nvfp4_mla_fp8_rope( + kv_c, + k_pe, + cache, + slot_mapping, + per_token_scale=per_token_scale, + ) + return cache.reshape(-1, _RECORD_BYTES)[:num_tokens].cpu() + + +def _dequantize_two_level(records: torch.Tensor) -> torch.Tensor: + """Host reference: e2m1 * e4m3(group scale) * fp32 s_t at [292, 296).""" + packed = records[:, :_NOPE_BYTES] + codes = torch.stack((packed & 0xF, (packed >> 4) & 0xF), dim=-1).reshape( + records.shape[0], _V_HEAD_DIM + ) + e2m1 = torch.tensor(E2M1_TO_FLOAT32, dtype=torch.float32) + group_scales = ( + records[:, _GROUP_SCALES_OFFSET:_ROPE_SCALE_OFFSET] + .contiguous() + .view(torch.float8_e4m3fn) + .float() + ) + latent_scales = ( + records[:, _LATENT_SCALE_OFFSET:_PAD_OFFSET] + .contiguous() + .view(torch.float32) + .reshape(-1) + ) + return ( + e2m1[codes.long()].reshape(records.shape[0], 32, 16) + * group_scales.unsqueeze(-1) + ).reshape(records.shape[0], _V_HEAD_DIM) * latent_scales.unsqueeze(-1) + + +def _dequantize_static(records: torch.Tensor) -> torch.Tensor: + """Host reference for the implicit-1.0 static writer (no second level).""" + packed = records[:, :_NOPE_BYTES] + codes = torch.stack((packed & 0xF, (packed >> 4) & 0xF), dim=-1).reshape( + records.shape[0], _V_HEAD_DIM + ) + e2m1 = torch.tensor(E2M1_TO_FLOAT32, dtype=torch.float32) + group_scales = ( + records[:, _GROUP_SCALES_OFFSET:_ROPE_SCALE_OFFSET] + .contiguous() + .view(torch.float8_e4m3fn) + .float() + ) + return ( + e2m1[codes.long()].reshape(records.shape[0], 32, 16) + * group_scales.unsqueeze(-1) + ).reshape(records.shape[0], _V_HEAD_DIM) + + +def _layered_inputs( + device: torch.device, dtype: torch.dtype +) -> tuple[torch.Tensor, torch.Tensor]: + """Token magnitudes spanning the GLM-5.2 per-layer kv_c range (~240x). + + Token 0 mimics a shallow layer (max_abs ~0.02 -- the E4M3-subnormal + regime under the implicit-1.0 writer), the last a deep layer (~5.2). + """ + torch.manual_seed(0x145) + base = torch.randn((6, _V_HEAD_DIM), dtype=torch.float32) + base = base / base.abs().amax(dim=-1, keepdim=True) + mags = torch.tensor([0.02, 0.08, 0.35, 1.0, 2.6, 5.2]).unsqueeze(-1) + kv_c = (base * mags).to(device=device, dtype=dtype) + k_pe = torch.randn((6, _PE_DIM), dtype=torch.float32).to( + device=device, dtype=dtype + ) + return kv_c, k_pe + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16], ids=["bf16", "fp16"]) +@torch.inference_mode() +def test_per_token_records_store_exact_scale_and_keep_abi( + dtype: torch.dtype, +) -> None: + device = require_sm120() + kv_c, k_pe = _layered_inputs(device, dtype) + records = _write_records(kv_c, k_pe, per_token_scale=True) + static_records = _write_records(kv_c, k_pe, per_token_scale=False) + + # s_t == token_amax * f32(1/2688) bit-exactly (same exact-constant + # contract as the rope scale). + token_amax = kv_c.float().abs().amax(dim=-1).cpu() + expected = token_amax * _TWO_LEVEL_RCP + stored = ( + records[:, _LATENT_SCALE_OFFSET:_PAD_OFFSET] + .contiguous() + .view(torch.float32) + .reshape(-1) + ) + assert torch.equal(stored, expected) + + # Remaining pad stays zero; static mode keeps the full pad zero. + assert (records[:, _PAD_OFFSET:_ROPE_OFFSET] == 0).all() + assert (static_records[:, _LATENT_SCALE_OFFSET:_ROPE_OFFSET] == 0).all() + + # The RoPE lane (scale + payload) is mode-independent. + assert torch.equal( + records[:, _ROPE_SCALE_OFFSET:_LATENT_SCALE_OFFSET], + static_records[:, _ROPE_SCALE_OFFSET:_LATENT_SCALE_OFFSET], + ) + assert torch.equal( + records[:, _ROPE_OFFSET:], static_records[:, _ROPE_OFFSET:] + ) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16], ids=["bf16"]) +@torch.inference_mode() +def test_per_token_scale_positions_group_scales_out_of_subnormals( + dtype: torch.dtype, +) -> None: + device = require_sm120() + kv_c, k_pe = _layered_inputs(device, dtype) + records = _write_records(kv_c, k_pe, per_token_scale=True) + static_records = _write_records(kv_c, k_pe, per_token_scale=False) + + group_scales = ( + records[:, _GROUP_SCALES_OFFSET:_ROPE_SCALE_OFFSET] + .contiguous() + .view(torch.float8_e4m3fn) + .float() + ) + # Positioning invariant: every token's LARGEST group scale sits near the + # top of the E4M3 range (>= 256 given e4m3 rounding), never subnormal. + assert (group_scales.amax(dim=-1) >= 256.0).all() + + # The static writer's shallow-magnitude token (amax 0.02) demonstrates the + # defect this mode removes: its group scales are E4M3 subnormals. + static_scales = ( + static_records[:, _GROUP_SCALES_OFFSET:_ROPE_SCALE_OFFSET] + .contiguous() + .view(torch.float8_e4m3fn) + .float() + ) + assert (static_scales[0].amax() <= _E4M3_MIN_NORMAL) or ( + static_scales[0][static_scales[0] > 0].amin() < _E4M3_MIN_NORMAL + ) + + # Accuracy: two-level reconstruction must beat implicit-1.0 on the + # shallow tokens and never lose on the deep ones (small slack for + # rcp.approx in the pack path). + reference = kv_c.float().cpu() + err_dynamic = (_dequantize_two_level(records) - reference).abs().amax(dim=-1) + err_static = (_dequantize_static(static_records) - reference).abs().amax(dim=-1) + assert (err_dynamic[:2] < err_static[:2]).all() + assert (err_dynamic <= err_static * 1.05 + 1e-6).all() + + # Absolute bound: NVFP4 worst-case relative step at two-level positioning. + rel = err_dynamic / kv_c.float().abs().amax(dim=-1).cpu() + assert (rel < 0.25).all() + + +@torch.inference_mode() +def test_zero_token_writes_zero_scale_and_zero_payload() -> None: + device = require_sm120() + kv_c = torch.zeros((2, _V_HEAD_DIM), dtype=torch.bfloat16, device=device) + k_pe = torch.zeros((2, _PE_DIM), dtype=torch.bfloat16, device=device) + records = _write_records(kv_c, k_pe, per_token_scale=True) + assert (records[:, :_ROPE_SCALE_OFFSET] == 0).all() + assert (records[:, _LATENT_SCALE_OFFSET:_PAD_OFFSET] == 0).all() + assert torch.equal( + _dequantize_two_level(records), torch.zeros((2, _V_HEAD_DIM)) + ) From 7f3d2708ccd941b4e3a6c30e388a3d68b741c3f0 Mon Sep 17 00:00:00 2001 From: derek Date: Mon, 27 Jul 2026 22:15:00 -0400 Subject: [PATCH 2/3] tests(mla): parameterize production reader e2e over static/dynamic records Both production-head tests (multisplit decode, multitile MG prefill) now run against writer records in per_token_scale mode with the reference dequant applying the in-record fp32 outer scale. Validated on CN4 SM120. Co-authored-by: Sol Claude-Session: https://claude.ai/code/session_01YHuYXXq9krPdvcgpzY4EfE --- .../attention/test_attention_mla_kv_cache.py | 49 +++++++++++++++++-- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/tests/attention/test_attention_mla_kv_cache.py b/tests/attention/test_attention_mla_kv_cache.py index d1fb20a0c..c91468a5b 100644 --- a/tests/attention/test_attention_mla_kv_cache.py +++ b/tests/attention/test_attention_mla_kv_cache.py @@ -216,6 +216,8 @@ def _make_exactly_quantizable_inputs( def _dequantize_records( records: torch.Tensor, + *, + per_token_scale: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: packed = records[:, :_NOPE_BYTES] codes = torch.stack((packed & 0xF, (packed >> 4) & 0xF), dim=-1).reshape( @@ -232,6 +234,14 @@ def _dequantize_records( e2m1[codes.long()].reshape(records.shape[0], 32, 16) * group_scales.unsqueeze(-1) ).reshape(records.shape[0], _V_HEAD_DIM) + if per_token_scale: + latent_scales = ( + records[:, _PAD_OFFSET : _PAD_OFFSET + 4] + .contiguous() + .view(torch.float32) + .reshape(-1) + ) + nope = nope * latent_scales.unsqueeze(-1) rope_scales = ( records[:, _ROPE_SCALE_OFFSET:_PAD_OFFSET] @@ -350,6 +360,7 @@ def _make_written_reader_case( topk: int, seed: int, device: torch.device, + per_token_scale: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: generator = torch.Generator(device="cpu") generator.manual_seed(seed) @@ -376,7 +387,13 @@ def _make_written_reader_case( device=device, ) slots = torch.arange(topk, dtype=torch.int64, device=device) - concat_and_cache_nvfp4_mla_fp8_rope(kv_c, k_pe, cache, slots) + concat_and_cache_nvfp4_mla_fp8_rope( + kv_c, + k_pe, + cache, + slots, + per_token_scale=per_token_scale, + ) return q, cache, indices @@ -387,8 +404,12 @@ def _reference_attention_from_records( indices: torch.Tensor, lengths: torch.Tensor, sm_scale: float, + per_token_scale: bool = False, ) -> torch.Tensor: - nope, _, rope, _ = _dequantize_records(cache.reshape(-1, _RECORD_BYTES)) + nope, _, rope, _ = _dequantize_records( + cache.reshape(-1, _RECORD_BYTES), + per_token_scale=per_token_scale, + ) keys = torch.cat((nope, rope), dim=-1) rows = [] for row, length in enumerate(lengths.cpu().tolist()): @@ -414,8 +435,15 @@ def _assert_reader_matches_dequantized_records( assert cosine > 0.999, f"cosine similarity {cosine:.8f} did not exceed 0.999" +@pytest.mark.parametrize( + "per_token_scale", + [False, True], + ids=["static", "dynamic-token"], +) @torch.inference_mode() -def test_writer_records_feed_production_head_multisplit_decode() -> None: +def test_writer_records_feed_production_head_multisplit_decode( + per_token_scale: bool, +) -> None: device = require_sparkinfer() topk = 129 q, cache, indices = _make_written_reader_case( @@ -423,6 +451,7 @@ def test_writer_records_feed_production_head_multisplit_decode() -> None: topk=topk, seed=1301, device=device, + per_token_scale=per_token_scale, ) lengths = torch.full((1,), topk, dtype=torch.int32, device=device) sm_scale = _HEAD_DIM**-0.5 @@ -467,6 +496,7 @@ def test_writer_records_feed_production_head_multisplit_decode() -> None: forced_num_splits=2, scale_format_override=ScaleFormat.NVFP4_E4M3, fp8_rope_override=None, + latent_scale_per_token=per_token_scale, ) expected = _reference_attention_from_records( q=q, @@ -474,13 +504,21 @@ def test_writer_records_feed_production_head_multisplit_decode() -> None: indices=indices, lengths=lengths, sm_scale=sm_scale, + per_token_scale=per_token_scale, ) torch.cuda.synchronize(device) _assert_reader_matches_dequantized_records(actual, expected) +@pytest.mark.parametrize( + "per_token_scale", + [False, True], + ids=["static", "dynamic-token"], +) @torch.inference_mode() -def test_writer_records_feed_production_head_multitile_prefill_mg() -> None: +def test_writer_records_feed_production_head_multitile_prefill_mg( + per_token_scale: bool, +) -> None: device = require_sparkinfer() topk = 129 q, cache, indices = _make_written_reader_case( @@ -488,6 +526,7 @@ def test_writer_records_feed_production_head_multitile_prefill_mg() -> None: topk=topk, seed=2302, device=device, + per_token_scale=per_token_scale, ) lengths = torch.tensor([topk, 65], dtype=torch.int32, device=device) sm_scale = _HEAD_DIM**-0.5 @@ -504,6 +543,7 @@ def test_writer_records_feed_production_head_multitile_prefill_mg() -> None: model_type=ModelType.GLM_NSA, scale_format=ScaleFormat.NVFP4_E4M3, fp8_rope=True, + latent_scale_per_token=per_token_scale, ) expected = _reference_attention_from_records( q=q, @@ -511,6 +551,7 @@ def test_writer_records_feed_production_head_multitile_prefill_mg() -> None: indices=indices, lengths=lengths, sm_scale=sm_scale, + per_token_scale=per_token_scale, ) torch.cuda.synchronize(device) _assert_reader_matches_dequantized_records(actual, expected) From 0ddd13b4fdbb6a287581aec55fcf9dbbb7e52fd3 Mon Sep 17 00:00:00 2001 From: derek Date: Tue, 28 Jul 2026 10:00:03 -0400 Subject: [PATCH 3/3] docs/tests(mla): clarify dynamic-scale record contract Name the inline scale accurately, share the host reference decoder, and pin the largest-group positioning invariant without claiming every group avoids E4M3 subnormals. Assisted-by: OpenAI Codex --- sparkinfer/attention/_shared/mla/kv_cache.py | 12 ++-- tests/_reference/helpers.py | 40 +++++++++++ .../attention/test_attention_mla_kv_cache.py | 47 ++++++------ .../test_mla_kv_cache_per_token_scale.py | 72 ++++++------------- 4 files changed, 87 insertions(+), 84 deletions(-) diff --git a/sparkinfer/attention/_shared/mla/kv_cache.py b/sparkinfer/attention/_shared/mla/kv_cache.py index b57cc1769..1a44f80ae 100644 --- a/sparkinfer/attention/_shared/mla/kv_cache.py +++ b/sparkinfer/attention/_shared/mla/kv_cache.py @@ -31,7 +31,7 @@ reconstruct ``e4m3_decode(byte) * scale`` (``prefill_mg._ld_global_nvfp4_fp8_rope_bfloat2``). -``per_token_scale=True`` selects the self-describing two-level variant: the +``per_token_scale=True`` selects the inline-scale two-level variant: the NoPE lane derives its own per-token second-level scale instead of assuming the implicit global 1.0 (which parks small-magnitude tokens' group scales in E4M3 subnormals -- the defect the static per-layer @@ -269,9 +269,7 @@ def kernel( token_amax = fmax_f32(token_amax, tmp) latent_scale = token_amax * Float32(_TWO_LEVEL_RCP) if tid == Int32(0): - st_global_f32( - dst + Int64(_LATENT_SCALE_OFFSET), latent_scale - ) + st_global_f32(dst + Int64(_LATENT_SCALE_OFFSET), latent_scale) scale_u32 = Uint32(0) packed64 = Uint64(0) if latent_scale != Float32(0.0): @@ -314,9 +312,7 @@ def kernel( if cutlass.const_expr(self.per_token_scale): if tid < Int32(_PAD_BYTES - _LATENT_SCALE_BYTES): st_global_u8( - dst - + Int64(_PAD_OFFSET + _LATENT_SCALE_BYTES) - + tid.to(Int64), + dst + Int64(_PAD_OFFSET + _LATENT_SCALE_BYTES) + tid.to(Int64), cutlass.Uint8(0), ) else: @@ -513,7 +509,7 @@ def concat_and_cache_nvfp4_mla_fp8_rope( :param scale: accepted for signature parity with the fp8 cache-op family; the nvfp4_ds_mla record has an implicit global scale of 1.0 (group scales carry all magnitude), so it is unused. - :param per_token_scale: write self-describing two-level records: the + :param per_token_scale: write inline-scale two-level records: the per-token second-level scale ``token_amax/(6*448)`` is stored fp32 at record bytes [292, 296) and group scales are encoded relative to it. Readers must run in the matching ``latent_scale_per_token`` mode. diff --git a/tests/_reference/helpers.py b/tests/_reference/helpers.py index 32cd2efc8..d8eeae1f6 100644 --- a/tests/_reference/helpers.py +++ b/tests/_reference/helpers.py @@ -31,6 +31,46 @@ ] +def dequantize_nvfp4_mla_nope( + records: torch.Tensor, + *, + nope_bytes: int = 256, + group_scales_offset: int = 256, + group_scales_end: int = 288, + latent_scale_offset: int | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Decode the NoPE lane of compact NVFP4 MLA records. + + ``latent_scale_offset=None`` models the implicit/static outer-scale + record. Passing an offset models a record carrying one inline fp32 outer + scale per token. + """ + packed = records[:, :nope_bytes] + codes = torch.stack((packed & 0xF, (packed >> 4) & 0xF), dim=-1).reshape( + records.shape[0], nope_bytes * 2 + ) + e2m1 = torch.tensor(E2M1_TO_FLOAT32, dtype=torch.float32, device=records.device) + group_scales = ( + records[:, group_scales_offset:group_scales_end] + .contiguous() + .view(torch.float8_e4m3fn) + .float() + ) + values = ( + e2m1[codes.long()].reshape(records.shape[0], group_scales.shape[-1], -1) + * group_scales.unsqueeze(-1) + ).reshape(records.shape[0], nope_bytes * 2) + if latent_scale_offset is not None: + latent_scales = ( + records[:, latent_scale_offset : latent_scale_offset + 4] + .contiguous() + .view(torch.float32) + .reshape(-1) + ) + values = values * latent_scales.unsqueeze(-1) + return values, group_scales + + def prepare_tp_moe_fp4_experts( *, a: torch.Tensor, diff --git a/tests/attention/test_attention_mla_kv_cache.py b/tests/attention/test_attention_mla_kv_cache.py index c91468a5b..84c137197 100644 --- a/tests/attention/test_attention_mla_kv_cache.py +++ b/tests/attention/test_attention_mla_kv_cache.py @@ -10,16 +10,23 @@ ) from sparkinfer.attention._shared.mla.prefill_mg import run_unified_prefill_mg from sparkinfer.attention._shared.mla.traits import ComputeMode, ModelType, ScaleFormat -from sparkinfer.attention.sparse_mla._scratch import SPARKINFERSparseMLAScratchCaps, plan_sparse_mla_scratch +from sparkinfer.attention.sparse_mla._scratch import ( + SPARKINFERSparseMLAScratchCaps, + plan_sparse_mla_scratch, +) -from tests._reference.helpers import E2M1_TO_FLOAT32, require_sparkinfer +from tests._reference.helpers import ( + dequantize_nvfp4_mla_nope, + require_sparkinfer, +) _RECORD_BYTES = 368 _NOPE_BYTES = 256 _GROUP_SCALES_OFFSET = 256 _ROPE_SCALE_OFFSET = 288 -_PAD_OFFSET = 292 +_LATENT_SCALE_OFFSET = 292 +_PAD_OFFSET = 296 _ROPE_OFFSET = 304 _PAGE_SIZE = 64 _HEADS = 64 @@ -219,32 +226,16 @@ def _dequantize_records( *, per_token_scale: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: - packed = records[:, :_NOPE_BYTES] - codes = torch.stack((packed & 0xF, (packed >> 4) & 0xF), dim=-1).reshape( - records.shape[0], _V_HEAD_DIM - ) - e2m1 = torch.tensor(E2M1_TO_FLOAT32, dtype=torch.float32, device=records.device) - group_scales = ( - records[:, _GROUP_SCALES_OFFSET:_ROPE_SCALE_OFFSET] - .contiguous() - .view(torch.float8_e4m3fn) - .float() + nope, group_scales = dequantize_nvfp4_mla_nope( + records, + nope_bytes=_NOPE_BYTES, + group_scales_offset=_GROUP_SCALES_OFFSET, + group_scales_end=_ROPE_SCALE_OFFSET, + latent_scale_offset=(_LATENT_SCALE_OFFSET if per_token_scale else None), ) - nope = ( - e2m1[codes.long()].reshape(records.shape[0], 32, 16) - * group_scales.unsqueeze(-1) - ).reshape(records.shape[0], _V_HEAD_DIM) - if per_token_scale: - latent_scales = ( - records[:, _PAD_OFFSET : _PAD_OFFSET + 4] - .contiguous() - .view(torch.float32) - .reshape(-1) - ) - nope = nope * latent_scales.unsqueeze(-1) rope_scales = ( - records[:, _ROPE_SCALE_OFFSET:_PAD_OFFSET] + records[:, _ROPE_SCALE_OFFSET:_LATENT_SCALE_OFFSET] .contiguous() .view(torch.float32) .reshape(-1) @@ -325,7 +316,9 @@ def test_writer_preserves_skipped_slots_and_writes_the_record_abi( assert torch.equal( records[:, :_NOPE_BYTES], expected_packed.index_select(0, live_tokens) ) - assert torch.count_nonzero(records[:, _PAD_OFFSET:_ROPE_OFFSET]).item() == 0 + assert ( + torch.count_nonzero(records[:, _LATENT_SCALE_OFFSET:_ROPE_OFFSET]).item() == 0 + ) nope, group_scales, rope, rope_scales = _dequantize_records(records) torch.testing.assert_close( diff --git a/tests/attention/test_mla_kv_cache_per_token_scale.py b/tests/attention/test_mla_kv_cache_per_token_scale.py index 214941832..c23a726ce 100644 --- a/tests/attention/test_mla_kv_cache_per_token_scale.py +++ b/tests/attention/test_mla_kv_cache_per_token_scale.py @@ -4,8 +4,9 @@ bytes [292, 296) and encodes every group scale relative to it, so the largest group's E4M3 scale byte lands at the top of the E4M3 range by construction. These tests pin the record ABI, the positioning invariant that motivates the -mode (no E4M3-subnormal group scales for small-magnitude tokens), and the -accuracy win over the implicit-1.0 static writer at shallow-layer magnitudes. +mode (the largest group scale is placed near the top of the E4M3 range), and +the accuracy win over the implicit-1.0 static writer at shallow-layer +magnitudes. Smaller groups within the same token can still be subnormal. """ from __future__ import annotations @@ -18,7 +19,7 @@ concat_and_cache_nvfp4_mla_fp8_rope, ) -from .._reference.helpers import E2M1_TO_FLOAT32 +from .._reference.helpers import dequantize_nvfp4_mla_nope from ..conftest import require_sparkinfer as require_sm120 @@ -68,46 +69,25 @@ def _write_records( def _dequantize_two_level(records: torch.Tensor) -> torch.Tensor: """Host reference: e2m1 * e4m3(group scale) * fp32 s_t at [292, 296).""" - packed = records[:, :_NOPE_BYTES] - codes = torch.stack((packed & 0xF, (packed >> 4) & 0xF), dim=-1).reshape( - records.shape[0], _V_HEAD_DIM + values, _ = dequantize_nvfp4_mla_nope( + records, + nope_bytes=_NOPE_BYTES, + group_scales_offset=_GROUP_SCALES_OFFSET, + group_scales_end=_ROPE_SCALE_OFFSET, + latent_scale_offset=_LATENT_SCALE_OFFSET, ) - e2m1 = torch.tensor(E2M1_TO_FLOAT32, dtype=torch.float32) - group_scales = ( - records[:, _GROUP_SCALES_OFFSET:_ROPE_SCALE_OFFSET] - .contiguous() - .view(torch.float8_e4m3fn) - .float() - ) - latent_scales = ( - records[:, _LATENT_SCALE_OFFSET:_PAD_OFFSET] - .contiguous() - .view(torch.float32) - .reshape(-1) - ) - return ( - e2m1[codes.long()].reshape(records.shape[0], 32, 16) - * group_scales.unsqueeze(-1) - ).reshape(records.shape[0], _V_HEAD_DIM) * latent_scales.unsqueeze(-1) + return values def _dequantize_static(records: torch.Tensor) -> torch.Tensor: """Host reference for the implicit-1.0 static writer (no second level).""" - packed = records[:, :_NOPE_BYTES] - codes = torch.stack((packed & 0xF, (packed >> 4) & 0xF), dim=-1).reshape( - records.shape[0], _V_HEAD_DIM + values, _ = dequantize_nvfp4_mla_nope( + records, + nope_bytes=_NOPE_BYTES, + group_scales_offset=_GROUP_SCALES_OFFSET, + group_scales_end=_ROPE_SCALE_OFFSET, ) - e2m1 = torch.tensor(E2M1_TO_FLOAT32, dtype=torch.float32) - group_scales = ( - records[:, _GROUP_SCALES_OFFSET:_ROPE_SCALE_OFFSET] - .contiguous() - .view(torch.float8_e4m3fn) - .float() - ) - return ( - e2m1[codes.long()].reshape(records.shape[0], 32, 16) - * group_scales.unsqueeze(-1) - ).reshape(records.shape[0], _V_HEAD_DIM) + return values def _layered_inputs( @@ -123,9 +103,7 @@ def _layered_inputs( base = base / base.abs().amax(dim=-1, keepdim=True) mags = torch.tensor([0.02, 0.08, 0.35, 1.0, 2.6, 5.2]).unsqueeze(-1) kv_c = (base * mags).to(device=device, dtype=dtype) - k_pe = torch.randn((6, _PE_DIM), dtype=torch.float32).to( - device=device, dtype=dtype - ) + k_pe = torch.randn((6, _PE_DIM), dtype=torch.float32).to(device=device, dtype=dtype) return kv_c, k_pe @@ -160,14 +138,12 @@ def test_per_token_records_store_exact_scale_and_keep_abi( records[:, _ROPE_SCALE_OFFSET:_LATENT_SCALE_OFFSET], static_records[:, _ROPE_SCALE_OFFSET:_LATENT_SCALE_OFFSET], ) - assert torch.equal( - records[:, _ROPE_OFFSET:], static_records[:, _ROPE_OFFSET:] - ) + assert torch.equal(records[:, _ROPE_OFFSET:], static_records[:, _ROPE_OFFSET:]) @pytest.mark.parametrize("dtype", [torch.bfloat16], ids=["bf16"]) @torch.inference_mode() -def test_per_token_scale_positions_group_scales_out_of_subnormals( +def test_per_token_scale_positions_largest_group_scale_near_e4m3_max( dtype: torch.dtype, ) -> None: device = require_sm120() @@ -181,8 +157,8 @@ def test_per_token_scale_positions_group_scales_out_of_subnormals( .view(torch.float8_e4m3fn) .float() ) - # Positioning invariant: every token's LARGEST group scale sits near the - # top of the E4M3 range (>= 256 given e4m3 rounding), never subnormal. + # Positioning invariant: every token's largest group scale sits near the + # top of the E4M3 range (>= 256 given e4m3 rounding). assert (group_scales.amax(dim=-1) >= 256.0).all() # The static writer's shallow-magnitude token (amax 0.02) demonstrates the @@ -219,6 +195,4 @@ def test_zero_token_writes_zero_scale_and_zero_payload() -> None: records = _write_records(kv_c, k_pe, per_token_scale=True) assert (records[:, :_ROPE_SCALE_OFFSET] == 0).all() assert (records[:, _LATENT_SCALE_OFFSET:_PAD_OFFSET] == 0).all() - assert torch.equal( - _dequantize_two_level(records), torch.zeros((2, _V_HEAD_DIM)) - ) + assert torch.equal(_dequantize_two_level(records), torch.zeros((2, _V_HEAD_DIM)))