File size: 2,422 Bytes
0f775e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""A single wide SwiGLU block at batch 8 -- the producer/consumer warp-specialisation problem.

Three GEMVs against 805 MB of weights, with a hard dependency in the middle: `down` cannot start
until `silu(gate @ x) * (up @ x)` is complete for the whole 16384-wide intermediate. That makes the
whole thing one kernel with a grid-wide barrier in it, and inside each half the shape is the classic
warp-specialisation case: a stream of weight tiles that must be pulled from HBM continuously while a
separate set of warps consumes them against 8 resident activation rows.

Batch 8 rather than batch 1 on purpose: each loaded weight tile is used eight times, so the consumer
has enough arithmetic that keeping it fed is a real scheduling problem rather than a formality, while
the arithmetic intensity (8 flop/byte against a ~146 flop/byte machine balance) keeps the task firmly
bandwidth-bound and the reward honestly a GB/s number.
"""

BODY = r'''
def make_weights(cfg, seed=0, device="cuda"):
    """gate/up: (ffn, d).  down: (d, ffn).  1/sqrt(fan_in) scaled, bf16."""
    g = torch.Generator(device=device).manual_seed(seed)
    d, f = cfg["d"], cfg["ffn"]

    def rnd(*shape, fan_in):
        return (torch.randn(*shape, device=device, dtype=torch.float32, generator=g)
                / (fan_in ** 0.5)).to(torch.bfloat16)

    return {"gate": rnd(f, d, fan_in=d), "up": rnd(f, d, fan_in=d), "down": rnd(d, f, fan_in=f)}


def make_kv(cfg, batch, prefill_len, max_seq, seed=0, device="cuda"):
    """No KV cache in this task."""
    return []


def make_step_args(cfg, batch, base_pos, seed, n):
    """(x,) per call -- a fresh (B, d) bf16 activation block."""
    g = torch.Generator(device="cuda").manual_seed(seed)
    return [(torch.randn(batch, cfg["d"], device="cuda", dtype=torch.float32,
                         generator=g).to(torch.bfloat16),) for _ in range(n)]


def build_gemv(weights, kv_cache, cfg, max_seq_len):
    """UNTIMED setup. Re-tile, interleave gate/up, allocate the intermediate, ..."""
    return {"W": weights, "cfg": cfg}


@torch.no_grad()
def swiglu_gemv(handle, x):
    """One SwiGLU block: down @ (silu(gate @ x) * (up @ x)).

    x       : (B, d) bf16
    returns : (B, d) fp32
    """
    W = handle["W"]
    h = F.silu(torch.matmul(x, W["gate"].T).float()) * torch.matmul(x, W["up"].T).float()
    return torch.matmul(h.to(torch.bfloat16), W["down"].T).float()
'''

MODEL_SRC = BODY