File size: 4,210 Bytes
8aa515d | 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 | # SPDX-License-Identifier: Apache-2.0
"""Run the packaged model over an eval manifest and save the raw outputs (heatmaps, in/out) for offline scoring.
python scripts/eval_dump.py --root <data dir> --manifest <data dir>/manifest.json --out tt.npz
The manifest is a JSON list of frames ``{"file": <path under root>, "heads": [{"bbox_norm": [x1, y1, x2, y2]}, ...]}``
(GazeFollow test, VideoAttentionTarget test). Each frame is ONE public-API call ``model(path, boxes)`` with all of
its head boxes in normalised coordinates, exactly what a user would run: decode, squash to 448x448 (PIL bilinear),
uint8 upload, the traced device graph, readback. A box that the API rejects as too small (it covers no cell of the
32x32 feature grid) is run through the same preprocessing and device call without that check, as upstream does
(an empty head map); such heads are counted in ``fallback``.
Output .npz: ``heatmap`` float32 (H, 64, 64), ``inout`` float32 (H,), ``frame`` int32 (H,), ``fallback`` bool (H,),
``call_ms`` float32 (frames,), one row per head in manifest order.
"""
from __future__ import annotations
import argparse
import json
import os
import time
from pathlib import Path
import numpy as np
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--root", required=True)
ap.add_argument("--manifest", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--limit", type=int, default=None)
ap.add_argument("--dispatch", default=os.environ.get("GAZE_LLE_DISPATCH", "auto"))
args = ap.parse_args()
import torch
from PIL import Image
from gaze_lle import GazeLLE
from gaze_lle import api as gl_api
frames = json.loads(Path(args.manifest).read_text())[: args.limit]
root = Path(args.root)
torch.set_grad_enabled(False)
model = GazeLLE.from_pretrained(dispatch=args.dispatch, max_heads=10)
g = model.device.compute_with_storage_grid_size()
print(f"model ready: dispatch={model.dispatch} grid={g.x}x{g.y}; {len(frames)} frames", flush=True)
hms, ios, fr, fb, call_ms = [], [], [], [], []
t_start = time.perf_counter()
for i, f in enumerate(frames):
boxes = [h["bbox_norm"] for h in f["heads"]]
path = str(root / f["file"])
t0 = time.perf_counter()
try:
r = model(path, boxes)
flags = [False] * len(boxes)
except ValueError:
# same host preprocessing as GazeLLE._prepare, without the "box covers a feature cell" check
im = gl_api._to_pil(path)
w, h = im.size
if im.size != (gl_api.INPUT_SIZE, gl_api.INPUT_SIZE):
im = im.resize((gl_api.INPUT_SIZE, gl_api.INPUT_SIZE), Image.BILINEAR)
px = torch.from_numpy(np.array(im, dtype=np.uint8))[None]
cl = [tuple(min(max(float(v), 0.0), 1.0) for v in b) for b in boxes]
r = model._finish(model._run(gl_api._Prepared(px, cl, (w, h))))
ok = []
for b in boxes:
try:
gl_api.normalise_bboxes([b], "normalized", w, h, 10)
ok.append(False)
except ValueError:
ok.append(True)
flags = ok
call_ms.append((time.perf_counter() - t0) * 1e3)
hms.append(r.heatmap.numpy().astype(np.float32))
ios.append(r.inout.numpy().astype(np.float32))
fr += [i] * len(boxes)
fb += flags
if (i + 1) % 500 == 0:
print(f"{i + 1}/{len(frames)} frames, {time.perf_counter() - t_start:.0f} s, fallback heads {sum(fb)}",
flush=True)
model.close()
np.savez_compressed(args.out, heatmap=np.concatenate(hms), inout=np.concatenate(ios),
frame=np.asarray(fr, np.int32), fallback=np.asarray(fb, bool),
call_ms=np.asarray(call_ms, np.float32))
cm = np.asarray(call_ms)
print(f"done: {len(frames)} frames, {len(fr)} heads, fallback heads {sum(fb)}, call p50 {np.median(cm):.2f} ms, "
f"{time.perf_counter() - t_start:.0f} s -> {args.out}")
if __name__ == "__main__":
main()
|