File size: 5,165 Bytes
c147de1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Device check of the plan, step by step (run under bin/devrun):

    python -m tt_visionpilot.tests.dev_plan [--nets autosteer autospeed autodrive] [--sample 0] [--json OUT]

For each network: the plan on the p150 (eager) against the same plan on the host in fp32 (``RowsNumpy``), every
step's outputs compared (PCC, max |diff|, relative L2); then the host tail on the device cut tensors against the
onnxruntime golden of the published file; then the eager time of a second run (synchronised).
"""
from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

import numpy as np

from ..graph import Graph
from ..host.rows_numpy import RowsNumpy
from ..models import NETWORKS
from ..plan import Plan


def pcc(a: np.ndarray, b: np.ndarray) -> float:
    a = np.asarray(a, np.float64).ravel()
    b = np.asarray(b, np.float64).ravel()
    if a.std() == 0 or b.std() == 0:
        return 1.0 if np.allclose(a, b) else 0.0
    return float(np.corrcoef(a, b)[0, 1])


def rel_l2(a: np.ndarray, b: np.ndarray) -> float:
    return float(np.linalg.norm(np.asarray(a, np.float64) - b) / max(np.linalg.norm(b), 1e-30))


def main(argv=None) -> int:
    import ttnn

    from ..tt.backend import TtBackend
    from ..ttaw.device import close_device, describe_device, open_device

    ap = argparse.ArgumentParser()
    ap.add_argument("--nets", nargs="*", default=list(NETWORKS))
    ap.add_argument("--data", default="/weights/port")
    ap.add_argument("--sample", type=int, default=0)
    ap.add_argument("--weight-terms", type=int, default=1)
    ap.add_argument("--json", default=None)
    ap.add_argument("--show", type=int, default=12, help="worst steps to print")
    args = ap.parse_args(argv)

    dev = open_device(0, dispatch="eth", num_command_queues=1, l1_small_size=32768, trace_region_size=64 << 20,
                      allow_fallback=False)
    print(json.dumps(describe_device(dev)))
    report = {}
    try:
        for name in args.nets:
            spec = NETWORKS[name]
            g = Graph(Path(args.data) / "folded" / f"{name}.onnx")
            z = np.load(Path(args.data) / "golden" / f"{name}.npz")
            plan = Plan(g, spec)
            feeds_np = {k: z[f"{args.sample}/in/{k}"] for k in spec.inputs}
            ref = {}
            host = RowsNumpy()
            plan.run(host, {k: host.input_map(v) for k, v in feeds_np.items()},
                     hook=lambda s, outs: ref.update({o: v for o, v in zip(s.outputs, outs)}))
            be = TtBackend(dev, weight_terms=args.weight_terms)
            rows = []

            def hook(s, outs):
                for o, v in zip(s.outputs, outs):
                    m = plan.meta[o]
                    if m[0] == "map":
                        got = be.to_nchw(v)
                        exp = host.to_nchw(ref[o], m)
                    else:
                        got = ttnn.to_torch(v).float().numpy().reshape(-1)[: m[1]]
                        exp = ref[o].reshape(-1)
                    rows.append({"step": s.index, "kind": s.kind, "out": o, "pcc": pcc(got, exp),
                                 "max_abs": float(np.abs(got - exp).max()), "rel_l2": rel_l2(got, exp),
                                 "ref_absmax": float(np.abs(exp).max())})

            t0 = time.time()
            cut = plan.run(be, {k: be.input_map(v) for k, v in feeds_np.items()}, hook=hook)
            t_first = time.time() - t0
            cut_np = {c: be.to_nchw(cut[c]) for c in spec.cut}
            outs = plan.run_tail(cut_np)
            final = {o: {"rel_l2": rel_l2(outs[o], z[f"{args.sample}/out/{o}"]),
                         "max_abs": float(np.abs(outs[o] - z[f"{args.sample}/out/{o}"]).max()),
                         "pcc": pcc(outs[o], z[f"{args.sample}/out/{o}"])} for o in g.outputs}
            for v in cut.values():
                be.release(v)
            # second eager run, timed (no per-step reads)
            feeds = {k: be.input_map(v) for k, v in feeds_np.items()}
            ttnn.synchronize_device(dev)
            t0 = time.time()
            cut = plan.run(be, feeds)
            ttnn.synchronize_device(dev)
            t_eager = time.time() - t0
            for v in cut.values():
                be.release(v)
            worst = sorted(rows, key=lambda r: r["pcc"])[: args.show]
            print(f"== {name}: {len(plan.steps)} steps, first run {t_first:.1f} s, eager {t_eager * 1e3:.1f} ms")
            for r in worst:
                print(f"   step {r['step']:3d} {r['kind']:10s} {r['out'][:28]:28s} pcc {r['pcc']:.6f} "
                      f"max|d| {r['max_abs']:.4g} relL2 {r['rel_l2']:.3g} (|ref| {r['ref_absmax']:.3g})")
            for o, f in final.items():
                print(f"   output {o}: relL2 {f['rel_l2']:.4g} max|d| {f['max_abs']:.4g} pcc {f['pcc']:.6f}")
            report[name] = {"steps": rows, "final": final, "eager_ms": t_eager * 1e3, "first_s": t_first}
    finally:
        close_device(dev)
    if args.json:
        Path(args.json).write_text(json.dumps(report, indent=1))
    return 0


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