File size: 4,681 Bytes
6e303cd | 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 | """Reference outputs of LookAnything LA-2B (fp32 on CPU, the repo's own code) for the one-pass
query path (point, box, heatmap), plus the intermediate tensors the ONNX parts must reproduce.
usage: ref_look.py OUT_DIR PROMPT_KEY IMAGE [IMAGE ...]
PROMPT_KEY: point | box | b2p:x1,y1,x2,y2 (head box in 0..1000)
"""
from __future__ import annotations
import json
import os
import sys
import time
import numpy as np
import torch
SP = os.environ.get("LOOK_DIR", ".") # holds src/ (the code repo), ckpt/LA-2B (the checkpoint), ref/ (reference outputs)
sys.path.insert(0, f"{SP}/src")
from PIL import Image # noqa: E402
from look_anything import inference as li # noqa: E402
torch.set_num_threads(4)
CKPT = f"{SP}/ckpt/LA-2B"
MIN_PIXELS, MAX_PIXELS = 28 * 28 * 16, int(os.environ.get("LOOK_MAXPX", 28 * 28 * 576)) # Predictor defaults (what serve.py uses)
TEMPLATES = {
"point": "Where is the person looking at? Output only its normalized point as (x,y), using integer coordinates from 0 to 1000.",
"box": "Where is the person looking at? Output only its normalized bounding box as [x1,y1,x2,y2], using integer coordinates from 0 to 1000.",
}
def prompt_for(key: str) -> str:
if key.startswith("b2p:"):
return (f"Locate the gaze target of the person with head box [{key[4:]}]. "
"Output only its normalized point as (x,y), using integer coordinates from 0 to 1000.")
return TEMPLATES[key]
if __name__ == "__main__":
out, key, images = sys.argv[1], sys.argv[2], sys.argv[3:]
os.makedirs(out, exist_ok=True)
t0 = time.time()
proc = li.load_processor(CKPT, min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS)
# transformers 5.4.0's Qwen2VLImageProcessor has no min_pixels attribute, so load_processor's hasattr guard
# skips the limits; setting them afterwards does take effect (inference_config.json: 12544 / 451584).
proc.image_processor.min_pixels, proc.image_processor.max_pixels = MIN_PIXELS, MAX_PIXELS
model = li.load_model(CKPT, device="cpu", dtype=torch.float32)
print(f"loaded {time.time()-t0:.0f}s", flush=True)
cap = {}
orig_prepare, orig_run = model._prepare, model._run_backbone
def prepare(*a, **k):
r = orig_prepare(*a, **k)
cap["inputs_embeds"], cap["deepstack"], cap["prompt_len"] = r[0], r[5], r[3]
return r
def run(inputs_embeds, position_ids, full_mask, attn_2d, vpm, deepstack):
h = orig_run(inputs_embeds, position_ids, full_mask, attn_2d, vpm, deepstack)
cap.update(position_ids=position_ids, full_mask=full_mask, hidden=h)
return h
model._prepare, model._run_backbone = prepare, run
prompt = prompt_for(key)
results = {}
for p in images:
t0 = time.time()
name = os.path.splitext(os.path.basename(p))[0]
img = Image.open(p).convert("RGB")
enc = li._encode_image(proc, img, prompt, "cpu")
with torch.inference_mode():
o = model(input_ids=enc["input_ids"], attention_mask=enc.get("attention_mask"), pixel_values=enc["pixel_values"],
image_grid_thw=enc["image_grid_thw"], answer_input_ids=None, compute_lm_loss=False, compute_auxiliary=True,
compute_gaze_heatmap=True, auxiliary_heads=("heatmap", "head_mask", "point", "box"), return_predictions=True)
pr = o["predictions"]
r = {"prompt": prompt, "size": list(img.size), "grid_thw": enc["image_grid_thw"][0].tolist(), "n_ids": int(enc["input_ids"].shape[1]),
"point": pr["point"][0].tolist(), "box": pr["box"][0].tolist(), "seconds": round(time.time() - t0, 1)}
hm = pr["gaze_heatmap_logits"][0, 0].float()
am, ex = li._heatmap_points(hm, model.config.heatmap_coordinate_mode)
r.update(heatmap_argmax=am, heatmap_expect=ex)
results[name] = r
np.savez_compressed(
f"{out}/{name}.npz", input_ids=enc["input_ids"].numpy(), pixel_values=enc["pixel_values"].numpy(),
grid=enc["image_grid_thw"].numpy(), inputs_embeds=cap["inputs_embeds"].numpy(),
deepstack=np.stack([d.numpy() for d in cap["deepstack"]]), position_ids=cap["position_ids"].numpy(),
full_mask=cap["full_mask"].numpy(), hidden=cap["hidden"].numpy(), heatmap=hm.numpy(),
head_mask=pr["head_mask_logits"][0, 0].float().numpy(), prompt_len=np.array(cap["prompt_len"]))
print(f"{name:14s} grid {r['grid_thw']} ids {r['n_ids']} point {np.round(r['point'], 3).tolist()} box {np.round(r['box'], 3).tolist()} "
f"hm-argmax {np.round(am, 3).tolist()} ({r['seconds']}s)", flush=True)
json.dump(results, open(f"{out}/results.json", "w"), indent=1)
|