"""VSA stage-3 sparse-attention Triton REFERENCE kernel (`wan22:triton64`). `_attn_fwd_sparse` is lifted verbatim from the production Wan2.2/wan/kernels/block_sparse_attn_triton.py. `triton_block_sparse_attn_forward` is the canonical BSHD host launcher (TMA descriptors). This is the reference any candidate VSA forward-attention kernel is scored against on the `baseten-admin/wan2.2_production_values` captures. See README.md ("Scoring / loss"). Reference call (returns (o, M)): o, M = triton_block_sparse_attn_forward(q, k, v, topk_idx, vbs) # q,k,v: (1,39936,40,128) bf16 ; topk_idx: (1,40,624,78) int32 ; vbs: (624,) int32 """ import math import torch from triton.tools.tensor_descriptor import TensorDescriptor import triton import triton.language as tl from triton.tools.tensor_descriptor import TensorDescriptor # Hardcoded kernel config (matches block_sparse_attn_triton.py). _BLOCK_M = 64 _BLOCK_N = 64 _NUM_WARPS = 4 _NUM_STAGES = 3 # ──────────────────────────── SPARSE ADDITION BEGIN ─────────────────────────── # per-query KV-block count is uniform (TOPK) for every (batch, head, query-block) # so we pass TOPK as a `tl.constexpr`... original `q2k_num` tensor argument is gone # for speed # note also that warp specialization slowed this down... do not implement @triton.jit def _attn_fwd_sparse( sm_scale, q2k_index, # topk indices variable_block_sizes, M, desc_q, # TMA descriptors for Q, K, V, Out desc_k, desc_v, desc_o, Z, H, N_CTX_Q, # S_Q N_CTX_KV, # S_KV HEAD_DIM: tl.constexpr, # head dimension BLOCK_M: tl.constexpr, # 64 BLOCK_N: tl.constexpr, # 64 TOPK: tl.constexpr): # topk # 64×64 block-sparse forward kernel and BSHD-native via TMA descriptors. # ----- stage 1: block idx mapping ----- q_blk = tl.program_id(0) # Q-tile index off_hz = tl.program_id(1) # fused (batch, head) b = off_hz // H h = off_hz % H # which head am i in? q_tiles = N_CTX_Q // BLOCK_M # S_Q / 64 meta_base = (h * q_tiles + q_blk) # h*q_tiles + q_blk # kv_blocks is now compile-time-known (== TOPK) kv_ptr = q2k_index + meta_base * TOPK # ptr to list of indices for this query block # ----- accumulators, load q tile, and arrays for running sum ----- q_offset = q_blk * BLOCK_M offs_m = q_offset + tl.arange(0, BLOCK_M) row_prev_max = tl.full([BLOCK_M], -float("inf"), tl.float32) row_prev_denom_sum = tl.zeros([BLOCK_M], dtype=tl.float32) + 1.0 acc = tl.zeros([BLOCK_M, HEAD_DIM], dtype=tl.float32) # running unnormalized output qk_scale = sm_scale * 1.44269504 # 2^(x*log_2(e)*scale) = e^(x*scale) = e^(x/sqrt(D)) # load Q tile via TMA q_4d = desc_q.load([b, q_offset, h, 0]) q = q_4d.reshape([BLOCK_M, HEAD_DIM]) # ----- sparse loop over selected K/V cubes ----- for i in range(0, TOPK): kv_idx = tl.load(kv_ptr + i).to(tl.int32) block_size = tl.load(variable_block_sizes + kv_idx) # real (non-pad) count kv_t = kv_idx * BLOCK_N # row offset into K/V # TMA loads K in natural (BLOCK_N, HEAD_DIM) orientation; # transpose in registers via .T (free metadata flip) to get (HEAD_DIM, BLOCK_N) k_4d = desc_k.load([b, kv_t, h, 0]) k = k_4d.reshape([BLOCK_N, HEAD_DIM]).T qk = tl.dot(q, k) mask = tl.arange(0, BLOCK_N) < block_size # mask pad columns qk = tl.where(mask[None, :], qk, -float("inf")) qk_normed = qk * qk_scale # flash attention online softmax update with curr max row_curr_max = tl.maximum(row_prev_max, tl.max(qk_normed, 1)) p = tl.math.exp2(qk_normed - row_curr_max[:, None]) row_curr_denom_sum = tl.sum(p, 1) # rescale running state if max changed fa style alpha = tl.math.exp2(row_prev_max - row_curr_max) # undoes prev max, then adds curr max. no-op (e^0=1 if no change) row_prev_denom_sum = row_prev_denom_sum * alpha + row_curr_denom_sum # online update denom acc = acc * alpha[:, None] # online update acc # load V tile via TMA v_4d = desc_v.load([b, kv_t, h, 0]) v = v_4d.reshape([BLOCK_N, HEAD_DIM]) acc = tl.dot(p.to(tl.bfloat16), v, acc) row_prev_max = row_curr_max # ----- epilogue ----- row_prev_max += tl.math.log2(row_prev_denom_sum) acc = acc / row_prev_denom_sum[:, None] # final softmax normalization tl.store(M + off_hz * N_CTX_Q + offs_m, row_prev_max) # store output tile via TMA out_4d = acc.to(tl.bfloat16).reshape([1, BLOCK_M, 1, HEAD_DIM]) desc_o.store([b, q_offset, h, 0], out_4d) def triton_block_sparse_attn_forward(q, k, v, q2k_index, variable_block_sizes): """Canonical BSHD launcher for `_attn_fwd_sparse`. Returns (o, M). o : (B, S, H, D) bf16 attention output M : (B, H, S) fp32 log-sum-exp (discarded by inference; provided for parity) """ B, S_q, H, D = q.shape S_kv = k.shape[1] sm_scale = 1.0 / math.sqrt(D) topk = q2k_index.shape[-1] o = torch.empty_like(q) M = torch.empty((B, H, S_q), dtype=torch.float32, device=q.device) sq = [S_q * H * D, H * D, D, 1] sk = [S_kv * H * D, H * D, D, 1] dq = TensorDescriptor(q, shape=[B, S_q, H, D], strides=sq, block_shape=[1, _BLOCK_M, 1, D]) dk = TensorDescriptor(k, shape=[B, S_kv, H, D], strides=sk, block_shape=[1, _BLOCK_N, 1, D]) dv = TensorDescriptor(v, shape=[B, S_kv, H, D], strides=sk, block_shape=[1, _BLOCK_N, 1, D]) do = TensorDescriptor(o, shape=[B, S_q, H, D], strides=sq, block_shape=[1, _BLOCK_M, 1, D]) grid = (triton.cdiv(S_q, _BLOCK_M), B * H, 1) _attn_fwd_sparse[grid]( sm_scale, q2k_index, variable_block_sizes, M, dq, dk, dv, do, B, H, S_q, S_kv, HEAD_DIM=D, BLOCK_M=_BLOCK_M, BLOCK_N=_BLOCK_N, TOPK=topk, num_warps=_NUM_WARPS, num_stages=_NUM_STAGES, ) return o, M