"""Inference timing of one arm: peak memory and lines per second at batch 1 and batch 32, on the H100 (GPU) or on N CPU threads. Weights are random (speed and memory do not depend on them); the codec size is the union codec size. Inputs are real KOHTD word crops from the smoke manifest, and 4-word line crops made by joining four of them (about 1500 px wide at height 96). The model's own forward pass plus greedy argmax is timed; image loading is not included (it is the same for every arm). Usage: python -m linedet.timing --arm A1 --device cuda | --device cpu --threads 16 """ import argparse import json import os import time import numpy as np import torch from . import data as D from .common import DATA, LD_OUT, load_json, read_manifest, save_json, utcnow from .models import build_arm_for_inference def make_inputs(spec, n, joined): rows = read_manifest(DATA + "/data/processed/r5_linedet_smoke/kohtd_val_smoke.tsv")[:200] rng = np.random.default_rng(1) tens = [] for i in range(n): if not joined: r = rows[int(rng.integers(0, len(rows)))] tens.append(D.load_tensor(r["image"], spec)) else: parts = [D.load_tensor(rows[int(rng.integers(0, len(rows)))]["image"], spec) for _ in range(4)] t4 = torch.cat(parts, dim=-1) if spec.fixed_width: # fixed-width arm: the four words are squashed into the fixed width (as a long line would be) t4 = torch.nn.functional.interpolate(t4[None], size=(spec.height, spec.fixed_width), mode="area")[0] tens.append(t4) return tens def pad_batch(ts): w = max(t.shape[-1] for t in ts) x = torch.stack([torch.nn.functional.pad(t, (0, w - t.shape[-1])) for t in ts]) return x, torch.LongTensor([t.shape[-1] for t in ts]) def main(): ap = argparse.ArgumentParser() ap.add_argument("--arm", required=True) ap.add_argument("--device", default="cuda") ap.add_argument("--threads", type=int, default=16) ap.add_argument("--iters", type=int, default=100) ap.add_argument("--codec", default="") a = ap.parse_args() dev = torch.device(a.device) if dev.type == "cpu": torch.set_num_threads(a.threads) from kraken.lib.codec import PytorchCodec cpath = a.codec or (LD_OUT + "/codec_union.json" if os.path.exists(LD_OUT + "/codec_union.json") else LD_OUT + "/smoke/codec_union.json") codec = PytorchCodec(load_json(cpath)["c2l"]) arm = build_arm_for_inference(a.arm, codec) arm.to(dev) arm.eval() spec = D.SPECS[a.arm] res = {"arm": a.arm, "device": a.device, "threads": a.threads if dev.type == "cpu" else None, "codec_classes": codec.max_label + 1, "params_deployed": arm.deploy_params(), "created": utcnow(), "codec_file": cpath} if dev.type == "cuda": res["gpu"] = torch.cuda.get_device_name(0) res["weights_gib"] = torch.cuda.memory_allocated() / 2 ** 30 for kind, joined in (("word", False), ("line", True)): pool = make_inputs(spec, 40, joined) res[kind + "_median_width_px"] = float(np.median([t.shape[-1] for t in pool])) for bs in (1, 32): if dev.type == "cpu" and bs == 32: bs_eff = 8 else: bs_eff = bs batches = [] for k in range(0, 40 - bs_eff + 1, bs_eff): batches.append(pad_batch(pool[k:k + bs_eff])) if dev.type == "cuda": torch.cuda.synchronize() torch.cuda.reset_peak_memory_stats() with torch.inference_mode(): for x, s in batches[:5]: arm.infer(x, s, dev) if dev.type == "cuda": torch.cuda.synchronize() t0 = time.time() n = 0 it = 0 while it < a.iters: x, s = batches[it % len(batches)] lp, ol = arm.infer(x, s, dev) lp.argmax(-1) n += x.shape[0] it += 1 if dev.type == "cuda": torch.cuda.synchronize() dt = time.time() - t0 key = "%s_batch%d" % (kind, bs_eff) res[key + "_lines_per_s"] = n / dt if dev.type == "cuda": res[key + "_peak_gib"] = torch.cuda.max_memory_allocated() / 2 ** 30 res[key + "_peak_reserved_gib"] = torch.cuda.max_memory_reserved() / 2 ** 30 print(a.arm, a.device, key, res[key + "_lines_per_s"], res.get(key + "_peak_gib"), flush=True) tag = os.environ.get("LINEDET_TIMING_TAG", "") out = LD_OUT + "/timing/%s_%s%s.json" % (a.arm, a.device + (str(a.threads) if dev.type == "cpu" else ""), ("_" + tag) if tag else "") res["tag"] = tag or "quiet_node_sequential" save_json(out, res) if __name__ == "__main__": main()