File size: 9,472 Bytes
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Per-op device time of one encoder layer (layer 1) on random BEV rows (bin/devrun): every ttnn op of the layer
outside the two attention kernels, each run eagerly and synchronized (median of N), plus alternative forms
(L1 outputs, sharded L1 row stages) for the same ops.

    bin/devrun python -m tt_autoe2e.tests.dev_layer_ops [--out /logs/x.json]
"""
from __future__ import annotations

import argparse
import json
import time

import numpy as np

CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"


def main(argv=None) -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default="/logs/layer_ops.json")
    ap.add_argument("--reps", type=int, default=7)
    ap.add_argument("--sweep", action="store_true")
    ap.add_argument("--skip-ops", action="store_true")
    args = ap.parse_args(argv)
    import torch
    import ttnn

    from ..reference.port_form import HEADS, Q
    from ..reference.tree import load_tree
    from ..tt.encoder import TtBevEncoder, linear_l1
    from ..ttaw.device import DeviceConfig, close_device

    tree = load_tree(CKPT)
    dev = DeviceConfig(trace_region_size=64 << 20).open()
    res = {}
    try:
        enc = TtBevEncoder(dev, tree)
        L = enc.layers[1]
        rng = np.random.default_rng(0)
        up = lambda a, dt=ttnn.bfloat16, mc=ttnn.DRAM_MEMORY_CONFIG: ttnn.from_torch(
            torch.from_numpy(np.ascontiguousarray(a, np.float32)), dtype=dt, layout=ttnn.TILE_LAYOUT, device=dev,
            memory_config=mc)
        q = up(rng.standard_normal((1, 1, Q, 256)))
        q2 = up(rng.standard_normal((1, 1, Q, 256)))
        h512 = up(rng.standard_normal((1, 1, Q, 512)))
        f512 = up(rng.standard_normal((1, 1, Q, 512)), ttnn.float32)
        f256 = up(rng.standard_normal((1, 1, Q, 256)), ttnn.float32)
        f128 = up(rng.standard_normal((1, 1, Q, 128)), ttnn.float32)

        def timed(name, fn):
            o = fn()
            ttnn.synchronize_device(dev)
            outs = o if isinstance(o, (list, tuple)) else [o]
            for x in outs:
                ttnn.deallocate(x)
            ts = []
            for _ in range(args.reps):
                t = time.perf_counter()
                o = fn()
                ttnn.synchronize_device(dev)
                ts.append(time.perf_counter() - t)
                outs = o if isinstance(o, (list, tuple)) else [o]
                for x in outs:
                    ttnn.deallocate(x)
            res[name] = round(float(np.median(ts)) * 1e3, 3)
            print(f"{name:40s} {res[name]:8.3f} ms", flush=True)

        timed("noop_sync", lambda: ttnn.add(q, q2, memory_config=ttnn.DRAM_MEMORY_CONFIG))
        run_op = timed if not args.skip_ops else (lambda name, fn: None)
        # ---- TSA
        run_op("tsa.off linear 256->128 fp32", lambda: L.tsa_off(q))
        run_op("tsa.off add const fp32", lambda: ttnn.add(f128, L.tsa_off_dev, memory_config=ttnn.DRAM_MEMORY_CONFIG))
        run_op("tsa.off typecast int32 [Q,128]", lambda: ttnn.typecast(f128, ttnn.int32))
        run_op("tsa.att linear 256->64 fp32", lambda: L.tsa_att(q))
        run_op("tsa.v linear L1", lambda: linear_l1(L.tsa_v, q))
        run_op("tsa.out linear 512->256", lambda: L.tsa_out(h512))
        # ---- SCA
        run_op("sca.off linear 256->512 fp32", lambda: L.sca_off(q))
        run_op("sca.off typecast int32 [Q,512]", lambda: ttnn.typecast(f512, ttnn.int32))
        run_op("sca.att linear 256->256 fp32", lambda: L.sca_att(q))
        run_op("sca.att heads [Q,256]->[8,Q,32] fp32", lambda: enc._heads(f256, HEADS))
        lh = enc._heads(f256, HEADS)
        run_op("sca.att softmax fp32 [8,Q,32]", lambda: ttnn.softmax(lh, dim=-1, compute_kernel_config=enc.cfg))
        ttnn.deallocate(lh)
        run_op("sca.out linear 256->256", lambda: L.sca_out(q))
        # ---- LN / FFN
        run_op("ln residual", lambda: L.norms[1](q2, residual=q, cfg=enc.cfg))
        run_op("ffn1 256->512 relu", lambda: L.ffn1(q))
        run_op("ffn2 512->256", lambda: L.ffn2(h512))
        # ---- references for the memory-traffic floor
        run_op("copy [Q,256] bf16 dram->dram", lambda: ttnn.clone(q, memory_config=ttnn.DRAM_MEMORY_CONFIG))
        run_op("copy [Q,512] fp32 dram->dram", lambda: ttnn.clone(f512, memory_config=ttnn.DRAM_MEMORY_CONFIG))
        def sweep():
            # ---- explicit matmul program configs (the same math: K blocks accumulate in fp32 DEST / L1)
            g = dev.compute_with_storage_grid_size()
            gx, gy = int(g.x), int(g.y)
            M = -(-Q // 32)

            def pc1d(K, N, ibw, obh, sbh, sbw, act=None):
                pcm = -(-M // (gx * gy))
                return ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig(
                    compute_with_storage_grid_size=ttnn.CoreCoord(gx, gy), in0_block_w=ibw, out_subblock_h=sbh,
                    out_subblock_w=sbw, out_block_h=obh, out_block_w=N, per_core_M=pcm, per_core_N=N, fuse_batch=True,
                    fused_activation=act, mcast_in0=False)

            def pc2d(K, N, ibw, nx, obh, sbh, sbw, act=None):
                pcn = N // nx
                pcm = -(-M // gy)
                return ttnn.MatmulMultiCoreReuseMultiCastProgramConfig(
                    compute_with_storage_grid_size=ttnn.CoreCoord(nx, gy), in0_block_w=ibw, out_subblock_h=sbh,
                    out_subblock_w=sbw, out_block_h=obh, out_block_w=pcn, per_core_M=pcm, per_core_N=pcn,
                    transpose_mcast=False, fused_activation=act)

            relu = ttnn.UnaryWithParam(ttnn.UnaryOpType.RELU)
            cases = [("sca.off", L.sca_off, q, 8, 16, ttnn.float32, None),
                     ("sca.att", L.sca_att, q, 8, 8, ttnn.float32, None),
                     ("sca.out", L.sca_out, q, 8, 8, ttnn.bfloat16, None),
                     ("ffn1", L.ffn1, q, 8, 16, ttnn.bfloat16, relu),
                     ("ffn2", L.ffn2, h512, 16, 8, ttnn.bfloat16, None),
                     ("tsa.out", L.tsa_out, h512, 16, 8, ttnn.bfloat16, None),
                     ("tsa.off", L.tsa_off, q, 8, 4, ttnn.float32, None)]
            for name, lin, x, K, N, odt, act in cases:
                w, b, grid, cfg = lin._device or lin._upload(dev)
                cands = []
                for ibw in (2, 4, 8):
                    if K % ibw:
                        continue
                    for obh in (2, 4, 8, 16):
                        sbw = min(N, 4)
                        while N % sbw:
                            sbw -= 1
                        sbh = max(1, 4 // sbw)
                        while obh % sbh:
                            sbh -= 1
                        cands.append((f"1d ibw{ibw} obh{obh} sb{sbh}x{sbw}", pc1d(K, N, ibw, obh, sbh, sbw, act)))
                for nx in (2, 4, 8):
                    if N % nx:
                        continue
                    pcn = N // nx
                    pcm = -(-M // gy)
                    for ibw in (2, 4, 8):
                        if K % ibw:
                            continue
                        for obh in (2, 4, 8):
                            if pcm % obh:
                                continue
                            sbw = min(pcn, 4)
                            while pcn % sbw:
                                sbw -= 1
                            sbh = max(1, 4 // sbw)
                            while obh % sbh:
                                sbh -= 1
                            cands.append((f"2d nx{nx} ibw{ibw} obh{obh} sb{sbh}x{sbw}",
                                          pc2d(K, N, ibw, nx, obh, sbh, sbw, act)))
                for cname, pc in cands:
                    try:
                        timed(f"{name} {cname}", lambda: ttnn.linear(x, w, bias=b, program_config=pc,
                                                                     compute_kernel_config=cfg, dtype=odt,
                                                                     memory_config=ttnn.DRAM_MEMORY_CONFIG))
                    except Exception as e:  # noqa: BLE001 - invalid configs are part of the sweep
                        res[f"{name} {cname}"] = f"error: {str(e).splitlines()[0][:120]}"
                        print(name, cname, "error", flush=True)
                ref = lin(x)
                best = min((k for k in res if k.startswith(name + " ") and isinstance(res[k], float)), key=res.get,
                           default=None)
                if best is not None:
                    cname = best[len(name) + 1:]
                    pc = dict(cands)[cname]
                    o = ttnn.linear(x, w, bias=b, program_config=pc, compute_kernel_config=cfg, dtype=odt,
                                    memory_config=ttnn.DRAM_MEMORY_CONFIG)
                    a, r = ttnn.to_torch(o).float().numpy(), ttnn.to_torch(ref).float().numpy()
                    res[f"{name} best"] = {"config": cname, "ms": res[best], "identical_to_default": bool(np.array_equal(a, r)),
                                           "max_abs": float(np.abs(a - r).max())}
                    print(name, "best", res[f"{name} best"], flush=True)
                    ttnn.deallocate(o)
                ttnn.deallocate(ref)

        if args.sweep:
            sweep()
    finally:
        close_device(dev)
    with open(args.out, "w") as f:
        json.dump(res, f, indent=1)
    return 0


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