File size: 5,685 Bytes
4c42b0f | 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | #!/usr/bin/env python3
"""
Run BEAR inference with ANY local model — no VLMEvalKit required.
Instead of VLMEvalKit's `supported_VLM`, this runner calls a tiny pluggable
adapter that you point at with `--model_impl module:ClassName`. An adapter is
just a class with:
class MyModel:
def __init__(self, model_name, **kwargs): ...
def generate(self, text: str, images: list[PIL.Image.Image]) -> str: ...
The runner prepares, per question:
* single-image tasks (pointing / bbox / trajectory): images = [the image]
* video tasks : images = 16 sampled frames
* interleaved tasks : images = 16 sampled frames + the observation image
and a text prompt, then calls `adapter.generate(text, images)`.
Ready-made adapters live in bear_models.py (Cosmos, generic Qwen2.5-VL, Echo).
Examples:
# NVIDIA Cosmos-Reason1-7B
cd task_planning
python ../run_custom_model.py --model_impl bear_models:CosmosReason1 \
--input_json_path next_action_prediction_official.json
# smoke test with the dependency-free Echo adapter
python ../run_custom_model.py --model_impl bear_models:EchoModel \
--input_json_path next_action_prediction_official.json
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import json
import argparse
import importlib
import numpy as np
from PIL import Image
from util.prompt_generation import generate_question_prompt
SAMPLE_FRAMES = 16
def sample_frames(mp4_path, num_frames=SAMPLE_FRAMES):
"""Return `num_frames` evenly-spaced frames from a video as PIL images."""
import cv2
cap = cv2.VideoCapture(mp4_path)
if not cap.isOpened():
raise ValueError(f"Cannot open video: {mp4_path}")
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
idx = np.linspace(0, max(total - 1, 0), num=num_frames, dtype=int)
frames = []
for i in idx:
cap.set(cv2.CAP_PROP_POS_FRAMES, int(i))
ok, frame = cap.read()
if ok:
frames.append(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
cap.release()
return frames
def make_input(category, item, fmt, base):
"""Build (text, images) for one item / one prompt format ('direct' or 'cot')."""
question = item.get("question", "")
options = item.get("options", [])
video = (item.get("video") or "").strip()
image = (item.get("image") or "").strip()
prompt = generate_question_prompt(fmt, category, question, options, model_category="general")
images = []
if isinstance(prompt, tuple):
text = "".join(str(p) for p in prompt)
if video:
images += sample_frames(os.path.join(base, video))
# 3-part prompts (relative direction / path planning) append the observation image
if len(prompt) == 3 and image:
images.append(Image.open(os.path.join(base, image)).convert("RGB"))
else:
text = prompt
if image:
images = [Image.open(os.path.join(base, image)).convert("RGB")]
elif video:
images = sample_frames(os.path.join(base, video))
return text, images
def load_adapter(spec, model_name):
"""spec = 'module:ClassName' -> instantiated adapter."""
if ":" not in spec:
raise ValueError("--model_impl must be 'module:ClassName', e.g. bear_models:CosmosReason1")
mod_name, cls_name = spec.split(":", 1)
cls = getattr(importlib.import_module(mod_name), cls_name)
return cls(model_name) if model_name else cls()
ROUTE = {
"image": ["pointing", "trajectory", "bbox"],
"interleaved": ["path planning", "relative direction"],
"video": ["object localization", "next action prediction", "task progress reasoning"],
}
if __name__ == "__main__":
ap = argparse.ArgumentParser(description="BEAR inference with a custom local model (no VLMEvalKit).")
ap.add_argument("--model_impl", default="bear_models:CosmosReason1",
help="Adapter as 'module:ClassName' (default: bear_models:CosmosReason1).")
ap.add_argument("--model_name", default="",
help="Passed to the adapter (e.g. HF id). Blank = adapter default.")
ap.add_argument("--input_json_path", required=True, help="Task JSON file.")
ap.add_argument("--formats", default="direct,cot",
help="Comma-separated prompt formats to run (default: direct,cot).")
ap.add_argument("--evaluate_output_category", default=None, help="Output tag. Default: input filename stem.")
args = ap.parse_args()
base = os.path.dirname(os.path.abspath(args.input_json_path))
tag = args.evaluate_output_category or os.path.splitext(os.path.basename(args.input_json_path))[0]
formats = [f.strip() for f in args.formats.split(",") if f.strip()]
model = load_adapter(args.model_impl, args.model_name)
model_label = args.model_name or getattr(model, "model_name", type(model).__name__)
with open(args.input_json_path) as f:
data = json.load(f)
out = []
for i, item in enumerate(data):
category = item.get("category", "")
item_copy = item.copy()
for fmt in formats:
try:
text, images = make_input(category, item, fmt, base)
item_copy[f"{fmt}_reply"] = model.generate(text, images)
except Exception as e:
item_copy[f"{fmt}_reply"] = f"error: {e}"
out.append(item_copy)
print(f"[{i + 1}/{len(data)}] {item.get('idx', i)} done")
out_path = f"final_{model_label.replace('/', '_')}_evaluate_{tag}.json"
with open(out_path, "w") as f:
json.dump(out, f, indent=4, ensure_ascii=False)
print(f"Saved -> {out_path}")
|