File size: 5,165 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 | # SPDX-License-Identifier: Apache-2.0
"""Where ``msda_cm``'s time goes (bin/devrun): the real inputs of layer 1's cross-attention on the golden frame
(captured while the encoder runs), the kernel timed as is and with parts switched off (debug defines; the outputs of
those are wrong by design, only the times matter):
- ``rdnone``: the reader hands over the pages without work (compute alone); ``cpnone``: the compute consumes them
without work (reader alone); ``noread``: no value reads;
- with ``rdnone``: ``now`` (no weights), ``notl`` (no tilize), ``nomul`` (no product),
``nosteps``;
- ``new_hifi3``: HiFi3 products (compared with the HiFi4 output).
bin/devrun python -m tt_autoe2e.tests.dev_cm_probe [--out /logs/x.json] [--variants a,b,..]
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import time
import numpy as np
CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"
VARIANTS = {
"new": (),
"new_hifi3": ("fid:HiFi3",),
"rdnone": ("rdnone",),
"cpnone": ("cpnone",),
"cpnone_noread": ("cpnone", "noread"),
"rdnone_cpnone": ("rdnone", "cpnone"),
"rdnone_now": ("rdnone", "now"),
"rdnone_notl": ("rdnone", "notl"),
"rdnone_nomul": ("rdnone", "nomul"),
"rdnone_nosteps": ("rdnone", "nosteps"),
}
EXACT = ("new", "new_hifi3")
def main(argv=None) -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="/logs/cm_probe.json")
ap.add_argument("--variants", default=",".join(VARIANTS))
ap.add_argument("--reps", type=int, default=5)
args = ap.parse_args(argv)
import torch
import ttnn
from ..host.geometry import bev_geometry
from ..reference.tree import load_tree
from ..tt import encoder as E
from ..tt.encoder import TtBevEncoder
from ..ttaw.device import DeviceConfig, close_device
names = [v for v in args.variants.split(",") if v]
gpath = glob.glob("/ae2e/ref/autoe2e_kitscenes_epoch5_*f000045.npz")[0]
g = np.load(gpath)
inter = np.load(gpath.replace(".npz", "_intermediates.npz"))
tree = load_tree(CKPT)
geo = bev_geometry(g["camera_projection_matrix"][0], 512)
feats = [inter[f"fpn_current_l{i}"] for i in range(4)]
res = {"variants_ms": {}, "exact_vs_new": {}}
dev = DeviceConfig(trace_region_size=64 << 20).open()
orig = E.msda_cm
state = {"n": 0}
def run(maps, loc, att, table, dbg):
fid = next((d[4:] for d in dbg if d.startswith("fid:")), None)
dbg = tuple(d for d in dbg if not d.startswith("fid:"))
old = os.environ.get("AE_MSDA_FIDELITY")
if fid:
os.environ["AE_MSDA_FIDELITY"] = fid
try:
return orig(maps, loc, att, table, debug=dbg)
finally:
if fid:
if old is None:
os.environ.pop("AE_MSDA_FIDELITY", None)
else:
os.environ["AE_MSDA_FIDELITY"] = old
def variants(maps, loc, att, table):
ref = None
for name in names:
dbg = VARIANTS[name]
o = run(maps, loc, att, table, dbg)
ttnn.synchronize_device(dev)
if name in EXACT:
a = ttnn.to_torch(o).float().numpy()
if name == "new":
ref = a
elif ref is not None:
d = np.abs(a - ref)
res["exact_vs_new"][name] = {"identical": bool(np.array_equal(a, ref)),
"max_abs": float(d.max()),
"rel_l2": float(np.linalg.norm(a - ref) / np.linalg.norm(ref))}
ttnn.deallocate(o)
ts = []
for _ in range(args.reps):
t = time.perf_counter()
o = run(maps, loc, att, table, dbg)
ttnn.synchronize_device(dev)
ts.append(time.perf_counter() - t)
ttnn.deallocate(o)
res["variants_ms"][name] = round(float(np.median(ts)) * 1e3, 3)
print(name, res["variants_ms"][name], "ms", flush=True)
def hook(maps, loc, att, table, **kw):
state["n"] += 1
if state["n"] == 2: # layer 1: offsets / weights from the real query
variants(maps, loc, att, table)
return orig(maps, loc, att, table, **kw)
try:
enc = TtBevEncoder(dev, tree)
up = lambda a: ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a, np.float32)), dtype=ttnn.bfloat16,
layout=ttnn.TILE_LAYOUT, device=dev)
levels = [up(f.transpose(0, 2, 3, 1).reshape(1, 1, -1, 256)) for f in feats]
gd = enc.upload_geometry(geo)
E.msda_cm = hook
out = enc.frame(levels, gd)
ttnn.synchronize_device(dev)
ttnn.deallocate(out)
finally:
E.msda_cm = orig
close_device(dev)
with open(args.out, "w") as f:
json.dump(res, f, indent=1)
print(json.dumps(res, indent=1))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|