File size: 5,902 Bytes
ca1a504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""CPU emulation (fp32 torch) of the device SAM / CLIP algorithm (token orders, one-hot permutations, rel-pos folded
into augmented q' / k', masked windows, clip row placement) against the clean-room reference: checks the host-side
constants of tt/vision_consts.py. Needs the DeepSeek-OCR weights (skipped when absent)."""

from __future__ import annotations

import os
import sys

import pytest
import torch
import torch.nn.functional as F

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.tt import vision_consts as VC  # noqa: E402
from tt_dsocr.tests._paths import MODELS  # noqa: E402

WP = MODELS["deepseek-ocr"]
pytestmark = pytest.mark.skipif(not os.path.isdir(WP), reason="weights not present")


def attn_aug(qa, ka, v, cu=None, kmask=None):
    """softmax(qa ka^T) v per head; cu: window boundaries (segments attend within themselves)."""
    if cu is None:
        return (qa @ ka.transpose(-1, -2)).softmax(-1) @ v
    out = torch.zeros(*qa.shape[:-1], v.shape[-1])
    for k in range(1, len(cu)):
        a, b = cu[k - 1], cu[k]
        out[..., a:b, :] = (qa[..., a:b, :] @ ka[..., a:b, :].transpose(-1, -2)).softmax(-1) @ v[..., a:b, :]
    return out


def emulate_sam(W, px, v):
    p = R.PFX + "sam_model."
    x = VC.patches_window(px, v) @ W.get(p + "patch_embed.proj.weight").reshape(768, -1).t() + W.get(
        p + "patch_embed.proj.bias")
    x = x + VC.pos_window(W, v)
    rm = VC.rowmask_window(v)
    Pw2g, Pg2w = VC.perm_w2g(v), VC.perm_g2w(v)
    Maug = VC.window_mask_aug(v)
    Kw = VC.window_kaug(v)
    Kg = VC.global_kaug(v)
    cu = [c for c in VC.window_cu(v)]
    cu = sorted(set(cu))
    order = "w"
    for i in range(12):
        b = p + f"blocks.{i}."
        glob = i in R.SAM_GLOBAL
        if glob and order == "w":
            x = Pw2g @ x
            order = "g"
        if not glob and order == "g":
            x = Pg2w @ x
            order = "w"
        h = F.layer_norm(x, (768,), W.get(b + "norm1.weight"), W.get(b + "norm1.bias"), eps=1e-6)
        if not glob:
            h = h * rm
        qkv = h @ W.get(b + "attn.qkv.weight").t() + W.get(b + "attn.qkv.bias")
        q, k, vv = qkv.view(-1, 3, 12, 64).permute(1, 2, 0, 3)  # [12, N, 64]
        q = q / VC.QSCALE  # the device folds 1 / 8 into the q rows (tables carry x 8)
        if not glob:
            Wa, Sa = VC.window_aug(W, v, i)
            qa = ((q @ Wa) * Maug) @ Sa
            ka = torch.cat([k, Kw[None].expand(12, -1, -1)], -1)
            o = attn_aug(qa, ka, vv, cu)
        else:
            RhT, RwT = VC.global_rel(W, v, i)
            q4 = q.reshape(12, v.B, v.g, v.G32, 64).reshape(12 * v.B, v.g, v.G32, 64)
            rh = q4 @ RhT[None]  # [12B, g, G32 (qw), G32 (kh)]
            q4t = q4.transpose(1, 2)  # [12B, G32 (qw), g (qh), 64]
            rw = (q4t @ RwT[None]).transpose(1, 2)  # [12B, g, G32, G32 (kw)]
            one = torch.zeros(12 * v.B, v.g, v.G32, 32)
            one[..., 0] = 1.0
            qa = torch.cat([q4, rh, rw, one], -1).reshape(12, v.B, v.g * v.G32, -1)
            ka = torch.cat([k, Kg[None].expand(12, -1, -1)], -1).reshape(12, v.B, v.g * v.G32, -1)
            vb = vv.reshape(12, v.B, v.g * v.G32, 64)
            o = attn_aug(qa, ka, vb).reshape(12, -1, 64)
        o = o.permute(1, 0, 2).reshape(-1, 768)
        x = x + o @ W.get(b + "attn.proj.weight").t() + W.get(b + "attn.proj.bias")
        h = F.layer_norm(x, (768,), W.get(b + "norm2.weight"), W.get(b + "norm2.bias"), eps=1e-6)
        h = F.gelu(h @ W.get(b + "mlp.lin1.weight").t() + W.get(b + "mlp.lin1.bias"))
        x = x + h @ W.get(b + "mlp.lin2.weight").t() + W.get(b + "mlp.lin2.bias")
    if v.G32 != v.g:
        x = VC.perm_g2r(v) @ x
    return x.reshape(v.B, v.g, v.g, 768)


@pytest.mark.parametrize("S,B", [(512, 1), (640, 2)])
def test_sam_blocks_emulation(S, B):
    torch.manual_seed(0)
    W = R.Weights(WP)
    v = VC.view_geom(S, B)
    px = torch.rand(B, 3, S, S) * 2 - 1
    st = {}
    ref = R.sam(W, px, st)  # neck output; compare the block-11 residual
    emu = emulate_sam(W, px, v)
    blk = st["sam_block11"]
    err = (emu - blk).abs().max() / blk.abs().max()
    assert err < 1e-4, float(err)


def test_clip_placement():
    W = R.Weights(WP)
    v = VC.view_geom(640, 2)
    torch.manual_seed(0)
    sam_out = torch.randn(2, 1024, v.gs, v.gs)
    ref = R.clip_l(W, sam_out)  # [B, 1 + n, 1024] (cls first)
    tok = sam_out.flatten(2).transpose(1, 2).reshape(-1, 1024)
    x = VC.clip_place(v) @ tok + VC.clip_const(W, v)
    p = R.PFX + "vision_model."
    x = F.layer_norm(x, (1024,), W.get(p + "pre_layrnorm.weight"), W.get(p + "pre_layrnorm.bias"), eps=1e-5)
    m = VC.clip_mask(v)
    x = x.view(v.B, v.Sc, 1024)
    for i in range(24):
        b = p + f"transformer.layers.{i}."
        y = F.layer_norm(x, (1024,), W.get(b + "layer_norm1.weight"), W.get(b + "layer_norm1.bias"), eps=1e-5)
        qkv = y @ W.get(b + "self_attn.qkv_proj.weight").t() + W.get(b + "self_attn.qkv_proj.bias")
        q, k, vv = qkv.view(v.B, v.Sc, 3, 16, 64).unbind(2)
        o = F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), vv.transpose(1, 2), attn_mask=m)
        x = x + o.transpose(1, 2).reshape(v.B, v.Sc, 1024) @ W.get(b + "self_attn.out_proj.weight").t() + W.get(
            b + "self_attn.out_proj.bias")
        y = F.layer_norm(x, (1024,), W.get(b + "layer_norm2.weight"), W.get(b + "layer_norm2.bias"), eps=1e-5)
        y = y @ W.get(b + "mlp.fc1.weight").t() + W.get(b + "mlp.fc1.bias")
        y = y * torch.sigmoid(1.702 * y)
        x = x + y @ W.get(b + "mlp.fc2.weight").t() + W.get(b + "mlp.fc2.bias")
    got = x[:, :v.n]
    exp = ref[:, 1:]
    err = (got - exp).abs().max() / exp.abs().max()
    assert err < 1e-4, float(err)