File size: 3,734 Bytes
7a24154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Bit-identity across knob settings (OPT round 4): run every catalogued public frame of one profile, the PandaSet
sample and the shipped synthetic sample through every trace that holds it (the full-capacity trace and each
FRNET_BUCKETS trace) and store, per frame and trace, the SHA-256 of the valid rows of ``pred_probs`` (fp32 bytes)
and their argmax (``--out`` .npz). Run it once per knob setting (the
knobs are read at build), then compare the archives with ``--compare A.npz B.npz`` (no device).

    bin/devrun -t 1200 -- env FRNET_P2P=0 python -u code/scripts/diag/dump_outputs.py --variant ot128 --out a.npz
    bin/devrun -t 1200 -- env FRNET_P2P=1 python -u code/scripts/diag/dump_outputs.py --variant ot128 --out b.npz
    python code/scripts/diag/dump_outputs.py --compare a.npz b.npz
"""
from __future__ import annotations

import argparse
import hashlib
import json
import sys

import numpy as np

sys.path.insert(0, __file__.rsplit("/scripts/", 1)[0])


def compare(a_path: str, b_path: str) -> int:
    a, b = np.load(a_path), np.load(b_path)
    keys = sorted({k[:-4] for k in set(a.files) | set(b.files) if k.endswith(".sha")})
    bad = 0
    for k in keys:
        if k + ".sha" not in a.files or k + ".sha" not in b.files:
            print(f"{k}: missing in {'A' if k + '.sha' not in a.files else 'B'}")
            bad += 1
            continue
        same = bytes(a[k + ".sha"]) == bytes(b[k + ".sha"])
        bad += 0 if same else 1
        x, y = a[k + ".arg"], b[k + ".arg"]
        print(f"{k}: n {x.shape[0]} bit-identical {same}, argmax agreement {float((x == y).mean()) * 100:.4f} %")
    print(f"COMPARED {len(keys)} MISMATCHES {bad}")
    return bad


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--variant", default="ot128")
    ap.add_argument("--out")
    ap.add_argument("--compare", nargs=2)
    a = ap.parse_args()
    if a.compare:
        sys.exit(1 if compare(*a.compare) else 0)
    from tt_frnet import FRNet
    from tt_frnet.host.preprocess import build_plan
    from tt_frnet.tests import _data

    out = {}
    with FRNet.from_pretrained(variant=a.variant) as model:
        print("knobs", json.dumps({k: str(v) for k, v in model.graph.knobs.items()}), flush=True)
        plans = {}
        for name, (_, _, var) in _data.FRAMES.items():
            if var != a.variant:
                continue
            inputs, _, _ = _data.load_frame(name)
            plans[name] = build_plan(inputs, model.config, pre_norm=(model.frnet_weights.pre_norm_scale,
                                                                     model.frnet_weights.pre_norm_shift))
        plans["pandaset_019_40"] = model._prepare(str(_data.SAMPLE), calibration=_data.SAMPLE_CALIB).plan
        plans["shipped"] = model._prepare(str(_data.shipped(a.variant)),
                                          calibration=_data.shipped_calib(a.variant)).plan
        with model._lock:
            for name, plan in plans.items():
                for bname, st in model.stagings:
                    if not st.fits(plan):
                        continue
                    got = np.asarray(model.runner(bname, inputs=st.write(plan)), np.float32)
                    rows = np.ascontiguousarray(got.reshape(-1, got.shape[-1])[: plan.n])
                    out[f"{name}@{bname}.sha"] = np.frombuffer(hashlib.sha256(rows.tobytes()).digest(), np.uint8)
                    out[f"{name}@{bname}.arg"] = rows.argmax(-1).astype(np.uint8)
                print(name, int(plan.n), model.select(plan)[0], flush=True)
    np.savez(a.out, **out)
    print("SAVED", len(out) // 2, a.out, flush=True)


if __name__ == "__main__":
    main()