File size: 8,560 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
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
#!/usr/bin/env python3
"""KTILE bring-up probe (hang protocol: smallest shape first, one core, eager x2, then a 2-call trace, then the
model shapes): ``tt.ktile.tilize`` against ``ttnn.to_layout(t, TILE_LAYOUT)`` bit for bit; traced replays timed.

    METEOR_DEVICE_OK=1 bin/devrun -t 300 -- python -u code/scripts/ktile_probe.py --shapes small --max-cores 1
    METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/ktile_probe.py --shapes model --trace
"""
from __future__ import annotations

import argparse
import sys
import time

import numpy as np

SMALL = ["1,4,40,64,bf16", "1,1,160,96,bf16", "1,4,40,48,fp32", "1,4,40,192,bf16", "1,2,100,96,bf16"]
MODEL = ["1,800,500,64,bf16", "1,1,400000,64,bf16", "1,400,250,192,bf16", "1,800,500,48,fp32", "1,1,400000,96,bf16",
         "1,800,500,96,bf16"]


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--shapes", default="small")
    ap.add_argument("--max-cores", type=int, default=0)
    ap.add_argument("--trace", action="store_true")
    ap.add_argument("--reps", type=int, default=10)
    a = ap.parse_args()

    import torch
    import ttnn

    from tt_meteor.tt import ktile
    from tt_meteor.ttaw.device import open_device

    specs = SMALL if a.shapes == "small" else MODEL if a.shapes == "model" else a.shapes.split(";")
    dev = open_device(dispatch="eth", trace_region_size=64 << 20)
    rng = np.random.default_rng(0)
    bad = 0
    for spec in specs:
        crop = None
        if spec.startswith("untile:"):                    # untile:<shape>,<dtype>: KUNTILE vs to_layout(RM)
            *dims, dt = spec[7:].split(",")
            shp = [int(v) for v in dims]
            tdt = ttnn.bfloat16 if dt == "bf16" else ttnn.float32
            x = torch.from_numpy(rng.standard_normal(shp).astype(np.float32))
            x = x.bfloat16() if dt == "bf16" else x
            t = ttnn.from_torch(x, dtype=tdt, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)
            if not ktile.supported_untilize(t):
                print(f"[{spec}] not supported", flush=True)
                bad += 1
                continue
            want = ttnn.to_torch(ttnn.to_layout(t, ttnn.ROW_MAJOR_LAYOUT)).float().numpy()
            y = ktile.untilize(t, max_cores=a.max_cores)
            got = ttnn.to_torch(y).float().numpy()
            got2 = ttnn.to_torch(ktile.untilize(t, max_cores=a.max_cores)).float().numpy()
            ok, ok2 = np.array_equal(got, want), np.array_equal(got, got2)
            bad += (0 if ok else 1) + (0 if ok2 else 1)
            print(f"[{spec}] kernel == to_layout(RM): {'IDENTICAL' if ok else 'DIFFERENT'}; eager x2 "
                  f"{'stable' if ok2 else 'UNSTABLE'}; layout {y.layout}", flush=True)
            if a.trace:
                for name, fn in (("to_layout", lambda: ttnn.to_layout(t, ttnn.ROW_MAJOR_LAYOUT)),
                                 ("kernel", lambda: ktile.untilize(t, max_cores=a.max_cores))):
                    ttnn.deallocate(fn())
                    tid = ttnn.begin_trace_capture(dev, cq_id=0)
                    o = fn()
                    ttnn.end_trace_capture(dev, tid, cq_id=0)
                    ts = []
                    for _ in range(max(2, a.reps)):
                        t0 = time.perf_counter()
                        ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
                        ts.append((time.perf_counter() - t0) * 1e3)
                    okt = np.array_equal(ttnn.to_torch(o).float().numpy(), want)
                    bad += 0 if okt else 1
                    ttnn.release_trace(dev, tid)
                    ttnn.deallocate(o)
                    print(f"    {name} traced replay p50 {np.median(ts):.3f} ms (min {np.min(ts):.3f}); traced output "
                          f"{'IDENTICAL' if okt else 'DIFFERENT'}", flush=True)
            ttnn.deallocate(t)
            continue
        if spec.startswith("crop:"):                      # crop:<shape>,<dtype>:r0,r1,c0,c1
            _, spec, cs = spec.split(":")
            crop = tuple(int(v) for v in cs.split(","))
        *dims, dt = spec.split(",")
        shp = [int(v) for v in dims]
        tdt = ttnn.bfloat16 if dt == "bf16" else ttnn.float32
        x = torch.from_numpy(rng.standard_normal(shp).astype(np.float32))
        if dt == "bf16":
            x = x.bfloat16()
        t = ttnn.from_torch(x, dtype=tdt, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)
        if not ktile.supported(t):
            print(f"[{spec}] not supported", flush=True)
            bad += 1
            continue
        if crop is not None:
            r0, r1, c0, c1 = crop
            sl = ttnn.slice(t, [0, r0, c0, 0], [1, r1, c1, shp[3]])
            want = ttnn.to_torch(ttnn.to_layout(sl, ttnn.TILE_LAYOUT)).float().numpy()
            y = ktile.tilize(t, crop=crop, max_cores=a.max_cores)
            got = ttnn.to_torch(y).float().numpy()
            got2 = ttnn.to_torch(ktile.tilize(t, crop=crop, max_cores=a.max_cores)).float().numpy()
            ok, ok2 = np.array_equal(got, want), np.array_equal(got, got2)
            bad += (0 if ok else 1) + (0 if ok2 else 1)
            print(f"[crop {spec} {crop}] kernel == slice + to_layout: {'IDENTICAL' if ok else 'DIFFERENT'}; eager x2 "
                  f"{'stable' if ok2 else 'UNSTABLE'}; padded {list(y.padded_shape)}", flush=True)
            if a.trace:
                for name, fn in (("slice+to_layout", lambda: ttnn.to_layout(
                                     ttnn.slice(t, [0, r0, c0, 0], [1, r1, c1, shp[3]]), ttnn.TILE_LAYOUT)),
                                 ("kernel", lambda: ktile.tilize(t, crop=crop, max_cores=a.max_cores))):
                    ttnn.deallocate(fn())
                    tid = ttnn.begin_trace_capture(dev, cq_id=0)
                    o = fn()
                    ttnn.end_trace_capture(dev, tid, cq_id=0)
                    ts = []
                    for _ in range(max(2, a.reps)):
                        t0 = time.perf_counter()
                        ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
                        ts.append((time.perf_counter() - t0) * 1e3)
                    ttnn.release_trace(dev, tid)
                    ttnn.deallocate(o)
                    print(f"    {name} traced replay p50 {np.median(ts):.3f} ms (min {np.min(ts):.3f})", flush=True)
            ttnn.deallocate(t)
            continue
        want = ttnn.to_torch(ttnn.to_layout(t, ttnn.TILE_LAYOUT)).float().numpy()
        y = ktile.tilize(t, max_cores=a.max_cores)
        got = ttnn.to_torch(y).float().numpy()
        ok = np.array_equal(got, want) and list(y.padded_shape) == list(ttnn.to_layout(t, ttnn.TILE_LAYOUT).padded_shape)
        got2 = ttnn.to_torch(ktile.tilize(t, max_cores=a.max_cores)).float().numpy()
        ok2 = np.array_equal(got, got2)
        bad += (0 if ok else 1) + (0 if ok2 else 1)
        # the padding: a matmul over the padded channel dimension sees zeros in both forms (ones row x tile map)
        print(f"[{spec}] kernel == to_layout: {'IDENTICAL' if ok else 'DIFFERENT'}; eager x2 {'stable' if ok2 else 'UNSTABLE'}; "
              f"padded {list(y.padded_shape)}", flush=True)
        if a.trace:
            for name, fn in (("to_layout", lambda: ttnn.to_layout(t, ttnn.TILE_LAYOUT)),
                             ("kernel", lambda: ktile.tilize(t, max_cores=a.max_cores))):
                ttnn.deallocate(fn())
                tid = ttnn.begin_trace_capture(dev, cq_id=0)
                o = fn()
                ttnn.end_trace_capture(dev, tid, cq_id=0)
                ts = []
                for i in range(max(2, a.reps)):
                    t0 = time.perf_counter()
                    ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
                    ts.append((time.perf_counter() - t0) * 1e3)
                    if i < 2 and name == "kernel":
                        okt = np.array_equal(ttnn.to_torch(o).float().numpy(), want)
                        bad += 0 if okt else 1
                        print(f"    kernel trace call {i + 1}: {'IDENTICAL' if okt else 'DIFFERENT'}", flush=True)
                ttnn.release_trace(dev, tid)
                ttnn.deallocate(o)
                print(f"    {name} traced replay p50 {np.median(ts):.3f} ms (min {np.min(ts):.3f})", flush=True)
        ttnn.deallocate(t)
    ttnn.close_device(dev)
    print("RESULT", "PASS" if bad == 0 else f"FAIL ({bad})")
    return 0 if bad == 0 else 1


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