#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 """Latency benchmark of the device pipeline (one device process; run under the device lock): bin/devrun -t 1200 -- python -u code/scripts/bench.py --profile 1.6 --images DIR \ --cases text_en_line.png:ocr,table_simple.png:table,page_synth.png:ocr --dec mk --reps 5 --out bench.json Per case: vision / prefill / TTFT (first token) / decode ms per token / total ms (median over reps, traced, greedy, the output length of the first run fixed via max_new_tokens) and the tokens/s of the decode. """ import argparse import json import os import statistics import sys import time sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def main(): ap = argparse.ArgumentParser() ap.add_argument("--profile", default="1.6") ap.add_argument("--weights-dir", default="") ap.add_argument("--images", required=True) ap.add_argument("--cases", required=True) ap.add_argument("--dec", default="mk") ap.add_argument("--reps", type=int, default=5) ap.add_argument("--max-new", type=int, default=0) ap.add_argument("--max-positions", type=int, default=4096) ap.add_argument("--precision", default="") ap.add_argument("--dispatch", default="eth") ap.add_argument("--compare-ttnn", action="store_true", help="also time the ttnn decode engine (fallback built)") ap.add_argument("--out", default="") args = ap.parse_args() from PIL import Image from tt_paddleocr.config import WEIGHTS, ModelConfig, resolve_weights_dir from tt_paddleocr.frontend import PromptBuilder, preprocess, task_image, task_max_pixels, task_prompt from tt_paddleocr.tt.model import DevicePipeline from tt_paddleocr.tt.model_types import GenParams from tt_paddleocr.tt.ttnn_vision import default_buckets from tt_paddleocr.ttaw.device import close_device, open_device wdir = args.weights_dir or resolve_weights_dir(args.profile) cfg = ModelConfig.from_dir(wdir, args.profile) pb = PromptBuilder.from_dir(wdir, cfg.prof) cases = [] for c in args.cases.split(","): name, task = c.split(":")[:2] img = preprocess(task_image(Image.open(os.path.join(args.images, name)), task), cfg.prof.min_pixels, task_max_pixels(task, cfg.prof)) cases.append((name, task, img, pb.ids(task_prompt(task, None), img.n_tokens))) db = default_buckets(max(c[2].n_patches for c in cases)) vb = sorted({next(b for b in db if b >= c[2].n_patches) for c in cases}) prec = dict(kv.split("=") for kv in args.precision.split(",") if kv) settings = {"engine": {"dec": args.dec}, "vis_buckets": vb, "max_positions": args.max_positions, "trace": True, "source": WEIGHTS[args.profile][1], "precision": prec or None, "ttnn_fallback": True if args.compare_ttnn else None} res = {"profile": args.profile, "dec": args.dec, "vis_buckets": vb, "precision": prec, "cases": {}} dev = open_device(0, dispatch=args.dispatch, l1_small_size=32768, trace_region_size=512 << 20) try: t0 = time.time() pipe = DevicePipeline(dev, wdir, cfg, settings, log=lambda s: print(s, flush=True)) pipe.prepare() res["init_s"] = round(time.time() - t0, 1) res["info"] = pipe.info() for name, task, img, ids in cases: first = pipe.run(img, ids, GenParams(max_new_tokens=args.max_new or 1024)) n = len(first.tokens) runs = [pipe.run(img, ids, GenParams(max_new_tokens=n, stop_ids=(0x7FFFFFFF,))) for _ in range(args.reps)] med = {k: round(statistics.median(r.timings[k] for r in runs), 3) for k in ("vision", "prefill", "first_token", "decode", "total", "ms_per_token") if all(k in r.timings for r in runs)} if args.compare_ttnn and pipe.dec is not None: rt = [pipe.run(img, ids, GenParams(max_new_tokens=n, stop_ids=(0x7FFFFFFF,)), engine="ttnn") for _ in range(max(2, args.reps // 2))] for k in ("prefill", "first_token", "decode", "total", "ms_per_token"): if all(k in r.timings for r in rt): med[f"ttnn_{k}"] = round(statistics.median(r.timings[k] for r in rt), 3) med["ttnn_tokens_equal"] = rt[0].tokens == runs[0].tokens med["tokens"] = n med["tokens_per_s"] = round(1e3 / med["ms_per_token"], 1) if med.get("ms_per_token") else None med["patches"] = img.n_patches med["prompt_tokens"] = len(ids) med["text"] = pb.decode(first.tokens)[:200] res["cases"][f"{name}:{task}"] = med print(name, task, json.dumps(med, ensure_ascii=False), flush=True) pipe.close() finally: if args.out: json.dump(res, open(args.out, "w"), ensure_ascii=False, indent=1) close_device(dev) if __name__ == "__main__": main()