File size: 5,438 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
#!/usr/bin/env python3
"""OPT2 MK4 follow-up probe (stock ops only, OPT_PLAN A7): a full-resolution ConvBlock (3x3 conv + ReLU twice, bf16
weights at HiFi2 as the ``fast`` profile's BEV trunk) run as row bands whose two convs take ttnn's L1 path
(``Conv2dL1FullSliceConfig``) instead of two DRAM-sliced convs (each with its PaddedSlice / Halo / Move / Untilize /
SliceWrite glue per slice). A band [r0, r1) slices input rows [r0 - 2, r1 + 2) (the two convs' halo), runs both
convs, keeps output rows [r0, r1) and the bands are concatenated. Prints traced times and the output difference
against the DRAM-sliced chain.

    METEOR_DEVICE_OK=1 bin/devrun -t 900 -- python -u code/scripts/bandchain_probe.py --bands 4,5,8
"""
from __future__ import annotations

import argparse
import sys
import time

import numpy as np

FAST = "HiFi2+fp32+l1acc:w=bfloat16"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--hw", default="800,500")
    ap.add_argument("--ch", default="96,96,96", help="Cin, Cmid, Cout")
    ap.add_argument("--bands", default="4,5,8")
    ap.add_argument("--reps", type=int, default=10)
    ap.add_argument("--layout", default="rm", choices=("rm", "t4"), help="input layout of the map")
    a = ap.parse_args()
    h, w = (int(v) for v in a.hw.split(","))
    c0, c1, c2 = (int(v) for v in a.ch.split(","))

    import torch
    import ttnn

    from tt_meteor.ttaw.device import open_device
    from tt_meteor.ttaw.ops.conv import Conv2d, FeatureMap

    dev = open_device(dispatch="eth", trace_region_size=128 << 20)
    rng = np.random.default_rng(0)
    x = rng.standard_normal((1, h, w, c0)).astype(np.float32)
    wa = (rng.standard_normal((c1, c0, 3, 3)) / np.sqrt(9 * c0)).astype(np.float32)
    wb = (rng.standard_normal((c2, c1, 3, 3)) / np.sqrt(9 * c1)).astype(np.float32)
    ba = (rng.standard_normal(c1) * 0.3).astype(np.float32)
    bb = (rng.standard_normal(c2) * 0.3).astype(np.float32)
    lay = ttnn.ROW_MAJOR_LAYOUT if a.layout == "rm" else ttnn.TILE_LAYOUT
    xd = ttnn.from_torch(torch.from_numpy(x).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=lay, device=dev,
                         memory_config=ttnn.DRAM_MEMORY_CONFIG)
    cfg = {"config_tensors_in_dram": True}

    def mk(wt, bt, slicing, out_layout):
        return Conv2d(wt, bt, stride=1, padding=1, activation="relu", precision=FAST, output_dtype="bfloat16",
                      output_layout=out_layout, slicing=slicing, conv_config=cfg, name="c")

    sa, sb = mk(wa, ba, "auto", "row_major"), mk(wb, bb, "auto", "row_major")

    def stock():
        ya = sa(FeatureMap(xd, 1, h, w, c0))
        yb = sb(ya)
        ttnn.deallocate(ya.tensor)
        return yb.tensor

    la, lb = mk(wa, ba, "l1", "tile"), mk(wb, bb, "l1", "tile")

    def banded(nb):
        br = -(-h // nb)
        parts = []
        for k in range(nb):
            r0, r1 = k * br, min(h, k * br + br)
            if r0 >= r1:
                break
            lo, hi = max(0, r0 - 2), min(h, r1 + 2)
            xb = ttnn.slice(xd, [0, lo, 0, 0], [1, hi, w, c0], memory_config=ttnn.DRAM_MEMORY_CONFIG)
            ya = la(FeatureMap(xb, 1, hi - lo, w, c0))
            ttnn.deallocate(xb)
            yb = lb(ya)
            ttnn.deallocate(ya.tensor)
            t = yb.tensor
            if t.memory_config().buffer_type != ttnn.BufferType.DRAM or t.is_sharded():
                t2 = ttnn.to_memory_config(t, ttnn.DRAM_MEMORY_CONFIG)
                ttnn.deallocate(t)
                t = t2
            keep = ttnn.slice(t, [0, 0, (r0 - lo) * w, 0], [1, 1, (r0 - lo + r1 - r0) * w, c2],
                              memory_config=ttnn.DRAM_MEMORY_CONFIG)
            ttnn.deallocate(t)
            parts.append(keep)
        out = ttnn.concat(parts, dim=2, memory_config=ttnn.DRAM_MEMORY_CONFIG)
        for p in parts:
            ttnn.deallocate(p)
        return out

    def run(fn):
        o = fn()
        r = ttnn.to_torch(o).float().numpy().reshape(h, w, c2)
        ttnn.deallocate(o)
        return r

    def timed(fn):
        fn_out = fn()
        ttnn.deallocate(fn_out)
        tid = ttnn.begin_trace_capture(dev, cq_id=0)
        o = fn()
        ttnn.end_trace_capture(dev, tid, cq_id=0)
        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)
        r = ttnn.to_torch(o).float().numpy().reshape(h, w, c2)
        ttnn.release_trace(dev, tid)
        ttnn.deallocate(o)
        return r, float(np.median(ts))

    ref = run(stock)
    rs, ts = timed(stock)
    print(f"stock DRAM-sliced chain [{h}x{w} {c0}->{c1}->{c2}, {a.layout} input]: traced {ts:.3f} ms, "
          f"traced == eager {np.array_equal(rs, ref)}", flush=True)
    for nb in (int(v) for v in a.bands.split(",")):
        try:
            y = run(lambda: banded(nb))
        except RuntimeError as e:
            print(f"bands {nb}: FAILED to run ({str(e).splitlines()[0][:200]})", flush=True)
            continue
        d = np.abs(y - ref)
        _, tb = timed(lambda: banded(nb))
        print(f"bands {nb}: traced {tb:.3f} ms (stock {ts:.3f}); vs stock: identical {np.array_equal(y, ref)}, "
              f"max|d| {float(d.max()):.4g}, mismatches {int(np.count_nonzero(d))}", flush=True)
    ttnn.close_device(dev)
    return 0


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