"""H100 block_sparse_gqa. Adapted from public-trial gpt6-astra-h100-xhigh-c2-20261105, frozen submission 4533473a1cb69f9c5d8c8302183d177c04b3819c91d215cd08222c39e24339e8.""" import math import torch import triton as tr import triton.language as tl def _attention_configs(): configurations = [] for bm, bn, warps, stages in [ (16, 64, 4, 1), (16, 64, 4, 2), (16, 128, 4, 2), (16, 256, 4, 1), (32, 64, 4, 2), (32, 64, 4, 3), (32, 128, 4, 1), (32, 128, 4, 2), (32, 128, 4, 3), (32, 256, 4, 1), (32, 256, 8, 1), (64, 64, 4, 2), (64, 64, 4, 3), (64, 128, 4, 1), (64, 128, 4, 2), (64, 128, 4, 3), (64, 128, 8, 2), (64, 256, 8, 1), (64, 256, 8, 2), (128, 64, 4, 1), (128, 64, 4, 2), (128, 64, 4, 3), (128, 64, 8, 2), (128, 128, 4, 1), (128, 128, 8, 2), ]: configurations.append( tr.Config( {"BM": bm, "BN": bn, "PIPE": stages, "MODE": 0}, num_warps=warps, num_stages=stages, ) ) # Scalar block traversal can avoid entire masked blocks in short, # strongly causal attention. for bm, bn in [(32, 64), (32, 128), (64, 64), (64, 128)]: configurations.append( tr.Config( {"BM": bm, "BN": bn, "PIPE": 2, "MODE": 1}, num_warps=4, num_stages=2, ) ) return configurations def _prune_attention_configs(configs, named_args, **kwargs): args = dict(named_args) args.update(kwargs) bs = args["BS"] bd = args["BD"] max_bm = max(16, tr.next_power_of_2(bs)) result = [] for config in configs: bm = config.kwargs["BM"] bn = config.kwargs["BN"] stages = config.kwargs["PIPE"] mode = config.kwargs["MODE"] if bm > max_bm: continue if mode == 1 and bn > max(64, tr.next_power_of_2(bs)): continue estimated_shared = 2 * bm * bd + 4 * bn * bd * stages if estimated_shared > 225280: continue result.append(config) return result if result else configs[:1] @tr.jit def _attention_update( q, KP, VP, cols, col_valid, rows, row_valid, ds, acc, m, l, QLEN: tl.constexpr, KLEN: tl.constexpr, DIM: tl.constexpr, ks2: tl.constexpr, ks3: tl.constexpr, vs2: tl.constexpr, vs3: tl.constexpr, CAUSAL: tl.constexpr, SCALE: tl.constexpr, ): keys = tl.load( KP + ds[:, None] * ks3 + cols[None, :] * ks2, mask=(ds[:, None] < DIM) & col_valid[None, :], other=0, ) scores = tl.dot(q, keys) * SCALE valid = row_valid[:, None] & col_valid[None, :] if CAUSAL: valid = valid & (cols[None, :] <= rows[:, None] + KLEN - QLEN) scores = tl.where(valid, scores, -float("inf")) new_m = tl.maximum(m, tl.max(scores, 1)) safe_m = tl.where(new_m == -float("inf"), 0.0, new_m) alpha = tl.exp2(m - safe_m) p = tl.exp2(scores - safe_m[:, None]) new_l = l * alpha + tl.sum(p, 1) acc = acc * alpha[:, None] values = tl.load( VP + cols[:, None] * vs2 + ds[None, :] * vs3, mask=col_valid[:, None] & (ds[None, :] < DIM), other=0, ) acc = tl.dot(p.to(q.dtype), values, acc) return acc, new_m, new_l @tr.autotune( configs=_attention_configs(), key=[ "BATCH", "HEADS", "GROUP", "QLEN", "KLEN", "DIM", "BS", "MAX_BLOCKS", "CAUSAL", "qs2", "ks2", "vs2", "chdiv", "ihdiv", ], prune_configs_by={"early_config_prune": _prune_attention_configs}, use_cuda_graph=True, ) @tr.jit def _block_attention( Q, K, V, Counts, Indices, O, BATCH: tl.constexpr, QLEN: tl.constexpr, KLEN: tl.constexpr, HEADS: tl.constexpr, GROUP: tl.constexpr, DIM: tl.constexpr, BS: tl.constexpr, MAX_BLOCKS: tl.constexpr, BD: tl.constexpr, CAUSAL: tl.constexpr, SCALE: tl.constexpr, qs0: tl.constexpr, qs1: tl.constexpr, qs2: tl.constexpr, qs3: tl.constexpr, ks0: tl.constexpr, ks1: tl.constexpr, ks2: tl.constexpr, ks3: tl.constexpr, vs0: tl.constexpr, vs1: tl.constexpr, vs2: tl.constexpr, vs3: tl.constexpr, csb: tl.constexpr, csh: tl.constexpr, csr: tl.constexpr, chdiv: tl.constexpr, isb: tl.constexpr, ish: tl.constexpr, isr: tl.constexpr, iss: tl.constexpr, ihdiv: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, PIPE: tl.constexpr, MODE: tl.constexpr, ): tile = tl.program_id(0) bh = tl.program_id(1) b = bh // HEADS h = bh % HEADS kh = h // GROUP tiles_per_block: tl.constexpr = tr.cdiv(BS, BM) qb = tile // tiles_per_block start = qb * BS + (tile % tiles_per_block) * BM rows = start + tl.arange(0, BM) ds = tl.arange(0, BD) ns = tl.arange(0, BN) row_valid = (rows < QLEN) & (rows < (qb + 1) * BS) count = tl.load(Counts + b * csb + (h // chdiv) * csh + qb * csr) ip = Indices + b * isb + (h // ihdiv) * ish + qb * isr kp = K + b * ks0 + kh * ks1 vp = V + b * vs0 + kh * vs1 acc = tl.full((BM, BD), 0.0, tl.float32) m = tl.full((BM,), -float("inf"), tl.float32) l = tl.full((BM,), 0.0, tl.float32) if count > 0: q = tl.load( Q + b * qs0 + h * qs1 + rows[:, None] * qs2 + ds[None, :] * qs3, mask=row_valid[:, None] & (ds[None, :] < DIM), other=0, ) if MODE == 0: # A tile may cover several selected blocks. Selection remains # entirely GPU-driven, including the partially occupied final tile. iterations = tl.cdiv(count * BS, BN) for step in tl.range(0, iterations, num_stages=PIPE): logical = step * BN + ns slots = logical // BS within = logical % BS ids = tl.load(ip + slots * iss, mask=slots < count, other=0) cols = ids * BS + within col_valid = (slots < count) & (cols >= 0) & (cols < KLEN) acc, m, l = _attention_update( q, kp, vp, cols, col_valid, rows, row_valid, ds, acc, m, l, QLEN, KLEN, DIM, ks2, ks3, vs2, vs3, CAUSAL, SCALE, ) else: for block in range(count): bid = tl.load(ip + block * iss) base = bid * BS useful = base < KLEN if CAUSAL: useful = useful & ( base <= tl.minimum(start + BM - 1, QLEN - 1) + KLEN - QLEN ) if useful: for sub in tl.static_range(tr.cdiv(BS, BN)): within = sub * BN + ns cols = base + within col_valid = (within < BS) & (cols >= 0) & (cols < KLEN) acc, m, l = _attention_update( q, kp, vp, cols, col_valid, rows, row_valid, ds, acc, m, l, QLEN, KLEN, DIM, ks2, ks3, vs2, vs3, CAUSAL, SCALE, ) result = acc / tl.where(l > 0.0, l, 1.0)[:, None] tl.store( O + (bh * QLEN + rows[:, None]) * DIM + ds[None, :], result, mask=row_valid[:, None] & (ds[None, :] < DIM), ) def _direct(q, k, v, block_counts, block_indices, block_size, causal): batch, heads, q_len, dim = q.shape out = q.new_empty(q.shape) def grid(meta): bm = meta["BM"] tiles = (q_len // block_size) * tr.cdiv(block_size, bm) + tr.cdiv(q_len % block_size, bm) return tiles, batch * heads _block_attention[grid]( q, k, v, block_counts, block_indices, out, BATCH=batch, QLEN=q_len, KLEN=k.size(2), HEADS=heads, GROUP=heads // k.size(1), DIM=dim, BS=block_size, MAX_BLOCKS=block_indices.size(-1), BD=max(16, tr.next_power_of_2(dim)), CAUSAL=causal, SCALE=math.log2(math.e) / math.sqrt(dim), qs0=q.stride(0), qs1=q.stride(1), qs2=q.stride(2), qs3=q.stride(3), ks0=k.stride(0), ks1=k.stride(1), ks2=k.stride(2), ks3=k.stride(3), vs0=v.stride(0), vs1=v.stride(1), vs2=v.stride(2), vs3=v.stride(3), csb=block_counts.stride(0), csh=0, csr=block_counts.stride(1), chdiv=1, isb=block_indices.stride(0), ish=0, isr=block_indices.stride(1), iss=block_indices.stride(2), ihdiv=1) return out def block_sparse_gqa(q, k, v, block_counts, block_indices, block_size, causal): from kernel_bench.baseline_v06.sparse_plan import pick_backend from kernel_bench.sparse_baselines import block_sparse_gqa as flex args = (q, k, v, block_counts, block_indices, block_size, causal) # The masked compact-head, noncausal path is already efficient in FlexAttention. if not causal and q.shape[-1] <= 64: return flex(*args) use_direct = pick_backend(_direct, flex, args) return (_direct if use_direct else flex)(*args)