File size: 5,291 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Host checks of the DEC megakernel's host side (no device): geometry, L1 budget, stream layout (one layer, bf16
round trip of every core's sticks vs the folded weights), tables, and a CPU emulation of the kernel's layer-0
decomposition (padded partition, real-K loops, sandwich norms) against the reference decoder."""

import os

import numpy as np
import pytest
import torch

from tt_glmocr.tt.mk_dec import arena as A
from tt_glmocr.tt.mk_dec import formats as F
from tt_glmocr.tt.mk_dec import geometry as G
from tt_glmocr.tt.mk_dec import weights as E

MODEL = os.environ.get("GLMOCR_MODEL_DIR") or os.environ.get("GLMOCR_MODEL") or ""  # a local checkpoint dir (optional)


def fake_banks():
    opt0 = [(0, 0), (0, 4), (4, 0), (4, 4), (8, 0), (8, 4), (11, 2), (11, 7)]
    opt1 = [(1, 1), (1, 5), (5, 1), (5, 5), (9, 1), (9, 5), (10, 3), (10, 8)]
    return opt0, opt1


def test_dims_and_l1():
    d = G.GLM
    assert (d.xs, d.fs, d.hc, d.dtk, d.itk) == (2, 5, 58, 48, 144)
    assert d.a_tiles % G.PACKET_TILES["bfp8"] == 0 and d.m_tiles % 8 == 0 and d.h_tiles % 8 == 0
    for f in ("bf16", "bfp8"):
        for k in (1, 2, 4, 6):
            assert G.cb_total(d, f, f, k) <= G.L1_BUDGET
            assert G.ring_bytes(f, f)["A"] % G.T32 == 0


def test_geometry_roles():
    o0, o1 = fake_banks()
    g = G.build(12, 10, o0, o1, attk=4)
    assert len(g.mm) == 32 and len(g.att) == 32 and g.hub not in g.att
    cores = [m.xy for m in g.mm] + g.att + [g.hub]
    assert len(set(cores)) == len(cores)
    args = G.core_args(g, lambda c: (c[0] + 1, c[1] + 2), {w: (0, 0, 0) for w in range(32)})
    for a, xy in enumerate(g.att):
        assert args[xy][G.A_W] == a // 4 and args[xy][G.A_SLOT] == a % 4
    for nb in (1, 3, 4, 5, 17, 128):
        cov = []
        for s in range(4):
            j0, j1 = G.slot_range(nb, 4, s)
            cov += list(range(j0, j1))
        assert cov == list(range(nb))


@pytest.mark.skipif(not os.path.isdir(MODEL), reason="weights not present")
def test_streams_one_layer_bf16():
    w = E.load_dec(MODEL, n_layers=1)
    st = A.mm_streams(w, E.RECIPES["bf16"], n_layers=1)
    d = G.GLM
    L = w.layers[0]
    wqkv = torch.cat([L["g1"][:, None] * L["wq"].t(), L["g1"][:, None] * L["wk"].t(), L["g1"][:, None] * L["wv"].t()], 1)
    for m in (0, 23, 24, 31):
        a = F.unpack_tiles(np.asarray(st[m]["A"]).reshape(-1, 2048), "bf16")
        assert a.shape[0] == d.a_tiles
        col0 = F.untilize(a[:d.dtk], d.d, 32)
        ref = F.to_bf16_rne(wqkv[:, 4 * m * 32:(4 * m + 1) * 32])
        assert torch.equal(col0, ref)
        o = F.untilize(a[4 * d.dtk:4 * d.dtk + 64], 2048, 32)
        if m >= 24:
            assert o.abs().max() == 0  # padded residual columns
        mm = F.unpack_tiles(np.asarray(st[m]["M"]).reshape(-1, 2048), "bf16")
        assert mm.shape[0] == d.m_tiles


def test_tables():
    rt = A.rope_table(64)
    assert rt.shape == (128, 1024)
    c, s = E.rope_tables(torch.arange(64))
    assert torch.allclose(rt[2 * 5, :128], c[5]) and torch.allclose(rt[2 * 5 + 1, 64:128], s[5, 64:])
    bm = A.seen_bitmap([0, 31, 32, 59391])
    assert bm[0] == (1 | (1 << 31)) and bm[1] == 1 and bm[59391 >> 5] == np.uint32(1 << 31)


@pytest.mark.skipif(not os.path.isdir(MODEL), reason="weights not present")
def test_emulated_layer0_matches_reference():
    """fp32 emulation of the kernel decomposition of layer 0 for one decode row (padded partition, folded gammas,
    half-split rope with the permuted rows, sandwich norms) == the reference decoder's layer 0 (fp32)."""
    from tt_glmocr.reference import model as R

    torch.manual_seed(0)
    w = E.load_dec(MODEL, n_layers=1)
    Wr = R.Weights(MODEL, torch.float32)
    L = w.layers[0]
    P = 7  # context: rows 0..P-1 then the new row at P (text positions)
    xs = torch.randn(P + 1, 1536) * 0.05
    dec = R.Decoder(Wr)
    st = {}
    # reference: run all rows through the 16-layer decoder, take layer 0's last row
    dec.forward(xs, torch.arange(P + 1).reshape(1, -1).expand(3, -1), st, all_logits=False)
    ref = st["t_layer0"][-1]

    def rms_r(v):
        return torch.rsqrt(v.pow(2).mean() + E.EPS)

    # K / V of rows 0..P (rope in the half layout with permuted rows)
    cos, sin = E.rope_tables(torch.arange(P + 1))
    h = xs * torch.stack([rms_r(r) for r in xs])[:, None]
    q = (h * L["g1"]) @ L["wq"].t()
    k = (h * L["g1"]) @ L["wk"].t()
    v = (h * L["g1"]) @ L["wv"].t()

    def rope(t, c, s_):
        t = t.reshape(t.shape[0], -1, 128)
        sw = torch.cat([t[..., 64:], t[..., :64]], -1)
        ss = torch.cat([-s_[:, :64], s_[:, 64:]], -1)
        return t * c[:, None] + sw * ss[:, None]

    qr, kr = rope(q, cos, sin), rope(k, cos, sin)
    vr = v.reshape(P + 1, 8, 128)
    o = []
    for hq in range(16):
        g = hq // 2
        sc = (qr[-1, hq] * 128 ** -0.5) @ kr[:, g].t()
        o.append(torch.softmax(sc, -1) @ vr[:, g])
    o = torch.cat(o)
    y = o @ L["wo"].t()
    x = xs[-1] + L["gpsa"] * y * rms_r(y)
    h2 = x * rms_r(x)
    f = torch.nn.functional.silu((h2 * L["g2"]) @ L["wg"].t()) * ((h2 * L["g2"]) @ L["wu"].t())
    y2 = f @ L["wd"].t()
    x = x + L["gpm"] * y2 * rms_r(y2)
    assert torch.allclose(x, ref, atol=2e-4, rtol=1e-4), (x - ref).abs().max()