File size: 5,194 Bytes
e91e989
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""DPOOL bring-up probe (OPT2 round 4 R4.4; hang protocol: smallest shapes first, eager x2, then a 2-call trace).

``tt.dpool.quadrants`` + the fp32 adds against the port's avgpool2 chain of ``depth_mean`` (untilize, ROW_MAJOR
slices of the row pairs, tilizes, add, untilize, reshape to column pairs, slices, tilizes, add, x0.25) on fp32 TILE maps
``[n*h*w, C]``: the pooled maps must be bit-identical (and equal to the numpy quadrant sum in the same order).
``--scale frame``: the depth logits' 8 x 108 x 192 x 64. Traced timings of both forms are printed.

    METEOR_DEVICE_OK=1 bin/devrun -t 300 -- python -u code/scripts/dpool_probe.py --scale small
"""
from __future__ import annotations

import argparse
import sys
import time

import numpy as np

SMALL = [("1x2x64x32", 1, 2, 64, 32), ("2x4x128x64", 2, 4, 128, 64), ("1x2x64x40", 1, 2, 64, 40)]
FRAME = [("depth", 8, 108, 192, 64)]


def stock_pool(ttnn, t, n, h, w, nb):
    from tt_meteor.tt.layers import rm, tile

    x = ttnn.reshape(rm(t), (n * h // 2, 2 * w, nb))
    a = ttnn.add(tile(ttnn.slice(x, [0, 0, 0], [n * h // 2, w, nb])),
                 tile(ttnn.slice(x, [0, w, 0], [n * h // 2, 2 * w, nb])))
    b = ttnn.reshape(rm(a), (n * h // 2, w // 2, 2 * nb))
    ttnn.deallocate(a, False)
    s = ttnn.add(tile(ttnn.slice(b, [0, 0, 0], [n * h // 2, w // 2, nb])),
                 tile(ttnn.slice(b, [0, 0, nb], [n * h // 2, w // 2, 2 * nb])))
    return ttnn.multiply(ttnn.reshape(s, (1, 1, n * h * w // 4, nb)), 0.25)


def kernel_pool(ttnn, t, n, h, w, nb):
    from tt_meteor.tt.dpool import quadrants

    q00, q01, q10, q11 = quadrants(t, n, h, w)
    a0 = ttnn.add(q00, q10)
    a1 = ttnn.add(q01, q11)
    for q in (q00, q01, q10, q11):
        ttnn.deallocate(q)
    s = ttnn.add(a0, a1)
    ttnn.deallocate(a0)
    ttnn.deallocate(a1)
    out = ttnn.multiply(s, 0.25)
    ttnn.deallocate(s)
    return out


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--scale", default="small", choices=("small", "frame"))
    ap.add_argument("--trace", action="store_true")
    ap.add_argument("--reps", type=int, default=5)
    a = ap.parse_args()

    import torch
    import ttnn

    from tt_meteor.tt.dpool import quadrants, supported
    from tt_meteor.ttaw.device import open_device

    dev = open_device(dispatch="eth", trace_region_size=64 << 20)
    rng = np.random.default_rng(0)
    bad = 0

    def host(t):
        return ttnn.to_torch(t).float().numpy().reshape(-1, int(t.shape[-1]))

    for name, n, h, w, c in (SMALL if a.scale == "small" else FRAME):
        x = (rng.normal(size=(n, h, w, c)) * 10.0 ** rng.integers(-3, 3, (n, h, w, c))).astype(np.float32)
        x.reshape(-1)[::11] = -0.0
        t = ttnn.from_torch(torch.from_numpy(x.reshape(1, 1, n * h * w, c)), dtype=ttnn.float32,
                            layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)
        assert supported(t, n, h, w), name
        # the quadrants themselves vs numpy (pure data movement: exact)
        qs = quadrants(t, n, h, w)
        for k, q in enumerate(qs):
            dy, dx = k >> 1, k & 1
            want = x[:, dy::2, dx::2, :].reshape(-1, c)
            ok = np.array_equal(host(q).view(np.uint32), want.view(np.uint32))
            bad += not ok
            print(f"[{name}] q{dy}{dx}: {'identical' if ok else 'DIFFERENT'}", flush=True)
            ttnn.deallocate(q)
        ref = host(stock_pool(ttnn, t, n, h, w, c))
        for i in range(2):
            y = kernel_pool(ttnn, t, n, h, w, c)
            ok = np.array_equal(host(y).view(np.uint32), ref.view(np.uint32))
            bad += not ok
            print(f"[{name}] eager{i + 1}: {'identical' if ok else 'DIFFERENT'} vs the stock chain", flush=True)
            ttnn.deallocate(y)
        if a.trace:
            for mode, fn in (("kernel", kernel_pool), ("stock", stock_pool)):
                box = {}

                def body():
                    box["y"] = fn(ttnn, t, n, h, w, c)

                body()
                ttnn.deallocate(box["y"])
                tid = ttnn.begin_trace_capture(dev, cq_id=0)
                body()
                ttnn.end_trace_capture(dev, tid, cq_id=0)
                for i in range(2):
                    ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
                    ok = np.array_equal(host(box["y"]).view(np.uint32), ref.view(np.uint32))
                    bad += not ok
                    print(f"  {mode} trace{i}: {'identical' if ok else 'DIFFERENT'}", flush=True)
                ts = []
                for _ in range(a.reps):
                    t0 = time.perf_counter()
                    ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
                    ts.append((time.perf_counter() - t0) * 1e3)
                print(f"  {mode}: traced ms p50 {np.median(ts):.3f} min {min(ts):.3f}", flush=True)
                ttnn.release_trace(dev, tid)
                ttnn.deallocate(box["y"])
        ttnn.deallocate(t)
    ttnn.close_device(dev)
    print("ALL IDENTICAL" if bad == 0 else f"{bad} DIFFERENT")
    return 0 if bad == 0 else 1


if __name__ == "__main__":
    sys.exit(main())