File size: 5,727 Bytes
5d12def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""Fixed sparse-attention contracts and independent FP32 mathematical oracles.

Sparsity is input data, never a quality/accuracy knob for the submitted program.
All valid indices are unique within their row. Empty rows have exactly zero O.
"""

import math

import torch


from .sparse_contracts import CONTRACTS


def make_inputs(case, rand, gen):
    b, h, qn, kn = (case[x] for x in ("batch", "heads", "q_len", "kv_len"))
    if case["task"] == "block_sparse_gqa":
        hk, d, bs, capacity = (case[x] for x in
                               ("kv_heads", "head_dim", "block_size", "max_blocks"))
        if h % hk or qn > kn or bs not in (64, 128):
            raise ValueError("Require divisible GQA heads, Q <= KV and block_size 64/128")
        qr, kr = math.ceil(qn / bs), math.ceil(kn / bs)
        if not 1 <= capacity <= kr:
            raise ValueError("Invalid block-list capacity")
        counts = torch.randint(1, capacity + 1, (b, qr), device="cuda", generator=gen, dtype=torch.int32)
        counts[0, 0] = capacity
        indices = torch.full((b, qr, capacity), -1, device="cuda", dtype=torch.int32)
        # Input generation is outside timing; the live GPU metadata is NOT a CPU plan.
        for batch in range(b):
            for row in range(qr):
                count = int(counts[batch, row])
                selected = torch.randperm(kr, device="cuda", generator=gen)[:count]
                indices[batch, row, :count] = selected.to(torch.int32)
        if case.get("empty_rows", True):
            counts[:, -1] = 0
            indices[:, -1] = -1
        return (rand((b, h, qn, d)), rand((b, hk, kn, d)), rand((b, hk, kn, d)),
                counts, indices, bs, case["causal"])
    latent, rope, selected, ps = (case[x] for x in
                                  ("latent_dim", "rope_dim", "selected", "page_size"))
    if kn % ps or not 1 <= selected <= kn:
        raise ValueError("Cache capacity must be page-aligned; selected must fit capacity")
    indices = torch.empty((b, qn, selected), device="cuda", dtype=torch.int32)
    for batch in range(b):
        for row in range(qn):
            count = int(torch.randint(1, selected + 1, (), device="cuda", generator=gen))
            if batch == 0 and row == 0:
                count = selected
            ids = torch.randperm(kn, device="cuda", generator=gen)[:selected].to(torch.int32)
            ids[count:] = -1
            # Padding can appear anywhere: implementations must test the index value.
            indices[batch, row] = ids[torch.randperm(selected, device="cuda", generator=gen)]
    if case.get("empty_rows", True) and b * qn > 1:
        indices[-1, -1] = -1
    cache = rand((kn // ps, ps, latent + rope))
    return rand((b, qn, h, latent + rope)), cache, indices, latent, case["scale"]


def reference(task, *args):
    if task == "block_sparse_gqa":
        q, k, v, counts, indices, bs, causal = args
        b, h, qn, d = q.shape
        hk, kn = k.shape[1:3]
        out = torch.zeros_like(q)
        for batch in range(b):
            for row in range(counts.shape[1]):
                start, stop = row * bs, min((row + 1) * bs, qn)
                blocks = indices[batch, row, :int(counts[batch, row])].long()
                positions = (blocks[:, None] * bs + torch.arange(bs, device=q.device)).flatten()
                positions = positions[positions < kn]
                if not positions.numel():
                    continue
                keys = k[batch, :, positions].float().repeat_interleave(h // hk, 0)
                values = v[batch, :, positions].float().repeat_interleave(h // hk, 0)
                scores = (q[batch, :, start:stop].float() @ keys.transpose(-1, -2)) / math.sqrt(d)
                if causal:
                    allowed = positions[None] <= torch.arange(start, stop, device=q.device)[:, None] + kn - qn
                    scores.masked_fill_(~allowed, -torch.inf)
                # All-masked queries have zero output, including causal-only empty rows.
                weights = torch.nan_to_num(torch.softmax(scores, -1), nan=0.)
                out[batch, :, start:stop] = (weights @ values).to(q.dtype)
        return out
    q, cache, indices, latent, scale = args
    flat = cache.flatten(0, 1)
    out = torch.zeros((*q.shape[:-1], latent), device=q.device, dtype=q.dtype)
    for batch in range(q.shape[0]):
        for row in range(q.shape[1]):
            ids = indices[batch, row]
            keys = flat[ids[ids >= 0].long()].float()
            if not keys.shape[0]:
                continue
            scores = (q[batch, row].float() @ keys.t()) * scale
            # Absorbed MLA: V is the latent prefix of K, NOT a separate projection.
            out[batch, row] = (torch.softmax(scores, -1) @ keys[:, :latent]).to(q.dtype)
    return out


def check_invariants(task, args, out):
    if task == "block_sparse_gqa":
        q, k, _, counts, indices, bs, causal = args
        empty = counts.repeat_interleave(bs, -1)[:, :q.shape[2]] == 0
        if causal:
            slots = torch.arange(indices.shape[-1], device=q.device)
            first = torch.where(slots < counts[..., None], indices, k.shape[2]).amin(-1) * bs
            first = first.repeat_interleave(bs, -1)[:, :q.shape[2]]
            empty = empty | (first > torch.arange(q.shape[2], device=q.device) + k.shape[2] - q.shape[2])
        return bool((out.transpose(1, 2)[empty] == 0).all().item())
    if task == "sparse_mla":
        empty = (args[2] < 0).all(-1)
        return bool((out[empty] == 0).all().item())
    return True


def output_view(task, out):
    if task == "block_sparse_gqa":
        out = out.transpose(1, 2)
    return out.reshape(-1, out.shape[-2] * out.shape[-1])