File size: 6,033 Bytes
1e8fbed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Host tests (no device): tokenizer parity (G0) and the clean-room CPU reference (G1) against the official goldens,
the megakernel's host-side layout (weight shards, plan, inputs) and the configuration parser."""
import json
import os

import numpy as np
import pytest

from tt_minilm.tests.gates import model_dir  # noqa: E402

MODEL_DIR = model_dir()
HAVE_MODEL = os.path.isfile(os.path.join(MODEL_DIR, "model.safetensors"))


def _golden():
    from tt_minilm.tests.gates import have_golden, load_golden

    if not have_golden():
        pytest.skip("goldens not available (MINILM_GOLDEN_DIR)")
    return load_golden()


@pytest.fixture(scope="module")
def model():
    if not HAVE_MODEL:
        pytest.skip("weights not available")
    from tt_minilm.host import HostEmbeddings
    from tt_minilm.tokenizer import Tokenizer
    from tt_minilm.weights import load_weights

    W = load_weights(MODEL_DIR)
    return W, HostEmbeddings(W), Tokenizer(MODEL_DIR)


def test_g0_tokenizer_matches_official(model):
    man, _ = _golden()
    _, _, tok = model
    bad = [c["key"] for c in man["cases"] if c["text"] is not None and tok.encode([c["text"]])[0] != c["ids"]]
    assert not bad, bad


def test_g1_reference_matches_official(model):
    from tt_minilm.host import finish
    from tt_minilm.reference.model import encode_ids
    from tt_minilm.tests.gates import cos

    man, gold = _golden()
    W, he, _ = model
    worst = 1.0
    for c in man["cases"][::3]:
        pooled, toks, _ = encode_ids(W, he, [c["ids"]])
        worst = min(worst, cos(finish(pooled, [len(c["ids"])])[0], gold[c["key"] + ".emb"]))
        assert np.abs(toks[0] - gold[c["key"] + ".tok"]).max() < 2e-4
    assert worst >= 0.999999


def test_truncation_policies(model):
    _, _, tok = model
    t = "alpha beta gamma delta epsilon " * 100
    r = tok.encode([t], 10, "right")[0]
    lft = tok.encode([t], 10, "left")[0]
    full = tok.pieces([t])[0]
    assert len(r) == 10 and r[0] == 101 and r[-1] == 102 and r[1:-1] == full[:8]
    assert len(lft) == 10 and lft[1:-1] == full[-8:]
    from tt_minilm.tokenizer import TooLong

    with pytest.raises(TooLong):
        tok.encode([t], 10, "error")
    assert tok.encode([""])[0] == [101, 102]


def test_weight_shards_layout(model):
    from tt_minilm.tt.mk import program as P

    W, _, _ = model
    D = P.D
    sh = P.weight_shards(W, 5)
    scale = 32 ** -0.5
    wq = W["encoder.layer.3.attention.self.query.weight"].numpy().T * scale
    w2 = W["encoder.layer.5.output.dense.weight"].numpy().T
    # core (x = 7, y = 3: h = 1), layer 3, QKV k = 4, j = 0 (q): W^T tile (6 + 4, 7)
    assert np.allclose(sh[3, 7, 3 * D["WL"] + D["W_QKV"] + 4 * 3], wq[10 * 32:11 * 32, 7 * 32:8 * 32])
    # core (x = 2, y = 8: h = 0), layer 5, W2 k = 20: W2^T tile (20, 2)
    assert np.allclose(sh[8, 2, 5 * D["WL"] + D["W_2"] + 20], w2[20 * 32:21 * 32, 2 * 32:3 * 32])
    # parameter tile: hi + lo of the bias vector V_B1 + 1 (b1 tile 4x + 1) for x = 9
    b1 = W["encoder.layer.0.intermediate.dense.bias"].numpy()
    pt = sh[0, 9, D["P_BASE"]]
    i = D["V_B1"] + 1
    assert np.allclose(pt[2 * i] + pt[2 * i + 1], b1[(4 * 9 + 1) * 32:(4 * 9 + 2) * 32], atol=1e-6)
    # E_i @ P = vector i on every row
    E = sh[0, 0, D["K_E0"] + i]
    assert np.allclose((E @ pt)[5], b1[(4 * 0 + 1) * 32:(4 * 0 + 2) * 32] * 0 + (pt[2 * i] + pt[2 * i + 1]))


def test_plan_and_inputs(model):
    from tt_minilm.tt.mk import program as P

    _, he, _ = model
    D = P.D
    lengths = [20, 256, 65, 2, 33, 32, 31]
    plan = P.build_plan(lengths, 5, 1, 2)
    nks = [(n + 31) // 32 for n in lengths]
    assert plan.nrt == sum(nks)
    seen = {}
    for c in range(plan.nchunk):
        base = D["PL_CHUNK"] + c * D["PL_CSTRIDE"]
        used = int(plan.words[base])
        n = bin(used).count("1")
        assert n <= 10 and used == (1 << n) - 1
        for s in range(n):
            rid, b, p, nv = (int(v) for v in plan.words[base + 1 + 4 * s: base + 5 + 4 * s])
            assert plan.rows[rid] == (b, p) and nv == min(32, lengths[b] - 32 * p)
            seen.setdefault(b, set()).add(p)
    assert all(seen[b] == set(range(nks[b])) for b in range(len(lengths)))
    ids = [list(range(1000, 1000 + n)) for n in lengths]
    e = np.zeros((plan.nrt * 32, 416), np.float32)
    P.fill_e(plan, ids, he, e)
    assert e[:, 384:].sum() == sum(lengths)
    m = next(m for m, (b, p) in enumerate(plan.rows) if (b, p) == (1, 3))
    assert np.allclose(e[m * 32 + 5, :384], he.rows(ids[1])[3 * 32 + 5])
    with pytest.raises(ValueError):
        P.build_plan([257], 5, 0, 0)
    with pytest.raises(ValueError):
        P.build_plan([2] * 33, 5, 0, 0)


def test_mask_tiles():
    from tt_minilm.tt.mk import program as P

    m = P.mask_tiles().reshape(32, 32, 32)
    assert (m[5, 0, :5] == 0).all() and (m[5, 0, 5:] == -1e9).all() and (m[5, 1:] == 0).all()


def test_config_env():
    from tt_minilm import config as C

    c = C.resolve_config({"MINILM_ENGINE": "ttnn", "MINILM_MAX_BATCH": "8", "MINILM_SEQ_BUCKETS": "64,256"})
    assert c.engine == "ttnn" and c.max_batch == 8 and c.seq_buckets == (64, 256)
    for bad in ({"MINILM_MAX_BATCH": "33"}, {"MINILM_ENGINE": "gpu"}, {"MINILM_SEQ_BUCKETS": "40"},
                {"MINILM_MAX_SEQ_LEN": "300"}, {"MINILM_TRACE": "maybe"}):
        with pytest.raises(ValueError):
            C.resolve_config(bad)
    assert C.resolve_config({}).engine == "mk"
    json.dumps(C.resolve_config({}).as_dict())


def test_tilize_roundtrip_and_face_order():
    from tt_minilm.tt.mk import program as P

    a = np.arange(64 * 96, dtype=np.float32).reshape(64, 96)
    t = P.tilize(a)
    assert t.shape == (6, 1024)
    assert np.array_equal(P.untilize(t, 2, 3), a)
    tile = a[32:64, 32:64]            # tile (1, 1) -> row 1 * 3 + 1
    faces = np.concatenate([tile[:16, :16].ravel(), tile[:16, 16:].ravel(), tile[16:, :16].ravel(),
                            tile[16:, 16:].ravel()])
    assert np.array_equal(t[4], faces)