File size: 2,939 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
"""Library/composed baselines; these are not claimed to be expert optima."""

from functools import lru_cache
import math

import torch
from .quantization import rowwise_fp8


NAMES = {
    "dense_gemm": "torch.matmul/cuBLAS/FP16",
    "w8a16_gemm": "torch.compile/dequant-BF16+cuBLAS",
    "rowwise_fp8": "Triton/fused-rowwise-E4M3FN/IEEE-div-rn",
    "residual_rmsnorm": "torch.compile/FP32-add-RMSNorm",
    "rope": "torch.compile/partial-NeoX-RoPE",
    "paged_gqa": "torch.gather+FLASH_ATTENTION/composed",
    "ragged_gqa": "per-sequence-FLASH_ATTENTION/host-plan/composed",
    "grouped_gemm": "torch.compile/cuBLAS-bmm+padding-mask/composed",
    "moe_combine": "torch.compile/routed-gather-weighted-reduce",
}


def dense_gemm(a, b):
    return a @ b.t()


def _w8a16_gemm(x, weight, scales):
    return x @ (weight.float() * scales[:, None]).to(x.dtype).t()


def _residual_rmsnorm(x, residual, weight, eps):
    y = x.float() + residual.float()
    return (y * torch.rsqrt(y.square().mean(-1, keepdim=True) + eps) * weight.float()).to(x.dtype)


def _rope(q, k, cache, positions):
    c, s = cache[positions].chunk(2, dim=-1)
    h = c.shape[-1]
    def rotate(x):
        a, b = x[..., :h].float(), x[..., h:2*h].float()
        return torch.cat((a*c[:, None]-b*s[:, None], b*c[:, None]+a*s[:, None], x[..., 2*h:].float()), -1).to(x.dtype)
    return rotate(q), rotate(k)


def _grouped_gemm(x, weight, counts):
    out = torch.bmm(x, weight)
    mask = torch.arange(x.shape[1], device=x.device)[None, :] < counts[:, None]
    return out.masked_fill(~mask[..., None], 0)


def _moe_combine(values, experts, slots, gates):
    return (values[experts, slots].float() * gates[..., None]).sum(1).to(values.dtype)


@lru_cache(None)
def _compiled(name):
    return torch.compile(globals()["_" + name], fullgraph=True, mode="max-autotune-no-cudagraphs")


def w8a16_gemm(*args): return _compiled("w8a16_gemm")(*args)
def residual_rmsnorm(*args): return _compiled("residual_rmsnorm")(*args)
def rope(*args): return _compiled("rope")(*args)
def grouped_gemm(*args): return _compiled("grouped_gemm")(*args)
def moe_combine(*args): return _compiled("moe_combine")(*args)


def paged_gqa(q, kc, vc, table, lengths):
    from .baselines import gqa_attention
    out = []
    for b, length in enumerate(lengths):
        pages = math.ceil(length / kc.shape[1])
        k = kc[table[b, :pages]].flatten(0, 1)[:length].transpose(0, 1)[None]
        v = vc[table[b, :pages]].flatten(0, 1)[:length].transpose(0, 1)[None]
        out.append(gqa_attention(q[b][None, :, None], k, v, False)[0, :, 0])
    return torch.stack(out)


def ragged_gqa(q, k, v, offsets):
    from .baselines import gqa_attention
    outputs = []
    for start, end in zip(offsets, offsets[1:]):
        inputs = [x[start:end].transpose(0, 1)[None] for x in (q, k, v)]
        outputs.append(gqa_attention(*inputs, True)[0].transpose(0, 1))
    return torch.cat(outputs)