File size: 11,139 Bytes
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
7b01b36
 
31ffdfe
 
 
 
7b01b36
31ffdfe
7b01b36
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Device check of the extended ``msda`` kernel against a numpy emulation (bin/devrun).

    bin/devrun python -m tt_autoe2e.tests.dev_msda_unit

Cases: (1) the AutoE2E cross-attention form: 8 heads, 6 value-map segments of unequal size read from a runtime table
(two different tables replayed on the same program), the merged sampling projection layout (``loc_hs`` 64 with the
level's ``loc_off``), the level's point columns inside the 32-column softmax block (``att_col0``); (2) the t1
self-attention form: 16 head blocks (head x queue entry) sharing 8 value maps (``hdiv`` 2), 4 points, ``loc_hs`` 8.
Pass: relative L2 error below 4e-3 (bf16 values and output) on every case.
"""
from __future__ import annotations

import json

import numpy as np


def bilinear_np(m, x, y):
    """m [h, w, 32]; x, y pixel coordinates (align_corners=False pixel centres at integers), zero padding."""
    h, w, _ = m.shape
    x0 = np.floor(x).astype(np.int64)
    y0 = np.floor(y).astype(np.int64)
    fx, fy = x - x0, y - y0
    out = np.zeros(x.shape + (32,), np.float64)
    for dy, wy in ((0, 1 - fy), (1, fy)):
        for dx, wx in ((0, 1 - fx), (1, fx)):
            xi, yi = x0 + dx, y0 + dy
            ok = (xi >= 0) & (xi < w) & (yi >= 0) & (yi < h)
            v = m[np.clip(yi, 0, h - 1), np.clip(xi, 0, w - 1)] * ok[..., None]
            out += v * (wx * wy)[..., None]
    return out


def emulate(value, locq, attn, *, heads, points, seg_rows, hdiv, map_of_head):
    """value [N, h, w, 32]; locq [rows, heads, points, 2] (Q16.16 ints); attn [rows, heads, points] -> [rows, heads*32]."""
    rows = locq.shape[0]
    out = np.zeros((rows, heads * 32), np.float64)
    ends = np.cumsum(seg_rows)
    seg = np.searchsorted(ends, np.arange(rows), side="right")
    seg = np.minimum(seg, len(seg_rows) - 1)
    nseg = len(seg_rows)
    for j in range(heads):
        for s in range(nseg):
            r = np.nonzero(seg == s)[0]
            if r.size == 0:
                continue
            m = value[map_of_head(j) * nseg + s].astype(np.float64)
            px = locq[r, j, :, 0] / 65536.0
            py = locq[r, j, :, 1] / 65536.0
            smp = bilinear_np(m, px, py)                       # [R, P, 32]
            out[r, j * 32:(j + 1) * 32] = (smp * attn[r, j, :, None]).sum(1)
    return out


def rel(a, b):
    return float(np.linalg.norm(a - b) / max(np.linalg.norm(b), 1e-30))


def main() -> int:
    import torch
    import ttnn
    from ..tt.msda_k import msda
    from ..tt.pairmap import pair_maps
    from ..ttaw.device import DeviceConfig, close_device

    rng = np.random.default_rng(0)
    dev = DeviceConfig(trace_region_size=32 << 20).open()
    res = {}
    try:
        # ---------------- (1) SCA form
        heads, P, h, w, cap = 8, 8, 32, 32, 2048
        bf = lambda a: torch.from_numpy(a).to(torch.bfloat16).float().numpy()
        value = bf(rng.standard_normal((heads * 6, h, w, 32)).astype(np.float32))
        vdev = ttnn.from_torch(torch.from_numpy(value), dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT,
                               device=dev, memory_config=ttnn.L1_MEMORY_CONFIG)
        for case, seg_rows in (("sca_a", [640, 320, 352, 224, 160, 352]), ("sca_b", [832, 288, 288, 96, 64, 480])):
            assert sum(seg_rows) == cap
            loc = rng.uniform(-3, w + 2, size=(cap, heads, 4, P, 2))        # 4 levels' worth of columns
            locq = np.round(loc * 65536).astype(np.int32)
            logits = rng.standard_normal((cap, heads, 32)).astype(np.float32)
            att = np.exp(logits - logits.max(-1, keepdims=True))
            att = (att / att.sum(-1, keepdims=True)).astype(np.float32)   # softmax over 4 levels x 8 points
            loc_dev = ttnn.from_torch(torch.from_numpy(locq.reshape(1, 1, cap, heads * 64)), dtype=ttnn.int32,
                                      layout=ttnn.TILE_LAYOUT, device=dev)
            att_dev = ttnn.from_torch(torch.from_numpy(att.reshape(cap, heads, 32).transpose(1, 0, 2)[None].copy()),
                                      dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev)
            ends = np.zeros((1, 1, 1, 16), np.uint32)
            ends[0, 0, 0, :6] = np.cumsum(seg_rows) // 32
            seg_dev = ttnn.from_torch(torch.from_numpy(ends.astype(np.int64)).to(torch.int32), dtype=ttnn.uint32,
                                      layout=ttnn.ROW_MAJOR_LAYOUT, device=dev)
            # the same maps as pixel pairs, built on the device from the value-projection layout
            proj = value.reshape(heads, 6, h * w, 32).transpose(1, 2, 0, 3).reshape(1, 1, 6 * h * w, heads * 32)
            pdev = ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(proj)), dtype=ttnn.bfloat16,
                                   layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.L1_MEMORY_CONFIG)
            pairs = pair_maps(pdev, heads=heads, sub=6, hw=(h, w))
            quads = pair_maps(pdev, heads=heads, sub=6, hw=(h, w), quad=True)
            ttnn.deallocate(pdev)
            for lvl in (0, 3):
                exp = emulate(value, locq[:, :, lvl], att[:, :, 8 * lvl:8 * lvl + 8], heads=heads, points=P,
                              seg_rows=seg_rows, hdiv=1, map_of_head=lambda j: j)
                outs = {}
                for tag, v in (("", vdev), ("_pairs", pairs), ("_quads", quads)):
                    out = msda(v, loc_dev, att_dev, points=P, nq=cap, segments=[0] * 6, seg_table=seg_dev,
                               loc_hs=64, loc_off=16 * lvl, att_col0=8 * lvl)
                    got = ttnn.to_torch(out).float().numpy().reshape(cap, heads * 32)
                    res[f"{case}_level{lvl}{tag}"] = rel(got, exp)
                    outs[tag] = got
                    ttnn.deallocate(out)
                # quads read the same sticks as pairs: identical outputs (a nonzero entry here fails the test)
                res[f"{case}_level{lvl}_quads_vs_pairs_max_abs"] = float(np.abs(outs["_quads"] - outs["_pairs"]).max())
            # joint softmax over a head's 32 logits + fp32 offsets with the anchor table added in the kernel
            logits = rng.standard_normal((cap, heads, 32)).astype(np.float32)
            e = np.exp(logits - logits.max(-1, keepdims=True))
            jsm = (e / e.sum(-1, keepdims=True)).astype(np.float32)
            basef = (rng.uniform(-1, w, size=(cap, 4, P, 2)) * 65536).astype(np.float32)        # [R, level, p, xy]
            offf = (rng.uniform(-2, 2, size=(cap, heads, 4, P, 2)) * 65536).astype(np.float32)
            locj = (np.round(offf.astype(np.float64)) + np.round(basef.astype(np.float64))[:, None]).astype(np.int32)
            lg_dev = ttnn.from_torch(torch.from_numpy(logits.reshape(1, 1, cap, heads * 32)), dtype=ttnn.float32,
                                     layout=ttnn.TILE_LAYOUT, device=dev)
            off_dev = ttnn.from_torch(torch.from_numpy(offf.reshape(1, 1, cap, heads * 64)), dtype=ttnn.float32,
                                      layout=ttnn.TILE_LAYOUT, device=dev)
            base_dev = ttnn.from_torch(torch.from_numpy(basef.reshape(1, 1, cap, 64)), dtype=ttnn.float32,
                                       layout=ttnn.TILE_LAYOUT, device=dev)
            jw_dev = ttnn.from_torch(torch.from_numpy(jsm.transpose(1, 0, 2)[None].copy()), dtype=ttnn.float32,
                                     layout=ttnn.TILE_LAYOUT, device=dev)
            for lvl in (0, 1, 2, 3):
                exp = emulate(value, locj[:, :, lvl], jsm[:, :, 8 * lvl:8 * lvl + 8], heads=heads, points=P,
                              seg_rows=seg_rows, hdiv=1, map_of_head=lambda j: j)
                # weights given (head split), positions = fp32 offsets + the anchor table in the kernel
                out = msda(pairs, off_dev, jw_dev, points=P, nq=cap, segments=[0] * 6, seg_table=seg_dev, loc_hs=64,
                           loc_off=16 * lvl, att_col0=8 * lvl, base=base_dev)
                got = ttnn.to_torch(out).float().numpy().reshape(cap, heads * 32)
                res[f"{case}_level{lvl}_base"] = rel(got, exp)
                ttnn.deallocate(out)
            ttnn.deallocate(jw_dev)
            for t in (lg_dev, off_dev, base_dev):
                ttnn.deallocate(t)
            ttnn.deallocate(pairs)
            ttnn.deallocate(quads)
            for t in (loc_dev, att_dev, seg_dev):
                ttnn.deallocate(t)
        ttnn.deallocate(vdev)
        # ---------------- (2) TSA form: 16 head blocks over 8 maps, 4 points, loc_hs 8
        hb, P, h, w, q = 16, 4, 30, 20, 600
        value = bf(rng.standard_normal((8, h, w, 32)).astype(np.float32))
        vdev = ttnn.from_torch(torch.from_numpy(value), dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT,
                               device=dev, memory_config=ttnn.L1_MEMORY_CONFIG)
        loc = rng.uniform(-2, max(h, w) + 1, size=(q, hb, P, 2))
        locq = np.round(loc * 65536).astype(np.int32)
        att = rng.uniform(0, 1, size=(q, hb, P)).astype(np.float32)
        att_full = np.zeros((1, hb, q, 32), np.float32)
        att_full[0, :, :, :P] = att.transpose(1, 0, 2)
        loc_dev = ttnn.from_torch(torch.from_numpy(locq.reshape(1, 1, q, hb * 8)), dtype=ttnn.int32,
                                  layout=ttnn.TILE_LAYOUT, device=dev)
        att_dev = ttnn.from_torch(torch.from_numpy(att_full), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev)
        out = msda(vdev, loc_dev, att_dev, points=P, nq=q, sub=1, hdiv=2, loc_hs=8)
        got = ttnn.to_torch(out).float().numpy().reshape(q, hb * 32)[:q]
        exp = emulate(value, locq, att, heads=hb, points=P, seg_rows=[q], hdiv=2, map_of_head=lambda j: j // 2)
        res["tsa"] = rel(got, exp)
        # the same with pair maps and the in-kernel softmax over each block's 4 compact logits
        logits = rng.standard_normal((q, hb, P)).astype(np.float32)
        e = np.exp(logits - logits.max(-1, keepdims=True))
        sm = (e / e.sum(-1, keepdims=True)).astype(np.float32)
        lg_dev = ttnn.from_torch(torch.from_numpy(logits.reshape(1, 1, q, hb * P)), dtype=ttnn.float32,
                                 layout=ttnn.TILE_LAYOUT, device=dev)
        proj = value.transpose(1, 2, 0, 3).reshape(1, 1, h * w, 8 * 32)
        pdev = ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(proj)), dtype=ttnn.bfloat16,
                               layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.L1_MEMORY_CONFIG)
        pairs = pair_maps(pdev, heads=8, sub=1, hw=(h, w))
        out = msda(pairs, loc_dev, lg_dev, points=P, nq=q, sub=1, hdiv=2, loc_hs=8, softmax=True)
        got = ttnn.to_torch(out).float().numpy().reshape(-1, hb * 32)[:q]
        exp = emulate(value, locq, sm, heads=hb, points=P, seg_rows=[q], hdiv=2, map_of_head=lambda j: j // 2)
        res["tsa_pairs_softmax"] = rel(got, exp)
    finally:
        close_device(dev)
    ok = all((v == 0.0 if k.endswith("_quads_vs_pairs_max_abs") else v < 4e-3) for k, v in res.items())
    print(json.dumps(res, indent=1))
    print("PASS" if ok else "FAIL")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())