File size: 7,740 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""Additional inference contracts. Oracles are independent of performance baselines."""

import math

import torch
import torch.nn.functional as F


CONTRACTS = {
    name: {"rtol": 0.02, "atol": 0.02, "nrmse": 0.01, "min_sm": 80}
    for name in ("dense_gemm", "w8a16_gemm", "rowwise_fp8", "residual_rmsnorm",
                 "rope", "paged_gqa", "ragged_gqa", "grouped_gemm", "moe_combine")
}
CONTRACTS["rowwise_fp8"].update(min_sm=89, outputs=[
    {"rtol": 0, "atol": 0, "nrmse": 0},
    {"rtol": 1e-6, "atol": 1e-12, "nrmse": 1e-6},
])
for _task in ("rope", "grouped_gemm"):
    CONTRACTS[_task]["semantic"] = _task


def check_invariants(task, args, out):
    if task == "rope":
        rotary_dim = args[2].shape[-1]
        return all(torch.equal(x[..., rotary_dim:], y[..., rotary_dim:]) for x,y in zip(args[:2], out))
    if task == "grouped_gemm":
        x, _, counts = args
        padding = torch.arange(x.shape[1], device=x.device)[None] >= counts[:, None]
        return bool((out[padding] == 0).all().item())
    return True


def make_inputs(case, rand, gen):
    task = case["task"]
    if task in ("dense_gemm", "w8a16_gemm"):
        m, n, k = (case[x] for x in ("m", "n", "k"))
        stride = case.get("input_stride", 1)
        x = rand((m, k * stride), 1 / math.sqrt(k))[:, ::stride]
        if task == "dense_gemm":
            return x.to(torch.float16), rand((n, k)).to(torch.float16)
        w = torch.randint(-127, 128, (n, k), device="cuda", generator=gen, dtype=torch.int8)
        scales = torch.rand(n, device="cuda", generator=gen) / 64 + 1 / 256
        return x, w, scales
    if task == "rowwise_fp8":
        return (rand((case["m"], case["hidden"])),)
    if task == "residual_rmsnorm":
        shape = (case["m"], case["hidden"])
        return rand(shape), rand(shape), rand((shape[-1],)), case.get("eps", 1e-5)
    if task == "rope":
        m, h, hk, d, rd = (case[x] for x in ("m", "heads", "kv_heads", "head_dim", "rotary_dim"))
        max_pos = case["max_position"]
        angles = torch.arange(max_pos, device="cuda")[:, None] * (10000. ** (-torch.arange(0, rd, 2, device="cuda").float() / rd))[None, :]
        cache = torch.cat((angles.cos(), angles.sin()), dim=-1)
        positions = torch.randint(max_pos, (m,), device="cuda", generator=gen)
        return rand((m, h, d)), rand((m, hk, d)), cache, positions
    if task == "paged_gqa":
        lengths = tuple(case["lengths"])
        b, h, hk, d, ps = len(lengths), case["heads"], case["kv_heads"], case["head_dim"], case["page_size"]
        max_pages = math.ceil(max(lengths) / ps)
        pages = b * max_pages + 3
        # Random physical page permutation; padding and unused pages contain live data.
        table = torch.randperm(pages, device="cuda", generator=gen)[:b * max_pages].reshape(b, max_pages)
        return rand((b, h, d)), rand((pages, ps, hk, d)), rand((pages, ps, hk, d)), table, lengths
    if task == "ragged_gqa":
        offsets = [0]
        for n in case["lengths"]:
            offsets.append(offsets[-1] + n)
        n, h, hk, d = offsets[-1], case["heads"], case["kv_heads"], case["head_dim"]
        return rand((n, h, d)), rand((n, hk, d)), rand((n, hk, d)), tuple(offsets)
    if task == "grouped_gemm":
        e, c, k, n = (case[x] for x in ("experts", "capacity", "k", "n"))
        counts = torch.randint(c + 1, (e,), device="cuda", generator=gen)
        counts[0], counts[-1] = 0, c
        return rand((e, c, k), 1 / math.sqrt(k)), rand((e, k, n)), counts
    if task == "moe_combine":
        m, k, e, c, h = (case[x] for x in ("m", "top_k", "experts", "capacity", "hidden"))
        expert = torch.randint(e, (m, k), device="cuda", generator=gen)
        slots = torch.randint(c, (m, k), device="cuda", generator=gen)
        # Duplicate expert/slot reads are legal and must be accumulated for every route.
        gates = torch.rand((m, k), device="cuda", generator=gen)
        gates /= gates.sum(-1, keepdim=True)
        return rand((e, c, h)), expert, slots, gates
    raise ValueError(task)


def reference(task, *args):
    if task == "dense_gemm":
        a, b = args
        return (a.float() @ b.float().t()).to(torch.float16)
    if task == "w8a16_gemm":
        x, w, scales = args
        # Dequantization has a specified BF16 operator boundary.
        weight = (w.float() * scales[:, None]).to(torch.bfloat16)
        return (x.float() @ weight.float().t()).to(torch.bfloat16)
    if task == "rowwise_fp8":
        x, = args
        max_abs = x.float().abs().amax(-1, keepdim=True)
        scale = torch.where(max_abs == 0, torch.ones_like(max_abs), max_abs / 448.)
        quantized = torch.clamp(x.float() / scale, -448, 448).to(torch.float8_e4m3fn)
        return quantized, scale
    if task == "residual_rmsnorm":
        x, residual, weight, eps = args
        y = x.float() + residual.float()
        return (y / torch.sqrt(y.square().mean(-1, keepdim=True) + eps) * weight.float()).to(x.dtype)
    if task == "rope":
        q, k, cache, positions = args
        half = cache.shape[-1] // 2
        c, s = cache.index_select(0, positions).split(half, dim=-1)
        outputs = []
        for x in (q, k):
            y = x.float().clone()
            left, right = x[..., :half].float(), x[..., half:2 * half].float()
            y[..., :half] = left * c[:, None] - right * s[:, None]
            y[..., half:2 * half] = right * c[:, None] + left * s[:, None]
            outputs.append(y.to(x.dtype))
        return tuple(outputs)
    if task in ("paged_gqa", "ragged_gqa"):
        from .tasks import reference as dense_reference
        outputs = []
        if task == "paged_gqa":
            q, kc, vc, table, lengths = args
            for b, length in enumerate(lengths):
                npages = math.ceil(length / kc.shape[1])
                k = kc.index_select(0, table[b, :npages]).flatten(0, 1)[:length]
                v = vc.index_select(0, table[b, :npages]).flatten(0, 1)[:length]
                outputs.append(dense_reference("gqa_attention", q[b][None, :, None],
                    k.transpose(0, 1)[None], v.transpose(0, 1)[None], False)[0, :, 0])
            return torch.stack(outputs)
        q, k, v, offsets = args
        for start, end in zip(offsets, offsets[1:]):
            outputs.append(dense_reference("gqa_attention", q[start:end].transpose(0, 1)[None],
                k[start:end].transpose(0, 1)[None], v[start:end].transpose(0, 1)[None], True)[0].transpose(0, 1))
        return torch.cat(outputs)
    if task == "grouped_gemm":
        x, weights, counts = args
        out = torch.zeros((*x.shape[:2], weights.shape[-1]), device=x.device, dtype=x.dtype)
        for expert, count in enumerate(counts.tolist()):
            out[expert, :count] = (x[expert, :count].float() @ weights[expert].float()).to(x.dtype)
        return out
    if task == "moe_combine":
        values, experts, slots, gates = args
        out = torch.zeros((experts.shape[0], values.shape[-1]), device=values.device, dtype=torch.float32)
        for route in range(experts.shape[1]):
            out += values[experts[:, route], slots[:, route]].float() * gates[:, route, None]
        return out.to(values.dtype)
    raise ValueError(task)


def output_view(task, out):
    """Consume all public outputs when reconnecting kernels to the fixed block."""
    if task == "rowwise_fp8":
        out = (out[0].float() * out[1]).to(torch.bfloat16)
    elif task == "rope":
        out = torch.cat([x.flatten(1) for x in out], dim=-1)
    elif task == "paged_gqa":
        out = out.flatten(1)
    elif task == "ragged_gqa":
        out = out.flatten(1)
    elif task == "grouped_gemm":
        out = out.flatten(0, 1)
    return out.to(torch.bfloat16)