Download scripts/ref_look.py from WeReCooking/LookAnything-ONNX-WebGPU: direct link, hf CLI and curl.
- Browser
- Download file 4.68 kB
-
https://huggingface.co/WeReCooking/LookAnything-ONNX-WebGPU/resolve/main/scripts/ref_look.py
- Command line
-
hf download hf://WeReCooking/LookAnything-ONNX-WebGPU/scripts/ref_look.py
-
curl -L -o ref_look.py https://huggingface.co/WeReCooking/LookAnything-ONNX-WebGPU/resolve/main/scripts/ref_look.py
4.68 kB
| """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) | |