File size: 9,221 Bytes
9b1a077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# SPDX-License-Identifier: Apache-2.0
"""Host test of the Unlimited-OCR-2 device engine LOGIC (tt/ttnn_dash.py on top of tt/ttnn_decoder.py) on a torch
fake ttnn (tests/fake_ttnn_torch.py): a 2-layer, 8-expert model with random weights through the engine's prefill
(per-layer host routing, block-bias mask expansion, masked SDPA, KV seeding) and decode steps (page2d coordinates,
router caches, masked SDPA decode over the KV capacity) vs the clean-room reference (reference/uocr2.py) on the same
weights. bf16 rounding of the fake makes them differ slightly; the routing and the logits must agree."""

from __future__ import annotations

import os
import sys

import pytest
import torch

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
from tt_dsocr.reference import model as R  # noqa: E402
from tt_dsocr.reference import uocr2 as U  # noqa: E402
from tt_dsocr.tests import fake_ttnn_torch as FT  # noqa: E402

NE_SMALL, VOCAB_SMALL, NL_SMALL = 8, 512, 2


class FakeW:
    def __init__(self, seed=0):
        g = torch.Generator().manual_seed(seed)
        rn = lambda *s, std=0.02: torch.randn(*s, generator=g) * std  # noqa: E731
        D, P = R.D, R.PFX
        t = {P + "embed_tokens.weight": rn(VOCAB_SMALL, D, std=0.5), "lm_head.weight": rn(VOCAB_SMALL, D, std=0.05),
             P + "norm.weight": 1 + rn(D, std=0.1)}
        for l in range(NL_SMALL):
            p = P + f"layers.{l}."
            t[p + "input_layernorm.weight"] = 1 + rn(D, std=0.1)
            t[p + "post_attention_layernorm.weight"] = 1 + rn(D, std=0.1)
            for n in ("q", "k", "v", "o"):
                t[p + f"self_attn.{n}_proj.weight"] = rn(D, D, std=0.03)
            r = p + "self_attn.dash_router."
            t[r + "q_proj.weight"], t[r + "k_proj.weight"] = rn(128, D, std=0.03), rn(128, D, std=0.03)
            t[r + "q_norm.weight"], t[r + "k_norm.weight"] = rn(128, std=0.1), rn(128, std=0.1)
            t[r + "head_cls"] = rn(128, std=1.0)
            m = p + "mlp."
            if l == 0:
                t[m + "gate_proj.weight"], t[m + "up_proj.weight"] = rn(R.I_DENSE, D), rn(R.I_DENSE, D)
                t[m + "down_proj.weight"] = rn(D, R.I_DENSE)
            else:
                t[m + "gate.weight"] = rn(NE_SMALL, D, std=0.1)
                for e in range(NE_SMALL):
                    t[m + f"experts.{e}.gate_proj.weight"] = rn(R.I_MOE, D)
                    t[m + f"experts.{e}.up_proj.weight"] = rn(R.I_MOE, D)
                    t[m + f"experts.{e}.down_proj.weight"] = rn(D, R.I_MOE)
                t[m + "shared_experts.gate_proj.weight"] = rn(2 * R.I_MOE, D)
                t[m + "shared_experts.up_proj.weight"] = rn(2 * R.I_MOE, D)
                t[m + "shared_experts.down_proj.weight"] = rn(D, 2 * R.I_MOE)
        self.t = t

    def get(self, k, cache=True):
        return self.t[k]


def pcc(a, b):
    a, b = a.double().flatten(), b.double().flatten()
    a, b = a - a.mean(), b - b.mean()
    return float((a @ b) / (a.norm() * b.norm() + 1e-30))


@pytest.fixture
def fake_ttnn(monkeypatch):
    FT.install()
    monkeypatch.setattr(R, "NL", NL_SMALL)
    from tt_dsocr.tt import ttnn_decoder as TD

    monkeypatch.setattr(TD, "NE", NE_SMALL)
    monkeypatch.setattr(TD, "V", VOCAB_SMALL)
    yield FT
    FT.uninstall()


def test_dash_engine_matches_reference(fake_ttnn):
    torch.set_num_threads(2)
    from tt_dsocr.tt.ttnn_dash import TtnnDashDecoder

    W = FakeW()
    g = torch.Generator().manual_seed(5)
    # one page: BOS, <PAGE>, 273 image tokens, 4 instruction tokens -> 279 rows (bucket 384)
    ids = [0, U.PAGE_ID] + [U.IMAGE_ID] * 273 + [100, 101, 102, 103]
    L = len(ids)
    emb = W.get(R.PFX + "embed_tokens.weight")
    rows = emb[torch.tensor([i if i < VOCAB_SMALL else 7 for i in ids])].clone()
    img = torch.tensor(ids) == U.IMAGE_ID
    rows[img] = torch.randn(int(img.sum()), R.D, generator=g) * 0.5
    ref = U.UocrDecoder(W)
    lg_ref = ref.prefill(rows, ids)
    dec = TtnnDashDecoder(FT.FakeDevice(), W, [384], max_seq=1024)
    dec.prefill(rows, L, ids=ids)
    lg = dec.logits_host()
    assert lg.shape[-1] == VOCAB_SMALL
    assert pcc(lg, lg_ref) > 0.995, pcc(lg, lg_ref)
    # decode: the first output token is <PAGE> (switches the coordinates / candidate domain), then text tokens;
    # ids >= the small vocab are not embeddable here, so <PAGE> is fed as a tiny id with the PAGE coordinate rule
    # exercised through the router state directly
    toks = [U.PAGE_ID] + [200 + i for i in range(60)]
    worst = 1.0
    for s, t in enumerate(toks):
        lr = ref.step(t) if t < VOCAB_SMALL else _ref_step_page(ref, t)
        _dev_step(dec, t, L + s)
        ld = dec.logits_host()
        worst = min(worst, pcc(ld, lr))
    assert worst > 0.99, worst
    # after the generated <PAGE> the decode candidates are page 0's image blocks (the official decode state)
    assert dec.router.allow is not None and bool(dec.router.allow[:8].all()) and not bool(dec.router.allow[9:].any())


def _ref_step_page(ref, t):
    """reference step with a token id outside the small vocab: embed row 7 (same as the device fake below)."""
    emb = ref.embed

    def emb7(ids):
        return emb([7 if i >= VOCAB_SMALL else i for i in ids])

    ref.embed = emb7
    try:
        return ref.step(t)
    finally:
        ref.embed = emb


def _dev_step(dec, t, pos):
    """device step; a token outside the small vocab is embedded as row 7 (the router still sees the real id)."""
    if t < VOCAB_SMALL:
        dec.step(t, pos)
        return
    real = dec._pre

    def pre7(i, x):
        if i == 0:
            dec.ttnn.copy_host_to_device_tensor(dec.ttnn.from_torch(torch.tensor([[7]], dtype=torch.int32),
                                                                    dtype=dec.ttnn.uint32,
                                                                    layout=dec.ttnn.ROW_MAJOR_LAYOUT), dec._tok)
        return real(i, x)

    dec._pre = pre7
    try:
        dec.step(t, pos)
    finally:
        dec._pre = real


def test_prompt_rows_places_every_page():
    """DsocrDevice.prompt_rows of a two-page Unlimited-OCR-2 prompt: each page's image rows (its own views through
    the vision engine) land at that page's span; the text rows are the embedding rows."""
    import types

    import numpy as np

    from tt_dsocr import frontend as FE
    from tt_dsocr.tt import model as M

    class Vis:
        def run(self, px):
            px = torch.as_tensor(px)
            # rows tagged with the view's mean pixel value (page-distinct)
            return torch.full((px.shape[0], 256, R.D), float(px.mean()))

    class Tok:
        def encode(self, s):
            return [FE.PAGE_TOKEN_ID] if s == FE.PAGE_TOKEN else [100 + len(s) % 7]

    pages = []
    for v in (0.25, -0.5):
        im = (np.full((600, 500, 3), int((v * 0.5 + 0.5) * 255), np.uint8))
        from PIL import Image

        pages.append(Image.fromarray(im))
    prep = FE.prepare_pages(FE.UOCR2, Tok(), pages, "", None)
    assert prep.mode == "base" and len(prep.extra["pages"]) == 2
    dev = M.DsocrDevice.__new__(M.DsocrDevice)
    dev.variant = FE.UOCR2
    dev.vis = Vis()
    sep, nl = torch.full((R.D,), 7.0), torch.full((R.D,), 9.0)
    dev.W = types.SimpleNamespace(get=lambda k, cache=True: sep if k.endswith("view_seperator") else nl)
    dev.embed = torch.zeros(129280, R.D, dtype=torch.bfloat16)
    rows = dev.prompt_rows(prep)
    assert rows.shape[0] == len(prep.ids)
    for pg in prep.extra["pages"]:
        s0, s1 = pg["image_pos"]
        assert s1 - s0 == 273
        blk = rows[s0:s1]
        val = float(torch.as_tensor(pg["global_px"]).mean())
        body = blk[:-1].view(16, 17, R.D)
        assert torch.allclose(body[:, :16], torch.full_like(body[:, :16], val))
        assert torch.all(body[:, 16] == 9.0) and torch.all(blk[-1] == 7.0)
    txt = torch.ones(len(prep.ids), dtype=torch.bool)
    for pg in prep.extra["pages"]:
        txt[pg["image_pos"][0]:pg["image_pos"][1]] = False
    assert torch.all(rows[txt] == 0)
    assert prep.ids.count(FE.PAGE_TOKEN_ID) == 2


def test_sparse_moe_decode_equals_dense(fake_ttnn):
    """TtnnDecoder(sparse_decode=True): the decode MoE over the 6 gathered experts (prefix-count slot assignment,
    ttnn.embedding row gathers, column matmuls) == the dense masked MoE, step after step."""
    torch.set_num_threads(2)
    from tt_dsocr.tt.ttnn_decoder import TtnnDecoder

    W = FakeW(seed=3)
    g = torch.Generator().manual_seed(9)
    L = 40
    rows = torch.randn(L, R.D, generator=g) * 0.5
    outs = []
    for sparse in (False, True):
        dec = TtnnDecoder(FT.FakeDevice(), W, [64], max_seq=256, sparse_decode=sparse)
        dec.prefill(rows, L)
        lg = [dec.logits_host()]
        for s, t in enumerate([5, 17, 300, 42, 8, 99, 250, 3]):
            dec.step(t, L + s)
            lg.append(dec.logits_host())
        outs.append(torch.stack(lg))
    assert torch.equal(outs[0][0], outs[1][0])                 # prefill is the same dense path
    assert (outs[0] - outs[1]).abs().max() < 2e-2 * outs[0].abs().max(), (outs[0] - outs[1]).abs().max()
    assert pcc(outs[0][1:], outs[1][1:]) > 0.9999