File size: 4,811 Bytes
1836fe9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NVIDIA-OneWay-Noncommercial

"""Stage 1: run a VLM over every (benchmark sample, prompt type) through an API.

Writes <output-dir>/inference/<model_slug>/<prompt_type>/idx_NNNN_<side>.json.
"""
from __future__ import annotations

import argparse
import datetime
import os
import sys

from . import _api
from ._shared import (
    PROMPT_TYPE_NAMES,
    build_question,
    load_eval_items,
    result_path,
    save_result,
)


def cmd_infer(args) -> None:
    """Run inference on every benchmark sample."""
    items = load_eval_items(args.scenarios)
    scenarios_dir = os.path.dirname(os.path.abspath(args.scenarios))
    if not items:
        print("No valid scenarios found.", file=sys.stderr)
        sys.exit(1)

    prompt_types = args.prompt_type
    total = len(items) * len(prompt_types)
    done = 0
    skipped = 0
    print(
        f"Inference: {len(items)} eval items x {len(prompt_types)} prompt type(s) "
        f"= {total} calls | model={args.model}"
    )

    for pt in prompt_types:
        for item in items:
            idx = item["scenario_index"]
            side = item["side"]
            rpath = result_path(args.output_dir, "inference", args.model, pt, idx, side)

            # Resume: skip if already done
            if not args.no_resume and os.path.isfile(rpath):
                skipped += 1
                continue

            question = build_question(pt, item["task"])
            # Clips ship pre-trimmed to their annotated window and are used as-is.
            video = item["video_path"]
            if not os.path.isabs(video):
                video = os.path.join(scenarios_dir, video)
            if not os.path.isfile(video):
                print(f"  Video not found, skipping: {video}", file=sys.stderr)
                continue

            done += 1
            print(
                f"  [{done + skipped}/{total}] idx={idx} side={side} pt={pt}",
                end="",
                flush=True,
            )

            try:
                answer = _api.query_model(
                    video, question, args.model, args.api_url, args.api_key,
                    args.input_mode, args.max_frames, robot_type=item["robot"],
                )
            except SystemExit:
                print(" [FAILED]")
                continue

            save_result(rpath, {
                "scenario_index": idx,
                "side": side,
                "prompt_type": pt,
                "model": args.model,
                "question": question,
                "video_path": item["video_path"],
                "model_response": answer,
                "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
            })
            print(f" [OK] {len(answer)} chars")

    print(f"Inference done: {done} new, {skipped} resumed, {total} total.")


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Run VLM inference on the benchmark videos through an API.",
    )
    parser.add_argument("--scenarios", required=True, help="Path to benchmark.json")
    parser.add_argument(
        "--model", required=True, help="Model name as your API endpoint knows it",
    )
    parser.add_argument(
        "--prompt-type", nargs="+", default=list(PROMPT_TYPE_NAMES),
        choices=PROMPT_TYPE_NAMES,
        help="Prompt type(s) to evaluate (default: all four)",
    )
    parser.add_argument("--output-dir", default="eval_results", help="Output directory")
    parser.add_argument(
        "--api-url", default=_api.CHAT_COMPLETIONS_URL,
        help="Full chat-completions URL (default: $VLM_API_BASE/v1/chat/completions)",
    )
    parser.add_argument(
        "--input-mode", choices=("auto", "gemini_video", "openai_frames"), default="auto",
        help="Send the whole clip ('gemini_video') or sampled frames ('openai_frames'). "
        "'auto' sends frames to GPT models and the clip to others.",
    )
    parser.add_argument(
        "--max-frames", type=int, default=16,
        help="Frames sent in 'openai_frames' mode, spread evenly over the clip",
    )
    parser.add_argument("--no-resume", action="store_true", help="Re-run all, ignore existing")

    args = parser.parse_args()
    args.api_key = os.environ.get("VLM_API_KEY", "")
    if args.max_frames < 1:
        parser.error("--max-frames must be at least 1")
    if not args.api_key.strip():
        print("Missing API key: set VLM_API_KEY.", file=sys.stderr)
        sys.exit(1)
    if not args.api_url:
        print("Missing endpoint: set VLM_API_BASE or pass --api-url.", file=sys.stderr)
        sys.exit(1)
    cmd_infer(args)


if __name__ == "__main__":
    main()