File size: 6,773 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
#!/usr/bin/env python3
"""MK-TF bring-up probe (OPT2 second megakernel pass; hang protocol: smallest shape first, one core, eager x2, then a
2-call trace, then the model shape).

Stock (the ``fast`` path today, TGATE=kernel): the merged 1x1 conv with its gate rows as logit differences (fp32
[R, 128] output) -> ``tgate.fuse`` (bf16 t0, flat). MK-TF: ``tgate.fuse_mm`` on the bf16 map itself, flat or as
its 4-D TILE form (``--hw H,W``). Both against a float64 host reference; kernel vs stock agreement; eager x2; trace
x2; traced replays timed (stock: conv + TGATE (+ the untilize the temporal fuse block's ROW_MAJOR input needs);
kernel: one program).

    METEOR_DEVICE_OK=1 bin/devrun -t 300 -- python -u code/scripts/tfuse_probe.py --hw 1,32 --max-cores 1
    METEOR_DEVICE_OK=1 bin/devrun -t 300 -- python -u code/scripts/tfuse_probe.py --hw 4,40 --trace
    METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/tfuse_probe.py --hw 800,500 --trace
"""
from __future__ import annotations

import argparse
import sys
import time

import numpy as np

PORT_PRECISION = "HiFi4+fp32+l1acc:w=fp32"
SCALE = 4.0


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--hw", default="1,32", help="H,W of the map (H * W % 32 == 0 for the flat stock path)")
    ap.add_argument("--max-cores", type=int, default=0)
    ap.add_argument("--flat", action="store_true", help="also run the kernel on the flat form")
    ap.add_argument("--no-four", action="store_true", help="skip the 4-D form")
    ap.add_argument("--trace", action="store_true")
    ap.add_argument("--reps", type=int, default=10)
    ap.add_argument("--logit-scale", type=float, default=1.0)
    a = ap.parse_args()

    import torch
    import ttnn

    from tt_meteor.tt import tgate
    from tt_meteor.tt.layers import CONV_CONFIG
    from tt_meteor.ttaw.device import open_device
    from tt_meteor.ttaw.ops.conv import Conv2d, FeatureMap

    h, w_ = (int(v) for v in a.hw.split(","))
    r = h * w_
    assert r % 32 == 0, "H * W must be a multiple of 32"
    dev = open_device(dispatch="eth", trace_region_size=64 << 20)
    rng = np.random.default_rng(0)
    x = torch.from_numpy(rng.standard_normal((r, 96)).astype(np.float32)).bfloat16().float().numpy()
    w = (rng.standard_normal((100, 96)) * 0.1).astype(np.float32)
    w[96:] *= a.logit_scale
    b = np.concatenate([np.zeros(96), rng.standard_normal(4) * a.logit_scale]).astype(np.float32)
    bt = (rng.standard_normal(96) * 0.2).astype(np.float32)
    wd, bd = tgate.diff_weights(w.reshape(100, 96, 1, 1), b)
    g64 = x.astype(np.float64) @ w.T.astype(np.float64) + b
    lg = g64[:, 96:]
    sm = np.exp(lg - lg.max(1, keepdims=True))
    gate = sm[:, :1] / sm.sum(1, keepdims=True) * SCALE
    ref = np.maximum(g64[:, :96] * gate + bt, 0.0)

    def up(arr, dtype=ttnn.float32):
        return ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(arr)), dtype=dtype, layout=ttnn.TILE_LAYOUT,
                               device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)

    xt = up(x.reshape(1, 1, r, 96), ttnn.bfloat16)
    x4 = up(x.reshape(1, h, w_, 96), ttnn.bfloat16)
    print(f"[{h}x{w_}] x4 shape {list(x4.shape)} padded {list(x4.padded_shape)}; supported flat "
          f"{tgate.supported_mm(xt)} 4-D {tgate.supported_mm(x4)}", flush=True)
    fm = FeatureMap(xt, 1, h, w_, 96)
    c_diff = Conv2d(wd, bd, name="tgate.diff", precision=PORT_PRECISION, output_dtype="float32",
                    conv_config=CONV_CONFIG, padding=0)
    ones, bias = up(tgate.ones_tile()), up(tgate.bias_tiles(bt))
    wt, gb = up(tgate.weight_tiles(wd)), up(tgate.gate_bias_tiles(bd))
    bad = 0

    def host(t):
        return ttnn.to_torch(t).float().numpy().reshape(r, -1)

    def stock(xf, untilize=False):
        g = c_diff(FeatureMap(xf, 1, h, w_, 96)).tensor
        y = tgate.fuse(g, ones, bias, SCALE)
        ttnn.deallocate(g)
        if untilize:
            z = ttnn.to_layout(y, ttnn.ROW_MAJOR_LAYOUT)
            ttnn.deallocate(y)
            return z
        return y

    def kern(xin):
        return tgate.fuse_mm(xin, wt, ones, bias, gb, SCALE, max_cores=a.max_cores)

    ys = host(stock(xt))
    es = np.abs(ys - ref).max()
    forms = ([] if a.no_four else [("4-D", x4)]) + ([("flat", xt)] if a.flat else [])
    outs = {}
    for name, xin in forms:
        yk_t = kern(xin)
        print(f"  {name}: output {list(yk_t.shape)} padded {list(yk_t.padded_shape)}", flush=True)
        yk = host(yk_t)
        ek = np.abs(yk - ref).max()
        same = np.mean(ys == yk)
        dif = np.abs(yk - ys)
        ulp = dif / np.maximum(np.abs(ys), 1e-30) * 128
        print(f"  {name}: max|err| vs float64: stock {es:.4g}, kernel {ek:.4g} (max|ref| {np.abs(ref).max():.4g}); "
              f"kernel == stock {same:.5f}, max |diff| {dif.max():.4g} (~{ulp[ys != 0].max() if (ys != 0).any() else 0:.2f}"
              f" bf16 ulp); finite {np.isfinite(yk).all()}", flush=True)
        ok = bool(np.isfinite(yk).all() and ek <= max(1.5 * es, 1e-6))
        bad += 0 if ok else 1
        print(f"  {name}: kernel precision vs stock: {'OK' if ok else 'WORSE'}", flush=True)
        yk2 = host(kern(xin))
        ok2 = np.array_equal(yk, yk2)
        bad += 0 if ok2 else 1
        print(f"  {name}: kernel eager x2: {'stable' if ok2 else 'UNSTABLE'}", flush=True)
        outs[name] = yk
    if "4-D" in outs and "flat" in outs:
        okf = np.array_equal(outs["4-D"], outs["flat"])
        bad += 0 if okf else 1
        print(f"  4-D == flat: {'IDENTICAL' if okf else 'DIFFERENT'}", flush=True)

    if a.trace:
        cases = [("stock+untilize", lambda: stock(xt, untilize=True), None)]
        cases += [(f"kernel {n}", (lambda xin=xin: kern(xin)), outs[n]) for n, xin in forms]
        for name, fn, want in cases:
            ttnn.deallocate(fn())
            tid = ttnn.begin_trace_capture(dev, cq_id=0)
            y = 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 want is not None:
                    okt = np.array_equal(host(y), want)
                    bad += 0 if okt else 1
                    print(f"  {name} trace call {i + 1}: {'IDENTICAL' if okt else 'DIFFERENT'}", flush=True)
            ttnn.release_trace(dev, tid)
            print(f"  {name} traced replay p50 {np.median(ts):.3f} ms (min {np.min(ts):.3f})", flush=True)
    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())