File size: 5,533 Bytes
5c33f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Latency / throughput bench of the device engines (ONE device process). Per stage and bucket: end-to-end engine
call (host packing + upload + traced replay + readback) and replay-only time (trace executed back to back).

  bin/devrun -t 1200 --reset-on-timeout -- python -u bundles/embeddinggemma-2/code/scripts/bench.py \
      --stages text,image,audio --out logs/embgemma/bench/ttnn.json
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import time

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

import numpy as np  # noqa: E402

from tt_embgemma import model_spec as S  # noqa: E402

MODEL = None   # EMBGEMMA_WEIGHTS_DIR or the pinned snapshot in the HF cache (weights.resolve_model_dir)


def timeit(fn, iters):
    fn()
    t0 = time.perf_counter()
    for _ in range(iters):
        fn()
    return (time.perf_counter() - t0) / iters * 1e3


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--stages", default="text")
    ap.add_argument("--iters", type=int, default=20)
    ap.add_argument("--text-lens", default="16,32,64,128,256,512,1024,2048")
    ap.add_argument("--text-batches", default="8x64,32x64,8x256,32x16")
    ap.add_argument("--image-tokens", default="70,140,280")
    ap.add_argument("--audio-secs", default="1,5,10,30")
    ap.add_argument("--weights", default="bf16")
    ap.add_argument("--fidelity", default="HiFi4")
    ap.add_argument("--out", default="bench.json")
    args = ap.parse_args()
    stages = args.stages.split(",")
    if os.path.dirname(args.out):
        os.makedirs(os.path.dirname(args.out), exist_ok=True)

    import ttnn

    from tt_embgemma.device import close_device, describe_device, open_device
    from tt_embgemma.preprocess.image import Patches
    from tt_embgemma.tt.engine import EngineConfig, TtnnEngine
    from tt_embgemma.weights import load_state, resolve_model_dir

    comps = ["text"] + (["vision"] if "image" in stages else []) + (["audio"] if "audio" in stages else [])
    W = load_state(resolve_model_dir(MODEL), comps, skip_embed=True)
    mods = ("text",) + (("image", "video") if "image" in stages else ()) + (("audio",) if "audio" in stages else ())
    dev = open_device()
    res = {"args": vars(args), "device": describe_device(dev), "text": {}, "text_batch": {}, "image": {}, "audio": {}}
    eng = None
    rng = np.random.default_rng(0)
    try:
        cfg = EngineConfig(modalities=mods, weights=args.weights, fidelity=args.fidelity)
        eng = TtnnEngine(dev, W, cfg)
        eng.warmup()
        res["warmup"] = dict(cfg.stats)
        print("warmup", cfg.stats, flush=True)
        if "text" in stages:
            for n in [int(x) for x in args.text_lens.split(",") if x]:
                xs = [rng.standard_normal((n, S.HIDDEN)).astype(np.float32)]
                t1 = time.perf_counter()
                eng.text(xs)
                first = (time.perf_counter() - t1) * 1e3
                ms = timeit(lambda: eng.text(xs), args.iters)
                res["text"][n] = {"ms": round(ms, 3), "first_ms": round(first, 1)}
                print("text", n, f"{ms:.3f} ms", flush=True)
            for spec in [x for x in args.text_batches.split(",") if x]:
                b, n = (int(v) for v in spec.split("x"))
                xs = [rng.standard_normal((n, S.HIDDEN)).astype(np.float32) for _ in range(b)]
                eng.text(xs)
                ms = timeit(lambda: eng.text(xs), max(3, args.iters // 4))
                res["text_batch"][spec] = {"ms": round(ms, 3), "inputs_per_s": round(b / ms * 1e3, 1),
                                           "tokens_per_s": round(b * n / ms * 1e3, 0)}
                print("text batch", spec, f"{ms:.3f} ms", f"{b / ms * 1e3:.1f} inputs/s", flush=True)
        if "image" in stages:
            for t in [int(x) for x in args.image_tokens.split(",") if x]:
                side = int(np.sqrt(t)) * 3
                g = (side, side)
                n = side * side
                gx, gy = np.meshgrid(np.arange(side), np.arange(side), indexing="xy")
                pos = np.stack([gx, gy], -1).reshape(n, 2).astype(np.int32)
                p = Patches(rng.random((n, 768), dtype=np.float32), pos, g, n // 9)
                ms = timeit(lambda: eng.vision([p]), max(3, args.iters // 2))
                res["image"][t] = {"ms": round(ms, 3), "patches": n}
                print("image", t, n, f"{ms:.3f} ms", flush=True)
                for b in (4,) if t <= 140 else ():
                    ms = timeit(lambda: eng.vision([p] * b), 3)
                    res["image"][f"{t}x{b}"] = {"ms": round(ms, 3)}
                    print("image batch", t, b, f"{ms:.3f} ms", flush=True)
        if "audio" in stages:
            from tt_embgemma.preprocess.audio import log_mel

            for sec in [float(x) for x in args.audio_secs.split(",") if x]:
                wav = (0.1 * rng.standard_normal(int(sec * 16000))).astype(np.float32)
                f, m = log_mel(wav)
                ms = timeit(lambda: eng.audio([(f, m)]), max(3, args.iters // 2))
                res["audio"][sec] = {"ms": round(ms, 3), "frames": int(f.shape[0])}
                print("audio", sec, f"{ms:.3f} ms", flush=True)
        res["engine"] = eng.describe()
    finally:
        if eng is not None:
            eng.close()
        close_device(dev)
    json.dump(res, open(args.out, "w"), indent=1)
    print("DONE", flush=True)


if __name__ == "__main__":
    main()