File size: 3,568 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""DEC diagnosis on realistic taps: run an ENC engine (mk or ttnn) once on a golden case, then decode the SAME device
taps with mk_dec, ttnn_dec and the float32 CPU reference decoder; report each decoder vs the reference decode of
those taps (pure DEC error) and the end-to-end metrics vs the golden. Saves the tensors under
assets/depthpro2/mk_dec_emu/diag_<case>__<size>_<enc>.pt.

    bin/devrun -t 1200 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_dec_diag.py --size L \
        --case img_375x500_pad --enc mk
"""

from __future__ import annotations

import argparse
import os
import sys

import torch

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))

from tt_depthpro2.reference import model as R  # noqa: E402
from tt_depthpro2.tests import baseline_helpers as BH  # noqa: E402
from tt_depthpro2.tt import StageShape  # noqa: E402
from tt_depthpro2.tt.weights import unfold_patches  # noqa: E402


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--size", default="L")
    ap.add_argument("--case", default="img_375x500_pad")
    ap.add_argument("--enc", default="mk")
    args = ap.parse_args()
    torch.set_num_threads(8)
    import ttnn

    from tt_depthpro2.tt import mk_dec, ttnn_dec
    from tt_depthpro2.tt.model import engine_class

    w = R.load_safetensors(os.path.join(BH.size_dir(args.size), "model.safetensors"))
    g, _ = BH.load_golden(args.case, args.size)
    x0 = g["x_norm"]
    t, _, h, wd = x0.shape
    x = R.pad_to_multiple(x0)
    hp, wp = x.shape[-2:]
    shape = StageShape(t, hp, wp)
    dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH),
                           l1_small_size=32768, trace_region_size=16 << 20)
    try:
        E = engine_class("enc", args.enc)
        enc = E(dev, E.prepare_weights(dev, w, args.size), shape)
        p = unfold_patches(x, shape.np_).reshape(1, 1, -1, 768).to(torch.bfloat16)
        patches = ttnn.from_torch(p, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev,
                                  memory_config=ttnn.DRAM_MEMORY_CONFIG)
        taps = enc.run(patches)
        taps_h = [ttnn.to_torch(tp).float().reshape(t, shape.np_, -1)[:, :shape.n] for tp in taps]
        dm = mk_dec.Engine(dev, mk_dec.Engine.prepare_weights(dev, w, args.size), shape)
        inv_mk = ttnn.to_torch(dm.run(taps)).float().reshape(t, hp, wp)
        dt = ttnn_dec.Engine(dev, ttnn_dec.Engine.prepare_weights(dev, w, args.size), shape)
        inv_tt = ttnn.to_torch(dt.run(taps)).float().reshape(t, hp, wp)
    finally:
        ttnn.close_device(dev)
    ref = R.DepthPro2Reference(args.size, w)
    with torch.no_grad():
        inv_ref = ref.decode(taps_h, (shape.gh, shape.gw))[:, 0]
    gold = g["inverse_depth"].reshape(t, h, wd)
    out = {"inv_mk": inv_mk, "inv_tt": inv_tt, "inv_ref": inv_ref, "taps": taps_h}
    path = os.path.join(BH.ROOT, f"assets/depthpro2/mk_dec_emu/diag_{args.case}__{args.size}_{args.enc}.pt")
    torch.save(out, path)
    for nm, v in (("mk_dec", inv_mk), ("ttnn_dec", inv_tt), ("ref_dec", inv_ref)):
        st = BH.drift_metrics(v[:, :h, :wd], inv_ref[:, :h, :wd])
        e2e = BH.drift_metrics(v[:, :h, :wd], gold)
        print(f"{nm:8s} vs ref decode of the same taps: pcc {st['pcc']:.7f} absrel {st['absrel_valid']:.5f} | "
              f"vs golden: pcc {e2e['pcc']:.6f} absrel {e2e['absrel_valid']:.5f}", flush=True)
    print(f"saved {path}")


if __name__ == "__main__":
    main()