zpy777 commited on
Commit
6461f0c
·
verified ·
1 Parent(s): b867c85

Release FIRM-Video-Bench (part 2)

Browse files
data/videos/vphy2_v2_3335_A_person_twists_a_piece_of_fabric_tightly,_creating_a_tourniquet_around_their_arm.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d20e8cb413fe8ac829fdd9796389fabe36874b0e2770e68ca5591f9a466b9c2e
3
+ size 1461663
data/videos/vphy2_v2_3388_c09f35b4-f527-498e-ac08-5149c282709a_result.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f28cdf3ccdab870b7388dbfade7e644247f0cd003bfcaa4e3c9aafc0484dd2e
3
+ size 962425
prompts/definitions.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ### Instruction Following
2
+ Measures how accurately and completely the video follows the text prompt, including requested subjects, attributes, actions, scene, style, camera/viewpoint, and temporal event order.
3
+
4
+ ### Perceptual Quality
5
+ Measures the perceptual and technical quality of the rendered video, including resolution, overall and local clarity, sharpness or blurriness, brightness and color stability, flicker, compression artifacts, and low-level visual distortions that affect the viewing experience.
6
+
7
+ ### World Coherence
8
+ Measures whether the video contains any violations of everyday knowledge, common sense, or basic physical laws, including temporal inconsistencies, unnatural or incoherent motion, physically implausible interactions, and structural abnormalities or deformities in objects or characters.
prompts/vanilla_prompts.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference prompts for the video-generation reward model.
3
+
4
+ **Per-dimension** query templates: one prompt per scoring dimension,
5
+ each tailored to the dimension's evaluation perspective. Each template
6
+ asks the judge to evaluate the video on that dimension and to return a
7
+ single strict JSON object ``{"reasoning": "...", "score": <int 1-5>}``.
8
+
9
+ The dimensions are:
10
+ - instruction_following
11
+ - visual_quality
12
+ - world_consistency
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from string import Template
17
+ from typing import Dict, List, Optional
18
+
19
+
20
+ DIMENSIONS: List[str] = [
21
+ "instruction_following",
22
+ "visual_quality",
23
+ "world_consistency",
24
+ ]
25
+
26
+ #: Dimensions that require the text-to-video prompt as input. All three
27
+ #: dimensions consume ``t2v_prompt`` -- IF as the object of evaluation,
28
+ #: VQ/WC as context only (see module docstring).
29
+ DIMENSIONS_REQUIRING_PROMPT: frozenset[str] = frozenset(DIMENSIONS)
30
+
31
+ #: Number of uniformly sampled frames per video that the judge will receive.
32
+ NUM_SAMPLED_FRAMES: int = 8
33
+
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Shared JSON output contract (response shape only — what the model must
37
+ # return, regardless of which dimension it was asked about).
38
+ # ---------------------------------------------------------------------------
39
+ _JSON_OUTPUT_CONTRACT = """\
40
+ Your output must be a valid JSON object and nothing else, in exactly \
41
+ the following format:
42
+
43
+ {
44
+ "reasoning": "<reasoning>",
45
+ "score": <score>
46
+ }
47
+
48
+ DO NOT include anything before or after the JSON object.\
49
+ """
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # Per-dimension query bodies.
54
+ # ---------------------------------------------------------------------------
55
+
56
+ # (1) instruction_following -- uses ${t2v_prompt}
57
+ _IF_BODY = """\
58
+ You are an expert for evaluating how well an AI-generated video \
59
+ follows its text prompt.
60
+
61
+ The video is given as ${n_frames} frames uniformly sampled in temporal \
62
+ order (frame 1 = earliest, frame ${n_frames} = latest). Judge only \
63
+ from these ${n_frames} frames.
64
+
65
+ We evaluate the dimension 'instruction_following': how accurately and \
66
+ completely the video follows the text prompt, including requested \
67
+ subjects, attributes, actions, scene, style, camera/viewpoint, and \
68
+ temporal event order.
69
+
70
+ Text prompt:
71
+ ${t2v_prompt}
72
+
73
+ Based on the video content, the text prompt, and the dimension \
74
+ definition, please evaluate the video's instruction_following and \
75
+ give the score. The score must be an integer in the range of 1 - 5. \
76
+ FIRST give a brief reasoning, THEN give the score.
77
+
78
+ """ + _JSON_OUTPUT_CONTRACT
79
+
80
+
81
+ # (2) visual_quality -- judged from frames; prompt shown as context only
82
+ _VQ_BODY = """\
83
+ You are an expert for evaluating the perceptual quality of \
84
+ AI-generated videos.
85
+
86
+ The video is given as ${n_frames} frames uniformly sampled in temporal \
87
+ order (frame 1 = earliest, frame ${n_frames} = latest). Judge only \
88
+ from these ${n_frames} frames.
89
+
90
+ We evaluate the dimension 'visual_quality': the perceptual and \
91
+ technical quality of the rendered video, including resolution, \
92
+ overall and local clarity, sharpness or blurriness, brightness and \
93
+ color stability, flicker, compression artifacts, and low-level visual \
94
+ distortions that affect the viewing experience.
95
+
96
+ Text prompt (context only):
97
+ ${t2v_prompt}
98
+
99
+ The text prompt is provided so that you can recognize intentional \
100
+ creative choices it requests (e.g. a stylized look, a non-realistic \
101
+ scene, an unusual camera) and NOT penalize them on this dimension. \
102
+ DO NOT judge how faithfully the video follows the prompt here -- \
103
+ that is covered by a separate dimension.
104
+
105
+ Based on the video content and the dimension definition, please \
106
+ evaluate the video's visual_quality and give the score. The score \
107
+ must be an integer in the range of 1 - 5. FIRST give a brief \
108
+ reasoning, THEN give the score.
109
+
110
+ """ + _JSON_OUTPUT_CONTRACT
111
+
112
+
113
+ # (3) world_consistency -- judged from frames; prompt shown as context only
114
+ _WC_BODY = """\
115
+ You are an expert for evaluating whether an AI-generated video is \
116
+ coherent with the real world.
117
+
118
+ The video is given as ${n_frames} frames uniformly sampled in temporal \
119
+ order (frame 1 = earliest, frame ${n_frames} = latest). Judge only \
120
+ from these ${n_frames} frames.
121
+
122
+ We evaluate the dimension 'world_consistency': whether the video \
123
+ contains any violations of everyday knowledge, common sense, or basic \
124
+ physical laws, including temporal inconsistencies, unnatural or \
125
+ incoherent motion, physically implausible interactions, and \
126
+ structural abnormalities or deformities in objects or characters.
127
+
128
+ Text prompt (context only):
129
+ ${t2v_prompt}
130
+
131
+ The text prompt is provided so that you can recognize intentional \
132
+ creative choices it requests (e.g. a non-realistic scene or a \
133
+ deliberately fantastical setup) and NOT penalize them on this \
134
+ dimension. DO NOT judge how faithfully the video follows the prompt \
135
+ here -- that is covered by a separate dimension.
136
+
137
+ Based on the video content and the dimension definition, please \
138
+ evaluate the video's world_consistency and give the score. The score \
139
+ must be an integer in the range of 1 - 5. FIRST give a brief \
140
+ reasoning, THEN give the score.
141
+
142
+ """ + _JSON_OUTPUT_CONTRACT
143
+
144
+
145
+ # Pre-built per-dimension templates.
146
+ VANILLA_QUERY_TEMPLATES: Dict[str, Template] = {
147
+ "instruction_following": Template(_IF_BODY),
148
+ "visual_quality": Template(_VQ_BODY),
149
+ "world_consistency": Template(_WC_BODY),
150
+ }
151
+
152
+
153
+ def build_query(
154
+ dimension: str,
155
+ t2v_prompt: Optional[str] = None,
156
+ n_frames: int = NUM_SAMPLED_FRAMES,
157
+ ) -> str:
158
+ """Render the single-dimension query for ``dimension``.
159
+
160
+ Parameters
161
+ ----------
162
+ dimension:
163
+ One of :data:`DIMENSIONS`.
164
+ t2v_prompt:
165
+ The text-to-video prompt. Required (non-empty) for all
166
+ dimensions: ``instruction_following`` evaluates the video
167
+ against it; ``visual_quality`` and ``world_consistency`` use
168
+ it as context only (see module docstring).
169
+ n_frames:
170
+ Number of uniformly sampled frames the judge will receive.
171
+ """
172
+ if dimension not in VANILLA_QUERY_TEMPLATES:
173
+ raise KeyError(
174
+ f"Unknown dimension: {dimension!r}. "
175
+ f"Expected one of {DIMENSIONS}."
176
+ )
177
+ if t2v_prompt is None or not str(t2v_prompt).strip():
178
+ raise ValueError(
179
+ f"`t2v_prompt` must be a non-empty string for "
180
+ f"dimension {dimension!r}."
181
+ )
182
+ return VANILLA_QUERY_TEMPLATES[dimension].substitute(
183
+ n_frames=int(n_frames),
184
+ t2v_prompt=str(t2v_prompt).strip(),
185
+ )
186
+
187
+
188
+ def build_prompt(
189
+ dimension: str,
190
+ video_prompt: Optional[str] = None,
191
+ n_frames: int = NUM_SAMPLED_FRAMES,
192
+ ) -> Dict[str, str]:
193
+ """Build the (system, user) prompt pair for a single-dimension call.
194
+
195
+ The whole query is sent as the user message; no separate system
196
+ message is used (matches the original VS2 setup).
197
+
198
+ All three dimensions require a non-empty ``video_prompt``. For
199
+ ``visual_quality`` and ``world_consistency`` it is shown as
200
+ context only (see module docstring).
201
+
202
+ Returns
203
+ -------
204
+ Dict[str, str]
205
+ ``{"system": "", "user": <rendered_query>}``.
206
+ """
207
+ return {
208
+ "system": "",
209
+ "user": build_query(
210
+ dimension=dimension,
211
+ t2v_prompt=video_prompt,
212
+ n_frames=n_frames,
213
+ ),
214
+ }
215
+
216
+
217
+ __all__ = [
218
+ "DIMENSIONS",
219
+ "DIMENSIONS_REQUIRING_PROMPT",
220
+ "NUM_SAMPLED_FRAMES",
221
+ "VANILLA_QUERY_TEMPLATES",
222
+ "build_query",
223
+ "build_prompt",
224
+ ]
results/firm-video-internvl3_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
results/firm-video-qwen3vl_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
results/gemini31pro_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
results/gpt5_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
results/internvl3-38b_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
results/internvl3-8b_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
results/qwen3vl235ba22b_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
results/qwen3vl30ba3b_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
results/qwen3vl8b_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
results/seed20lite_scores.json ADDED
The diff for this file is too large to render. See raw diff
 
scripts/__pycache__/_core.cpython-312.pyc ADDED
Binary file (16.9 kB). View file
 
scripts/__pycache__/eval.cpython-312.pyc ADDED
Binary file (17.5 kB). View file
 
scripts/__pycache__/infer.cpython-312.pyc ADDED
Binary file (5.19 kB). View file
 
scripts/__pycache__/metric.cpython-312.pyc ADDED
Binary file (13.8 kB). View file
 
scripts/_core.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared scoring core (per-dimension version).
2
+
3
+ Backend-agnostic helpers for the vanilla video-reward pipeline. The
4
+ ``infer.py`` entry script handles CLI parsing and client construction;
5
+ everything below is duck-typed on a client object exposing:
6
+
7
+ client.infer_with_frames(user_text, frame_b64_list, system_text)
8
+ client.max_retries : int
9
+ client.retry_base_delay : float
10
+ client.request_interval : float
11
+
12
+ Each video triggers ONE multimodal model call **per scoring dimension**
13
+ (see ``prompts/vanilla_prompts.py``). For the canonical 3-dim setup that
14
+ means up to 3 calls per video. Each reply must be a single JSON object
15
+ of the form::
16
+
17
+ {"reasoning": "...", "score": <int 1-5>}
18
+
19
+ The orchestrator aggregates the per-dimension replies into the SAME
20
+ ``scoring`` block layout used by the previous single-call pipeline, so
21
+ all downstream consumers (``compute_mae.py``, the gradio app, etc.)
22
+ keep working unchanged::
23
+
24
+ {
25
+ "dimensions": [
26
+ {"dimension": "instruction_following", "score": 4, "reasoning": "..."},
27
+ {"dimension": "visual_quality", "score": 3, "reasoning": "..."},
28
+ {"dimension": "world_consistency", "score": 5, "reasoning": "..."}
29
+ ],
30
+ "scores_by_dim": {
31
+ "instruction_following": 4,
32
+ "visual_quality": 3,
33
+ "world_consistency": 5
34
+ }
35
+ }
36
+
37
+ Resumability
38
+ ------------
39
+ Per-dimension calls are independent, so we can cache partial progress.
40
+ Two layers are persisted under the same parent dir as ``score_path``:
41
+
42
+ * ``<score_path>`` — final results (only fully-scored
43
+ videos appear here, same schema as
44
+ before).
45
+ * ``<score_path>.partial.json`` — per-video, per-dim cache. Each
46
+ entry maps ``video_id`` to a dict
47
+ ``{dim: {"reasoning": str, "score": int}}``
48
+ containing only the dims that have
49
+ already succeeded.
50
+
51
+ On rerun, fully-scored videos are skipped; partially-scored videos only
52
+ re-issue the missing dimensions; failed videos are retried from scratch
53
+ (of whatever is missing).
54
+ """
55
+ from __future__ import annotations
56
+
57
+ import os
58
+ import sys
59
+ import threading
60
+ import time
61
+ from concurrent.futures import ThreadPoolExecutor, as_completed
62
+ from typing import Any, Optional
63
+
64
+ from tqdm import tqdm
65
+
66
+ # --- Path bootstrapping so we can import from `prompts/` and `tools/` -----
67
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
68
+ PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
69
+ for _p in (PROJECT_ROOT, os.path.join(PROJECT_ROOT, "prompts")):
70
+ if _p not in sys.path:
71
+ sys.path.insert(0, _p)
72
+
73
+ from prompts.vanilla_prompts import ( # noqa: E402
74
+ DIMENSIONS,
75
+ NUM_SAMPLED_FRAMES,
76
+ build_prompt,
77
+ )
78
+ from tools import ( # noqa: E402
79
+ ensure_video_local,
80
+ extract_frames_from_video,
81
+ load_json_safe,
82
+ parse_json_from_model_output,
83
+ save_json_atomic,
84
+ )
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Shared defaults
88
+ # ---------------------------------------------------------------------------
89
+
90
+ DEFAULT_DATA_PATH = os.path.join(PROJECT_ROOT, "data", "firm-video-bench.json")
91
+ DEFAULT_RESULTS_DIR = os.path.join(PROJECT_ROOT, "results")
92
+
93
+ VALID_SCORES = {1, 2, 3, 4, 5}
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Output normalization (per-dimension)
98
+ # ---------------------------------------------------------------------------
99
+
100
+ def _coerce_score(score_raw: Any) -> int:
101
+ if isinstance(score_raw, bool): # bool is a subclass of int — reject
102
+ raise ValueError(f"score must be an integer, got bool: {score_raw}")
103
+ if isinstance(score_raw, int):
104
+ score = score_raw
105
+ elif isinstance(score_raw, float) and float(score_raw).is_integer():
106
+ score = int(score_raw)
107
+ elif isinstance(score_raw, str) and score_raw.strip().lstrip("-").isdigit():
108
+ score = int(score_raw.strip())
109
+ else:
110
+ raise ValueError(f"score must be an integer in 1-5, got: {score_raw!r}")
111
+ if score not in VALID_SCORES:
112
+ raise ValueError(f"score out of range 1-5: {score}")
113
+ return score
114
+
115
+
116
+ def _normalize_single_dim_output(parsed: Any) -> dict[str, Any]:
117
+ """Validate the per-dimension JSON ``{"reasoning":..., "score":...}``."""
118
+ if not isinstance(parsed, dict):
119
+ raise ValueError(f"Expected JSON object, got {type(parsed).__name__}")
120
+ reasoning = parsed.get("reasoning", "")
121
+ if not isinstance(reasoning, str):
122
+ reasoning = str(reasoning)
123
+ score = _coerce_score(parsed.get("score"))
124
+ return {"reasoning": reasoning.strip(), "score": score}
125
+
126
+
127
+ def _aggregate_scoring(
128
+ dim_results: dict[str, dict[str, Any]],
129
+ ) -> dict[str, Any]:
130
+ """Build the final ``scoring`` block from per-dimension results."""
131
+ dimensions_block = [
132
+ {
133
+ "dimension": dim,
134
+ "score": dim_results[dim]["score"],
135
+ "reasoning": dim_results[dim]["reasoning"],
136
+ }
137
+ for dim in DIMENSIONS
138
+ ]
139
+ scores_by_dim = {dim: dim_results[dim]["score"] for dim in DIMENSIONS}
140
+ return {
141
+ "dimensions": dimensions_block,
142
+ "scores_by_dim": scores_by_dim,
143
+ }
144
+
145
+
146
+ def _sort_key(video_id: str) -> tuple[int, str]:
147
+ try:
148
+ return int(str(video_id).split("_", 1)[0]), str(video_id)
149
+ except Exception: # noqa: BLE001
150
+ return 10**12, str(video_id)
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Per-dimension scoring (one model call per dimension)
155
+ # ---------------------------------------------------------------------------
156
+
157
+ def _score_one_dimension(
158
+ client: Any,
159
+ dimension: str,
160
+ video_prompt: Optional[str],
161
+ frame_b64_list: list[str],
162
+ video_id: str,
163
+ ) -> Optional[dict[str, Any]]:
164
+ """Issue ONE multimodal call for a single ``dimension``.
165
+
166
+ All three dimensions consume ``video_prompt``: ``instruction_following``
167
+ evaluates the video against it; ``visual_quality`` and
168
+ ``world_consistency`` use it as context only (see
169
+ ``prompts/vanilla_prompts.py``).
170
+
171
+ Returns ``{"reasoning": str, "score": int}`` on success or ``None``
172
+ after exhausting retries.
173
+ """
174
+ spec = build_prompt(
175
+ dimension=dimension,
176
+ video_prompt=video_prompt,
177
+ n_frames=len(frame_b64_list),
178
+ )
179
+ user_text = spec["user"]
180
+
181
+ last_err: Optional[str] = None
182
+ for attempt in range(client.max_retries):
183
+ try:
184
+ raw = client.infer_with_frames(
185
+ user_text=user_text,
186
+ frame_b64_list=frame_b64_list,
187
+ system_text=spec["system"],
188
+ )
189
+ parsed = parse_json_from_model_output(raw)
190
+ normalized = _normalize_single_dim_output(parsed)
191
+ print(
192
+ f" [{video_id}::{dimension}] OK score={normalized['score']}"
193
+ )
194
+ return normalized
195
+ except Exception as exc: # noqa: BLE001
196
+ last_err = str(exc)
197
+ print(
198
+ f" [{video_id}::{dimension}] attempt "
199
+ f"{attempt + 1}/{client.max_retries} failed: {exc}"
200
+ )
201
+ if attempt < client.max_retries - 1:
202
+ time.sleep(client.retry_base_delay * (2 ** attempt))
203
+
204
+ print(
205
+ f" [{video_id}::{dimension}] FAILED after "
206
+ f"{client.max_retries} attempts ({last_err})"
207
+ )
208
+ return None
209
+
210
+
211
+ # ---------------------------------------------------------------------------
212
+ # Partial cache (per-dim) helpers
213
+ # ---------------------------------------------------------------------------
214
+
215
+ def _partial_path(score_path: str) -> str:
216
+ """Sidecar path for the per-dim partial cache."""
217
+ return score_path + ".partial.json"
218
+
219
+
220
+ def _load_partial(score_path: str) -> dict[str, dict[str, dict[str, Any]]]:
221
+ """Load the per-video, per-dim cache, validating shape.
222
+
223
+ Returns ``{video_id: {dim: {"reasoning": str, "score": int}}}``.
224
+ Malformed entries are silently dropped.
225
+ """
226
+ raw = load_json_safe(_partial_path(score_path), default={})
227
+ if not isinstance(raw, dict):
228
+ return {}
229
+ out: dict[str, dict[str, dict[str, Any]]] = {}
230
+ for vid, dims in raw.items():
231
+ if not isinstance(dims, dict):
232
+ continue
233
+ clean: dict[str, dict[str, Any]] = {}
234
+ for dim, entry in dims.items():
235
+ if dim not in DIMENSIONS or not isinstance(entry, dict):
236
+ continue
237
+ try:
238
+ clean[dim] = _normalize_single_dim_output(entry)
239
+ except Exception: # noqa: BLE001
240
+ continue
241
+ if clean:
242
+ out[str(vid)] = clean
243
+ return out
244
+
245
+
246
+ def _save_partial(
247
+ score_path: str,
248
+ partial: dict[str, dict[str, dict[str, Any]]],
249
+ ) -> None:
250
+ save_json_atomic(partial, _partial_path(score_path))
251
+
252
+
253
+ # ---------------------------------------------------------------------------
254
+ # Pipeline
255
+ # ---------------------------------------------------------------------------
256
+
257
+ def run_scoring(
258
+ client: Any,
259
+ expanded_data: list[dict[str, Any]],
260
+ score_path: str,
261
+ concurrency: int,
262
+ ) -> None:
263
+ print("\n" + "=" * 72)
264
+ print("Vanilla per-dimension scoring (one model call per dim per video)")
265
+ print(f"Dimensions ({len(DIMENSIONS)}): {DIMENSIONS}")
266
+ print(f"Frames per video: {NUM_SAMPLED_FRAMES}")
267
+ print(f"Concurrency: {concurrency} (videos in flight)")
268
+ print(f"Calls per video: up to {len(DIMENSIONS)}")
269
+ print("=" * 72)
270
+
271
+ # Final results (fully-scored videos only).
272
+ results = load_json_safe(score_path, default=[])
273
+ if not isinstance(results, list):
274
+ results = []
275
+ result_by_id = {
276
+ r.get("video_id"): r for r in results if r.get("scoring") is not None
277
+ }
278
+
279
+ # Per-dim partial cache (covers BOTH not-yet-scored and partially-
280
+ # scored videos). Final results take precedence.
281
+ partial_by_id = _load_partial(score_path)
282
+ for vid in list(partial_by_id.keys()):
283
+ if vid in result_by_id:
284
+ partial_by_id.pop(vid, None)
285
+
286
+ todo = [
287
+ item for item in expanded_data if item["video_id"] not in result_by_id
288
+ ]
289
+ n_partial = sum(
290
+ 1 for item in todo if partial_by_id.get(item["video_id"])
291
+ )
292
+ print(
293
+ f"[scoring] videos={len(expanded_data)}, "
294
+ f"done={len(result_by_id)}, remaining={len(todo)} "
295
+ f"(of which {n_partial} have partial per-dim progress)"
296
+ )
297
+ if not todo:
298
+ return
299
+
300
+ results_lock = threading.Lock()
301
+ partial_lock = threading.Lock()
302
+ fail_counter = {"n": 0}
303
+ fail_lock = threading.Lock()
304
+
305
+ def process_video(item: dict[str, Any]) -> None:
306
+ video_id = item["video_id"]
307
+ caption = item["caption"]
308
+ try:
309
+ video_path = ensure_video_local(item)
310
+ frame_b64_list = extract_frames_from_video(
311
+ video_path, num_frames=NUM_SAMPLED_FRAMES
312
+ )
313
+ except Exception as exc: # noqa: BLE001
314
+ print(f" [{video_id}] preparation failed: {exc}")
315
+ with fail_lock:
316
+ fail_counter["n"] += 1
317
+ return
318
+
319
+ # Start from any cached per-dim results for this video.
320
+ cached = dict(partial_by_id.get(video_id, {}))
321
+ missing_dims = [d for d in DIMENSIONS if d not in cached]
322
+ print(
323
+ f" [{video_id}] scoring {video_path} "
324
+ f"({len(frame_b64_list)} frames; "
325
+ f"cached={len(cached)}/{len(DIMENSIONS)}, "
326
+ f"to_run={missing_dims})"
327
+ )
328
+
329
+ dim_results: dict[str, dict[str, Any]] = dict(cached)
330
+ # Run missing dims sequentially within a single video (keeps the
331
+ # client's retry/rate-limit semantics simple). Outer thread pool
332
+ # provides throughput across videos.
333
+ for dim in missing_dims:
334
+ single = _score_one_dimension(
335
+ client=client,
336
+ dimension=dim,
337
+ video_prompt=caption,
338
+ frame_b64_list=frame_b64_list,
339
+ video_id=video_id,
340
+ )
341
+ if single is None:
342
+ # Persist whatever succeeded so far, then bail on this video.
343
+ if dim_results:
344
+ with partial_lock:
345
+ partial_by_id[video_id] = dim_results
346
+ _save_partial(score_path, partial_by_id)
347
+ with fail_lock:
348
+ fail_counter["n"] += 1
349
+ time.sleep(client.request_interval)
350
+ return
351
+
352
+ dim_results[dim] = single
353
+
354
+ # Persist incrementally so a crash mid-video doesn't waste
355
+ # successful per-dim calls.
356
+ with partial_lock:
357
+ partial_by_id[video_id] = dict(dim_results)
358
+ _save_partial(score_path, partial_by_id)
359
+
360
+ # Light rate-limit between successive per-dim calls.
361
+ time.sleep(client.request_interval)
362
+
363
+ # All dimensions succeeded: assemble the final record.
364
+ scoring = _aggregate_scoring(dim_results)
365
+ result_item = {
366
+ "video_id": video_id,
367
+ "video_name": item["video_name"],
368
+ "caption": caption,
369
+ "video_path": item.get("video_path", ""),
370
+ "video_local_path": video_path,
371
+ "source": item.get("source", ""),
372
+ "source_index": item["source_index"],
373
+ "source_row_index": item.get("source_row_index"),
374
+ "metadata": item.get("metadata", {}),
375
+ "scoring": scoring,
376
+ }
377
+
378
+ with results_lock:
379
+ result_by_id[video_id] = result_item
380
+ ordered = [
381
+ result_by_id[k]
382
+ for k in sorted(result_by_id.keys(), key=_sort_key)
383
+ ]
384
+ save_json_atomic(ordered, score_path)
385
+
386
+ # Drop this video from the partial cache once it's fully done.
387
+ with partial_lock:
388
+ partial_by_id.pop(video_id, None)
389
+ _save_partial(score_path, partial_by_id)
390
+
391
+ dim_summary = " | ".join(
392
+ f"{d[:10]}={scoring['scores_by_dim'][d]}" for d in DIMENSIONS
393
+ )
394
+ print(f" [{video_id}] OK {dim_summary}")
395
+
396
+ with ThreadPoolExecutor(max_workers=max(1, int(concurrency))) as pool:
397
+ futures = [pool.submit(process_video, item) for item in todo]
398
+ for _ in tqdm(
399
+ as_completed(futures), total=len(futures), desc="vanilla scoring"
400
+ ):
401
+ pass
402
+
403
+ print(
404
+ f"[scoring] saved={score_path}; "
405
+ f"partial_cache={_partial_path(score_path)}; "
406
+ f"failures/skips={fail_counter['n']}"
407
+ )
408
+
409
+
410
+ __all__ = [
411
+ "DIMENSIONS",
412
+ "NUM_SAMPLED_FRAMES",
413
+ "VALID_SCORES",
414
+ "DEFAULT_DATA_PATH",
415
+ "DEFAULT_RESULTS_DIR",
416
+ "PROJECT_ROOT",
417
+ "SCRIPT_DIR",
418
+ "run_scoring",
419
+ ]
scripts/infer.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vanilla scoring pipeline for a vLLM/OpenAI-compatible backend.
2
+
3
+ Each video uses one model call per scoring dimension; strict per-dim
4
+ JSON outputs are aggregated into the final ``scoring`` block. This entry
5
+ talks to an OpenAI-compatible ``/v1/chat/completions`` endpoint.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import os
11
+
12
+ from _core import (
13
+ DEFAULT_DATA_PATH,
14
+ DEFAULT_RESULTS_DIR,
15
+ run_scoring,
16
+ )
17
+ from tools import VLLMClient, load_pointwise_data
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Defaults
21
+ # ---------------------------------------------------------------------------
22
+
23
+ DEFAULT_TAG = "infer"
24
+ DEFAULT_SCORE_OUTPUT = os.path.join(
25
+ DEFAULT_RESULTS_DIR, f"{DEFAULT_TAG}_scores.json"
26
+ )
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # CLI
31
+ # ---------------------------------------------------------------------------
32
+
33
+ def parse_args() -> argparse.Namespace:
34
+ parser = argparse.ArgumentParser(
35
+ description=(
36
+ "Vanilla video reward scoring pipeline (per-dimension, "
37
+ "3 dims = 3 calls/video) — local vLLM OpenAI-compatible "
38
+ "backend."
39
+ )
40
+ )
41
+ parser.add_argument("--data", type=str, default=DEFAULT_DATA_PATH)
42
+ parser.add_argument("--score_output", type=str, default=DEFAULT_SCORE_OUTPUT)
43
+ parser.add_argument(
44
+ "--num_samples",
45
+ type=str,
46
+ default="all",
47
+ help="Number of input videos, or 'all'",
48
+ )
49
+ parser.add_argument(
50
+ "--concurrency",
51
+ type=int,
52
+ default=32,
53
+ help="Max concurrent worker threads (videos in flight). Each "
54
+ "video issues one model call per scoring dimension; the per-dim "
55
+ "calls run sequentially within a video.",
56
+ )
57
+
58
+ # vLLM connection / generation params
59
+ parser.add_argument(
60
+ "--vllm_base_url",
61
+ type=str,
62
+ default=os.environ.get("VLLM_BASE_URL", "http://127.0.0.1:8000/v1"),
63
+ help="vLLM OpenAI base URL, e.g. http://127.0.0.1:8000/v1",
64
+ )
65
+ parser.add_argument(
66
+ "--model",
67
+ type=str,
68
+ default=os.environ.get("VLLM_MODEL", "Qwen3-VL-8B-Instruct"),
69
+ help="Served model name for vLLM backend",
70
+ )
71
+ parser.add_argument(
72
+ "--api_key",
73
+ type=str,
74
+ default=os.environ.get("VLLM_API_KEY", "EMPTY"),
75
+ help="OpenAI-compatible API key; vLLM usually accepts EMPTY",
76
+ )
77
+ parser.add_argument("--max_tokens", type=int, default=2048)
78
+ parser.add_argument("--temperature", type=float, default=0.0)
79
+ parser.add_argument("--top_p", type=float, default=None)
80
+ parser.add_argument(
81
+ "--request_interval",
82
+ type=float,
83
+ default=0.0,
84
+ help="Sleep seconds between successive videos on the same worker.",
85
+ )
86
+ parser.add_argument("--max_retries", type=int, default=3)
87
+ parser.add_argument("--retry_base_delay", type=float, default=2.0)
88
+ parser.add_argument("--request_timeout", type=int, default=300)
89
+ return parser.parse_args()
90
+
91
+
92
+ def main() -> None:
93
+ args = parse_args()
94
+
95
+ print(f"[vllm] base_url: {args.vllm_base_url}")
96
+ print(f"[vllm] model: {args.model}")
97
+ print(
98
+ f"[vllm] max_tokens={args.max_tokens}, "
99
+ f"temperature={args.temperature}, top_p={args.top_p}"
100
+ )
101
+
102
+ _, expanded_data = load_pointwise_data(
103
+ data_path=args.data,
104
+ num_samples=args.num_samples,
105
+ )
106
+
107
+ client = VLLMClient(
108
+ base_url=args.vllm_base_url,
109
+ model_name=args.model,
110
+ api_key=args.api_key,
111
+ max_tokens=args.max_tokens,
112
+ temperature=args.temperature,
113
+ top_p=args.top_p,
114
+ request_interval=args.request_interval,
115
+ max_retries=args.max_retries,
116
+ retry_base_delay=args.retry_base_delay,
117
+ request_timeout=args.request_timeout,
118
+ )
119
+
120
+ run_scoring(
121
+ client=client,
122
+ expanded_data=expanded_data,
123
+ score_path=args.score_output,
124
+ concurrency=args.concurrency,
125
+ )
126
+
127
+ print("\n" + "=" * 72)
128
+ print("DONE")
129
+ print(f"Scores: {args.score_output}")
130
+ print("=" * 72)
131
+
132
+
133
+ if __name__ == "__main__":
134
+ main()
scripts/infer.sh ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # ======================================================================
3
+ # Vanilla Video Reward Pipeline — vLLM/OpenAI-compatible backend,
4
+ # per-dimension scoring (3 dims):
5
+ # - instruction_following
6
+ # - visual_quality
7
+ # - world_consistency
8
+ # Definitions live in ../prompts/definitions.md.
9
+ #
10
+ # For every video, the model is called once per scoring dimension and
11
+ # asked to first reason, then assign an integer score in 1..5.
12
+ #
13
+ # Input data: a point-wise benchmark JSON whose ``video_path`` field is
14
+ # resolved relative to the JSON's directory.
15
+ #
16
+ # Start a vLLM OpenAI-compatible server in another terminal first.
17
+ #
18
+ # Usage:
19
+ # bash infer.sh
20
+ # bash infer.sh 50
21
+ # bash infer.sh all 12 my_run
22
+ # bash infer.sh all 12 my_run /path/data.json
23
+ #
24
+ # $1 num_samples : number of videos or 'all' (default: all)
25
+ # $2 concurrency : default 32
26
+ # $3 output tag : default infer
27
+ # $4 data json path : default ../data/firm-video-bench.json
28
+ # $5 vLLM base URL : default http://127.0.0.1:8000/v1
29
+ # $6 served model name : default Qwen3-VL-8B-Instruct
30
+ # ======================================================================
31
+
32
+ set -euo pipefail
33
+
34
+ NUM_SAMPLES="${1:-all}"
35
+ CONCURRENCY="${2:-32}"
36
+ TAG="${3:-infer}"
37
+ DATA="${4:-}"
38
+ VLLM_BASE_URL="${5:-${VLLM_BASE_URL:-http://127.0.0.1:8000/v1}}"
39
+ VLLM_MODEL="${6:-${VLLM_MODEL:-Qwen3-VL-8B-Instruct}}"
40
+ VLLM_API_KEY="${VLLM_API_KEY:-EMPTY}"
41
+ VLLM_MAX_TOKENS="${VLLM_MAX_TOKENS:-4096}"
42
+ VLLM_TEMPERATURE="${VLLM_TEMPERATURE:-0}"
43
+ VLLM_REQUEST_INTERVAL="${VLLM_REQUEST_INTERVAL:-0.0}"
44
+ VLLM_MAX_RETRIES="${VLLM_MAX_RETRIES:-3}"
45
+ VLLM_RETRY_BASE_DELAY="${VLLM_RETRY_BASE_DELAY:-2.0}"
46
+ VLLM_REQUEST_TIMEOUT="${VLLM_REQUEST_TIMEOUT:-300}"
47
+
48
+ if [[ "${VLLM_BASE_URL}" != */v1 ]]; then
49
+ VLLM_BASE_URL="${VLLM_BASE_URL%/}/v1"
50
+ fi
51
+
52
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
53
+ PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
54
+
55
+ if [ -z "${DATA}" ]; then
56
+ DATA="${PROJECT_ROOT}/data/firm-video-bench.json"
57
+ fi
58
+
59
+ RESULTS_DIR="${PROJECT_ROOT}/results"
60
+ SCORE_JSON="${RESULTS_DIR}/${TAG}_scores.json"
61
+
62
+ mkdir -p "${RESULTS_DIR}"
63
+
64
+ if command -v curl >/dev/null 2>&1; then
65
+ if ! curl -fsS "${VLLM_BASE_URL}/models" >/dev/null; then
66
+ echo "Cannot reach vLLM endpoint: ${VLLM_BASE_URL}" >&2
67
+ echo "Please start a vLLM OpenAI-compatible server first." >&2
68
+ exit 1
69
+ fi
70
+ fi
71
+
72
+ echo "============================================================"
73
+ echo " Vanilla Pipeline (vLLM/OpenAI-compatible, 3 dims, per-dim calls)"
74
+ echo "============================================================"
75
+ echo " vLLM base: ${VLLM_BASE_URL}"
76
+ echo " Model: ${VLLM_MODEL}"
77
+ echo " Data: ${DATA}"
78
+ echo " Num samples: ${NUM_SAMPLES} (videos)"
79
+ echo " Concurrency: ${CONCURRENCY}"
80
+ echo " Max tokens: ${VLLM_MAX_TOKENS}"
81
+ echo " Temperature: ${VLLM_TEMPERATURE}"
82
+ echo " Scores: ${SCORE_JSON}"
83
+ echo "============================================================"
84
+
85
+ python "${SCRIPT_DIR}/infer.py" \
86
+ --data "${DATA}" \
87
+ --score_output "${SCORE_JSON}" \
88
+ --num_samples "${NUM_SAMPLES}" \
89
+ --concurrency "${CONCURRENCY}" \
90
+ --vllm_base_url "${VLLM_BASE_URL}" \
91
+ --model "${VLLM_MODEL}" \
92
+ --api_key "${VLLM_API_KEY}" \
93
+ --max_tokens "${VLLM_MAX_TOKENS}" \
94
+ --temperature "${VLLM_TEMPERATURE}" \
95
+ --request_interval "${VLLM_REQUEST_INTERVAL}" \
96
+ --max_retries "${VLLM_MAX_RETRIES}" \
97
+ --retry_base_delay "${VLLM_RETRY_BASE_DELAY}" \
98
+ --request_timeout "${VLLM_REQUEST_TIMEOUT}"
99
+
100
+ echo ""
101
+ echo "Done!"
102
+ echo " Scores: ${SCORE_JSON}"
scripts/metric.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute Metrics between model scores and human-labeled scores.
2
+
3
+ Ground truth is loaded from the point-wise sampled file, where each item
4
+ exposes top-level fields ``if_score`` / ``vq_score`` / ``wc_score`` keyed by
5
+ ``video_name``.
6
+ """
7
+ import argparse
8
+ import json
9
+ from pathlib import Path
10
+
11
+ SCRIPT_DIR = Path(__file__).resolve().parent
12
+ PROJECT_ROOT = SCRIPT_DIR.parent
13
+ DEFAULT_RESULTS_DIR = PROJECT_ROOT / "results"
14
+ DEFAULT_GT_FILE = PROJECT_ROOT / "data" / "firm-video-bench.json"
15
+
16
+ MODEL_FILES = {
17
+ "gemini-3.1-pro": "gemini31pro_scores.json",
18
+ "gpt5": "gpt5_scores.json",
19
+ "seed-2.0-lite": "seed20lite_scores.json",
20
+ "qwen3vl-8b": "qwen3vl8b_scores.json",
21
+ "qwen3vl-30b": "qwen3vl30ba3b_scores.json",
22
+ "qwen3vl-235b": "qwen3vl235ba22b_scores.json",
23
+ "internvl3-8b": "internvl3-8b_scores.json",
24
+ "internvl3-38b": "internvl3-38b_scores.json",
25
+ "firm-video-8b-qwen3vl": "firm-video-qwen3vl_scores.json",
26
+ "firm-video-8b-internvl3": "firm-video-internvl3_scores.json"
27
+ }
28
+
29
+ # model dimension -> ground-truth key in GT_FILE
30
+ DIM_MAP = {
31
+ "instruction_following": "if_score",
32
+ "visual_quality": "vq_score",
33
+ "world_consistency": "wc_score",
34
+ }
35
+
36
+
37
+ def load(path):
38
+ with open(path, "r", encoding="utf-8") as f:
39
+ return json.load(f)
40
+
41
+
42
+ def load_gt(path):
43
+ """Return dict: video_name -> {if_score, vq_score, wc_score}."""
44
+ gt = {}
45
+ for item in load(path):
46
+ key = item.get("video_name")
47
+ if not key:
48
+ continue
49
+ gt[key] = {k: item.get(k) for k in DIM_MAP.values()}
50
+ return gt
51
+
52
+
53
+ def _std(abs_errors):
54
+ """绝对误差 |pred - human| 的样本标准差(围绕 MAE 的波动,ddof=1)。"""
55
+ m = len(abs_errors)
56
+ if m <= 1:
57
+ return None
58
+ mean_err = sum(abs_errors) / m
59
+ return (sum((e - mean_err) ** 2 for e in abs_errors) / (m - 1)) ** 0.5
60
+
61
+
62
+ def _accuracy(abs_errors):
63
+ """预测与 human GT 完全相等的比例。"""
64
+ if not abs_errors:
65
+ return None
66
+ return sum(1 for e in abs_errors if e == 0) / len(abs_errors)
67
+
68
+
69
+ def _relaxed_accuracy(abs_errors):
70
+ """预测与 human GT 相差不超过 1 的比例。"""
71
+ if not abs_errors:
72
+ return None
73
+ return sum(1 for e in abs_errors if e <= 1) / len(abs_errors)
74
+
75
+
76
+ def _rankdata(values):
77
+ """返回带 ties 平均秩(1-based)的秩数组。"""
78
+ order = sorted(range(len(values)), key=lambda i: values[i])
79
+ ranks = [0.0] * len(values)
80
+ i = 0
81
+ while i < len(values):
82
+ j = i
83
+ while j + 1 < len(values) and values[order[j + 1]] == values[order[i]]:
84
+ j += 1
85
+ avg_rank = (i + j) / 2.0 + 1.0
86
+ for k in range(i, j + 1):
87
+ ranks[order[k]] = avg_rank
88
+ i = j + 1
89
+ return ranks
90
+
91
+
92
+ def _spearman(pairs):
93
+ """Spearman 秩相关系数(对秩做 Pearson,含 ties 处理)。pairs: [(pred, human)]。"""
94
+ n = len(pairs)
95
+ if n < 2:
96
+ return None
97
+ xs = [p for p, _ in pairs]
98
+ ys = [h for _, h in pairs]
99
+ rx = _rankdata(xs)
100
+ ry = _rankdata(ys)
101
+ mean_rx = sum(rx) / n
102
+ mean_ry = sum(ry) / n
103
+ cov = sum((a - mean_rx) * (b - mean_ry) for a, b in zip(rx, ry))
104
+ var_x = sum((a - mean_rx) ** 2 for a in rx)
105
+ var_y = sum((b - mean_ry) ** 2 for b in ry)
106
+ denom = (var_x * var_y) ** 0.5
107
+ if denom == 0:
108
+ return None
109
+ return cov / denom
110
+
111
+
112
+ def compute_mae(items, gt):
113
+ """Return per-dimension (MAE, std, N), overall (MAE, std) and extra metrics.
114
+
115
+ extra 部分返回 per-dimension 的 (accuracy, relaxed_accuracy, spearman),
116
+ overall 仅返回 (accuracy, relaxed_accuracy)。
117
+ """
118
+ diffs = {dim: [] for dim in DIM_MAP}
119
+ pairs = {dim: [] for dim in DIM_MAP}
120
+ missing = 0
121
+ for item in items:
122
+ key = item.get("video_name")
123
+ human_scores = gt.get(key)
124
+ if human_scores is None:
125
+ missing += 1
126
+ continue
127
+ dims = {
128
+ d["dimension"]: d.get("score")
129
+ for d in item.get("scoring", {}).get("dimensions", [])
130
+ }
131
+ for model_dim, gt_key in DIM_MAP.items():
132
+ human = human_scores.get(gt_key)
133
+ pred = dims.get(model_dim)
134
+ if human is None or pred is None:
135
+ missing += 1
136
+ continue
137
+ try:
138
+ pv = float(pred)
139
+ hv = float(human)
140
+ except (TypeError, ValueError):
141
+ missing += 1
142
+ continue
143
+ diffs[model_dim].append(abs(pv - hv))
144
+ pairs[model_dim].append((pv, hv))
145
+
146
+ per_dim = {
147
+ dim: (sum(v) / len(v) if v else None, _std(v), len(v))
148
+ for dim, v in diffs.items()
149
+ }
150
+ all_diffs = [x for v in diffs.values() for x in v]
151
+ overall = sum(all_diffs) / len(all_diffs) if all_diffs else None
152
+ overall_std = _std(all_diffs)
153
+
154
+ per_dim_extra = {
155
+ dim: (_accuracy(diffs[dim]), _relaxed_accuracy(diffs[dim]), _spearman(pairs[dim]))
156
+ for dim in DIM_MAP
157
+ }
158
+ overall_extra = (
159
+ _accuracy(all_diffs),
160
+ _relaxed_accuracy(all_diffs),
161
+ )
162
+ return per_dim, overall, overall_std, per_dim_extra, overall_extra, missing, len(items)
163
+
164
+
165
+ def parse_args():
166
+ parser = argparse.ArgumentParser(
167
+ description="Compute metrics between model scores and human-labeled scores."
168
+ )
169
+ parser.add_argument(
170
+ "--gt_file",
171
+ type=str,
172
+ default=str(DEFAULT_GT_FILE),
173
+ help="Ground-truth JSON file with if_score/vq_score/wc_score fields.",
174
+ )
175
+ parser.add_argument(
176
+ "--results_dir",
177
+ type=str,
178
+ default=str(DEFAULT_RESULTS_DIR),
179
+ help="Directory containing model score JSON files.",
180
+ )
181
+ return parser.parse_args()
182
+
183
+
184
+ def main():
185
+ args = parse_args()
186
+ gt_file = Path(args.gt_file).expanduser()
187
+ results_dir = Path(args.results_dir).expanduser()
188
+
189
+ if not gt_file.exists():
190
+ print(f"GT file not found: {gt_file}")
191
+ return
192
+ gt = load_gt(gt_file)
193
+ print(f"Loaded {len(gt)} GT entries from {gt_file}")
194
+
195
+ fmt = lambda x: f"{x:.4f}" if x is not None else " N/A "
196
+ header = (
197
+ f"{'Model':<12} {'N':>4} "
198
+ f"{'IF':>10} {'IF_std':>10} "
199
+ f"{'PQ':>10} {'PQ_std':>10} "
200
+ f"{'WC':>10} {'WC_std':>10} "
201
+ f"{'Overall':>10} {'Ovr_std':>10} {'missing':>8}"
202
+ )
203
+ print(header)
204
+ print("-" * len(header))
205
+
206
+ # 收集每个模型的额外指标
207
+ extra_rows = []
208
+ for name, fname in MODEL_FILES.items():
209
+ path = results_dir / fname
210
+ if not path.exists():
211
+ print(f"{name}: file not found: {path}")
212
+ continue
213
+ items = load(path)
214
+ (per_dim, overall, overall_std, per_dim_extra,
215
+ overall_extra, missing, n) = compute_mae(items, gt)
216
+ if_mae, if_std, _ = per_dim["instruction_following"]
217
+ vq_mae, vq_std, _ = per_dim["visual_quality"]
218
+ wc_mae, wc_std, _ = per_dim["world_consistency"]
219
+ print(
220
+ f"{name:<12} {n:>4} "
221
+ f"{fmt(if_mae):>10} {fmt(if_std):>10} "
222
+ f"{fmt(vq_mae):>10} {fmt(vq_std):>10} "
223
+ f"{fmt(wc_mae):>10} {fmt(wc_std):>10} "
224
+ f"{fmt(overall):>10} {fmt(overall_std):>10} {missing:>8}"
225
+ )
226
+ extra_rows.append((name, per_dim_extra, overall_extra))
227
+
228
+ # ---- 额外指标:accuracy / relaxed accuracy / spearman ----
229
+ if extra_rows:
230
+ print("\n== Extra metrics: Accuracy(=) / Relaxed(|d|<=1) / Spearman ==")
231
+ extra_header = (
232
+ f"{'Model':<12} "
233
+ f"{'IF_acc':>8} {'IF_racc':>8} {'IF_spr':>8} "
234
+ f"{'PQ_acc':>8} {'PQ_racc':>8} {'PQ_spr':>8} "
235
+ f"{'WC_acc':>8} {'WC_racc':>8} {'WC_spr':>8} "
236
+ f"{'Ovr_acc':>8} {'Ovr_racc':>8}"
237
+ )
238
+ print(extra_header)
239
+ print("-" * len(extra_header))
240
+ for name, per_dim_extra, overall_extra in extra_rows:
241
+ if_acc, if_racc, if_spr = per_dim_extra["instruction_following"]
242
+ vq_acc, vq_racc, vq_spr = per_dim_extra["visual_quality"]
243
+ wc_acc, wc_racc, wc_spr = per_dim_extra["world_consistency"]
244
+ ovr_acc, ovr_racc = overall_extra
245
+ print(
246
+ f"{name:<12} "
247
+ f"{fmt(if_acc):>8} {fmt(if_racc):>8} {fmt(if_spr):>8} "
248
+ f"{fmt(vq_acc):>8} {fmt(vq_racc):>8} {fmt(vq_spr):>8} "
249
+ f"{fmt(wc_acc):>8} {fmt(wc_racc):>8} {fmt(wc_spr):>8} "
250
+ f"{fmt(ovr_acc):>8} {fmt(ovr_racc):>8}"
251
+ )
252
+
253
+ print("\nDimension mapping: instruction_following<->if_score, "
254
+ "perceptual quality (PQ; input: visual_quality<->vq_score), "
255
+ "world_coherence<->wc_score")
256
+ print("std = 模型打分绝对误差|pred - human|的样本标准差(ddof=1)")
257
+ print("acc = 完全相等准确率; racc = 相差<=1准确率; spr = Spearman秩相关系数")
258
+
259
+
260
+ if __name__ == "__main__":
261
+ main()
tools/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reusable utilities for the open vLLM benchmark pipeline.
2
+
3
+ Public sub-modules:
4
+ - io_utils : safe JSON load/save + JSON parsing from messy LLM outputs.
5
+ - frames : uniform frame sampling from a video to base64 JPEGs.
6
+ - data_loader : point-wise benchmark JSON loader.
7
+ - vllm_client : OpenAI-compatible HTTP client for a vLLM server.
8
+ """
9
+ from .io_utils import (
10
+ load_json_safe,
11
+ save_json_atomic,
12
+ parse_json_from_model_output,
13
+ )
14
+ from .frames import (
15
+ DEFAULT_NUM_SAMPLE_FRAMES,
16
+ extract_frames_from_video,
17
+ )
18
+ from .data_loader import (
19
+ load_pointwise_data,
20
+ ensure_video_local,
21
+ )
22
+ from .vllm_client import VLLMClient
23
+
24
+ __all__ = [
25
+ "load_json_safe",
26
+ "save_json_atomic",
27
+ "parse_json_from_model_output",
28
+ "DEFAULT_NUM_SAMPLE_FRAMES",
29
+ "extract_frames_from_video",
30
+ "load_pointwise_data",
31
+ "ensure_video_local",
32
+ "VLLMClient",
33
+ ]
tools/data_loader.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Point-wise benchmark JSON loader.
2
+
3
+ The expected schema is a flat JSON list of records of the form::
4
+
5
+ {
6
+ "video_name": "000434_c.mp4",
7
+ "video_path": "videos/000434_c.mp4", # relative to the JSON file
8
+ "prompt": "...",
9
+ "source": "vs2",
10
+ "metadata": {
11
+ "visual_score": 4,
12
+ "t2v_score": 4,
13
+ "phy_score": 4
14
+ }
15
+ }
16
+
17
+ ``video_path`` is interpreted relative to the directory that contains the
18
+ JSON file (and may also be absolute).
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import os
24
+ from typing import Any, Tuple
25
+
26
+
27
+ def _json_records(payload: Any, data_path: str) -> list[dict[str, Any]]:
28
+ if not isinstance(payload, list):
29
+ raise ValueError(
30
+ f"JSON data must be a list of records: {data_path} "
31
+ f"(got {type(payload).__name__})"
32
+ )
33
+ if not all(isinstance(item, dict) for item in payload):
34
+ raise ValueError(f"JSON data must contain objects only: {data_path}")
35
+ return payload
36
+
37
+
38
+ def _resolve_video_path(base_dir: str, video_path: str) -> str:
39
+ """Resolve a record's ``video_path`` against the JSON file's directory."""
40
+ if not isinstance(video_path, str) or not video_path:
41
+ return ""
42
+ if os.path.isabs(video_path):
43
+ return video_path
44
+ return os.path.normpath(os.path.join(base_dir, video_path))
45
+
46
+
47
+ def load_pointwise_data(
48
+ data_path: str,
49
+ num_samples: str = "all",
50
+ ) -> Tuple[list[dict[str, Any]], list[dict[str, Any]]]:
51
+ """Load a point-wise benchmark JSON.
52
+
53
+ Parameters
54
+ ----------
55
+ data_path : str
56
+ Path to the benchmark JSON file.
57
+ num_samples : str
58
+ Either ``"all"`` or a positive integer (as a string) capping the
59
+ number of records.
60
+
61
+ Returns
62
+ -------
63
+ (raw_prompts, expanded)
64
+ raw_prompts : list of de-duplicated prompts with their source row
65
+ indices (handy for any prompt-level step).
66
+ expanded : list of per-video records ready for scoring.
67
+ """
68
+ data_path = os.path.abspath(data_path)
69
+ base_dir = os.path.dirname(data_path)
70
+
71
+ with open(data_path, "r", encoding="utf-8") as f:
72
+ records = _json_records(json.load(f), data_path)
73
+ print(f"[data] Loaded {len(records)} videos from {data_path}")
74
+
75
+ if num_samples != "all":
76
+ records = records[: int(num_samples)]
77
+ print(f"[data] Truncated to {len(records)} videos")
78
+
79
+ prompt_to_index: dict[str, int] = {}
80
+ raw_prompts: list[dict[str, Any]] = []
81
+ expanded: list[dict[str, Any]] = []
82
+
83
+ for row_idx, item in enumerate(records):
84
+ video_name = str(item["video_name"])
85
+ prompt_text = str(item["prompt"])
86
+ source_index = prompt_to_index.get(prompt_text)
87
+ if source_index is None:
88
+ source_index = len(raw_prompts)
89
+ prompt_to_index[prompt_text] = source_index
90
+ raw_prompts.append(
91
+ {"prompt": prompt_text, "prompt_id": source_index, "source_rows": []}
92
+ )
93
+ raw_prompts[source_index]["source_rows"].append(row_idx)
94
+
95
+ rel_video_path = item.get("video_path", "")
96
+ local_path = _resolve_video_path(base_dir, rel_video_path)
97
+ source = str(item.get("source", "")).strip()
98
+ metadata = item.get("metadata", {}) or {}
99
+ if not isinstance(metadata, dict):
100
+ metadata = {}
101
+
102
+ expanded.append(
103
+ {
104
+ "video_id": f"{row_idx}_{os.path.splitext(video_name)[0]}",
105
+ "video_name": video_name,
106
+ "caption": prompt_text,
107
+ "video_path": rel_video_path,
108
+ "video_local_path": local_path,
109
+ "source": source,
110
+ "source_index": source_index,
111
+ "source_row_index": row_idx,
112
+ "metadata": metadata,
113
+ }
114
+ )
115
+
116
+ print(
117
+ f"[data] Unique prompts: {len(raw_prompts)}; videos to score: {len(expanded)}"
118
+ )
119
+ return raw_prompts, expanded
120
+
121
+
122
+ def ensure_video_local(item: dict[str, Any]) -> str:
123
+ """Validate that the local video file exists; return its absolute path."""
124
+ local_path = item.get("video_local_path")
125
+ if (
126
+ isinstance(local_path, str)
127
+ and local_path
128
+ and os.path.exists(local_path)
129
+ and os.path.getsize(local_path) > 0
130
+ ):
131
+ return local_path
132
+ raise FileNotFoundError(
133
+ f"Video not found: {local_path or item.get('video_name')}"
134
+ )
tools/frames.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Uniform frame sampling from a video into base64-encoded JPEG strings."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import io
6
+ import os
7
+
8
+ import cv2
9
+ from PIL import Image
10
+
11
+ DEFAULT_NUM_SAMPLE_FRAMES: int = 8
12
+
13
+
14
+ def extract_frames_from_video(
15
+ video_path: str,
16
+ num_frames: int = DEFAULT_NUM_SAMPLE_FRAMES,
17
+ jpeg_quality: int = 90,
18
+ verbose: bool = True,
19
+ ) -> list[str]:
20
+ """Uniformly sample frames from a video and return them as base64 JPEGs.
21
+
22
+ Returns
23
+ -------
24
+ list[str]
25
+ Base64-encoded JPEG strings, in temporal order
26
+ (frame 1 = earliest, frame N = latest).
27
+ """
28
+ cap = cv2.VideoCapture(video_path)
29
+ if not cap.isOpened():
30
+ raise RuntimeError(f"Cannot open video: {video_path}")
31
+
32
+ fps = cap.get(cv2.CAP_PROP_FPS)
33
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
34
+ if fps <= 0 or total_frames <= 0:
35
+ cap.release()
36
+ raise RuntimeError(
37
+ f"Invalid video metadata: fps={fps}, total_frames={total_frames}"
38
+ )
39
+
40
+ duration = total_frames / fps
41
+ num_to_sample = max(1, min(int(num_frames), total_frames))
42
+ if num_to_sample == 1:
43
+ sample_indices = [0]
44
+ else:
45
+ sample_indices = [
46
+ int(round(i * (total_frames - 1) / (num_to_sample - 1)))
47
+ for i in range(num_to_sample)
48
+ ]
49
+
50
+ frame_b64_list: list[str] = []
51
+ for frame_idx in sample_indices:
52
+ cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
53
+ ret, frame = cap.read()
54
+ if not ret:
55
+ continue
56
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
57
+ img = Image.fromarray(frame_rgb)
58
+ buf = io.BytesIO()
59
+ img.save(buf, format="JPEG", quality=int(jpeg_quality))
60
+ frame_b64_list.append(base64.b64encode(buf.getvalue()).decode("utf-8"))
61
+
62
+ cap.release()
63
+ if not frame_b64_list:
64
+ raise RuntimeError(f"Failed to extract any frames from {video_path}")
65
+
66
+ if verbose:
67
+ print(
68
+ f" [frames] Extracted {len(frame_b64_list)} frames from "
69
+ f"{os.path.basename(video_path)} "
70
+ f"(duration={duration:.1f}s, fps={fps:.1f})"
71
+ )
72
+ return frame_b64_list
tools/io_utils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """I/O utilities: safe JSON read/write and lenient JSON parsing
2
+ of LLM outputs (handles ```json fences, trailing prose, etc.)."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ from typing import Any
9
+
10
+
11
+ def load_json_safe(path: str, default: Any) -> Any:
12
+ """Load JSON if file exists; otherwise return ``default``."""
13
+ if os.path.exists(path):
14
+ with open(path, "r", encoding="utf-8") as f:
15
+ return json.load(f)
16
+ return default
17
+
18
+
19
+ def save_json_atomic(data: Any, path: str) -> None:
20
+ """Atomic JSON save (write to .tmp then rename), creates parent dir."""
21
+ parent = os.path.dirname(path) or "."
22
+ os.makedirs(parent, exist_ok=True)
23
+ tmp_path = f"{path}.tmp"
24
+ with open(tmp_path, "w", encoding="utf-8") as f:
25
+ json.dump(data, f, indent=2, ensure_ascii=False)
26
+ os.replace(tmp_path, path)
27
+
28
+
29
+ def parse_json_from_model_output(output_text: str) -> dict[str, Any]:
30
+ """Best-effort extraction of a JSON object from a model response.
31
+
32
+ Order of attempts:
33
+ 1. ```json ... ``` fenced block.
34
+ 2. ``` ... ``` fenced block whose content starts with '{'.
35
+ 3. Substring between the first '{' and the last '}'.
36
+ """
37
+ text = (output_text or "").strip()
38
+
39
+ match = re.search(r"```json\s*(.*?)\s*```", text, re.DOTALL)
40
+ if match:
41
+ try:
42
+ return json.loads(match.group(1))
43
+ except json.JSONDecodeError:
44
+ pass
45
+
46
+ match = re.search(r"```\s*(.*?)\s*```", text, re.DOTALL)
47
+ if match:
48
+ candidate = match.group(1).strip()
49
+ if candidate.startswith("{"):
50
+ try:
51
+ return json.loads(candidate)
52
+ except json.JSONDecodeError:
53
+ pass
54
+
55
+ first_brace = text.find("{")
56
+ last_brace = text.rfind("}")
57
+ if first_brace != -1 and last_brace > first_brace:
58
+ try:
59
+ return json.loads(text[first_brace : last_brace + 1])
60
+ except json.JSONDecodeError:
61
+ pass
62
+
63
+ raise ValueError(
64
+ f"Failed to extract valid JSON from model output. Preview: {text[:300]}..."
65
+ )
tools/vllm_client.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI-compatible HTTP client for a vLLM server.
2
+
3
+ The wire format uses the standard OpenAI ``/v1/chat/completions`` schema.
4
+ Frames are sent inline as base64 ``data:`` URLs.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import time
10
+ from typing import Any, Optional
11
+
12
+ import requests
13
+
14
+
15
+ class VLLMClient:
16
+ """OpenAI-compatible client backed by a vLLM server."""
17
+
18
+ def __init__(
19
+ self,
20
+ base_url: str,
21
+ model_name: str,
22
+ api_key: str = "EMPTY",
23
+ max_tokens: int = 2048,
24
+ temperature: float = 0.0,
25
+ top_p: Optional[float] = None,
26
+ request_interval: float = 0.0,
27
+ max_retries: int = 3,
28
+ retry_base_delay: float = 2.0,
29
+ request_timeout: int = 300,
30
+ ) -> None:
31
+ base_url = (base_url or "").rstrip("/")
32
+ if not base_url.endswith("/v1"):
33
+ base_url = f"{base_url}/v1"
34
+ self.base_url = base_url
35
+ self.model_name = model_name
36
+ self.max_tokens = int(max_tokens)
37
+ self.temperature = float(temperature)
38
+ self.top_p = top_p
39
+ self.request_interval = float(request_interval)
40
+ self.max_retries = int(max_retries)
41
+ self.retry_base_delay = float(retry_base_delay)
42
+ self.request_timeout = int(request_timeout)
43
+ self.headers = {
44
+ "Content-Type": "application/json",
45
+ "Authorization": f"Bearer {api_key or 'EMPTY'}",
46
+ }
47
+
48
+ # ------------------------------------------------------------------
49
+ # Public inference entry points
50
+ # ------------------------------------------------------------------
51
+
52
+ def infer_text_only(
53
+ self,
54
+ user_text: str,
55
+ system_text: Optional[str] = None,
56
+ ) -> str:
57
+ messages = self._build_messages(
58
+ user_content=[{"type": "text", "text": user_text}],
59
+ system_text=system_text,
60
+ )
61
+ return self._infer(messages)
62
+
63
+ def infer_with_frames(
64
+ self,
65
+ user_text: str,
66
+ frame_b64_list: list[str],
67
+ system_text: Optional[str] = None,
68
+ ) -> str:
69
+ content_parts: list[dict[str, Any]] = []
70
+ for frame_b64 in frame_b64_list:
71
+ content_parts.append(
72
+ {
73
+ "type": "image_url",
74
+ "image_url": {"url": f"data:image/jpeg;base64,{frame_b64}"},
75
+ }
76
+ )
77
+ content_parts.append({"type": "text", "text": user_text})
78
+ messages = self._build_messages(
79
+ user_content=content_parts, system_text=system_text
80
+ )
81
+ return self._infer(messages)
82
+
83
+ # ------------------------------------------------------------------
84
+ # Internal helpers
85
+ # ------------------------------------------------------------------
86
+
87
+ @staticmethod
88
+ def _build_messages(
89
+ user_content: list[dict[str, Any]],
90
+ system_text: Optional[str],
91
+ ) -> list[dict[str, Any]]:
92
+ messages: list[dict[str, Any]] = []
93
+ if system_text and system_text.strip():
94
+ messages.append(
95
+ {
96
+ "role": "system",
97
+ "content": [{"type": "text", "text": system_text}],
98
+ }
99
+ )
100
+ messages.append({"role": "user", "content": user_content})
101
+ return messages
102
+
103
+ def _infer(self, messages: list[dict[str, Any]]) -> str:
104
+ url = f"{self.base_url}/chat/completions"
105
+ payload: dict[str, Any] = {
106
+ "model": self.model_name,
107
+ "messages": messages,
108
+ "max_tokens": self.max_tokens,
109
+ "temperature": self.temperature,
110
+ }
111
+ if self.top_p is not None:
112
+ payload["top_p"] = self.top_p
113
+
114
+ resp = self._post_with_retry(url, payload)
115
+ data = resp.json()
116
+ if data.get("error"):
117
+ raise RuntimeError(f"vLLM API error: {data['error']}")
118
+
119
+ choices = data.get("choices", [])
120
+ if not choices:
121
+ raise RuntimeError(
122
+ "vLLM API returned no choices: "
123
+ f"{json.dumps(data, ensure_ascii=False)[:500]}"
124
+ )
125
+
126
+ content = choices[0].get("message", {}).get("content", "")
127
+ if isinstance(content, str) and content.strip():
128
+ return content
129
+ if isinstance(content, list):
130
+ text_parts = [
131
+ part.get("text", "")
132
+ for part in content
133
+ if isinstance(part, dict)
134
+ ]
135
+ text = "\n".join(p for p in text_parts if p)
136
+ if text.strip():
137
+ return text
138
+
139
+ raise RuntimeError(
140
+ "No text found in vLLM response: "
141
+ f"{json.dumps(data, ensure_ascii=False)[:500]}"
142
+ )
143
+
144
+ def _post_with_retry(
145
+ self, url: str, payload: dict[str, Any]
146
+ ) -> requests.Response:
147
+ last_exc: Optional[Exception] = None
148
+ for attempt in range(self.max_retries):
149
+ try:
150
+ resp = requests.post(
151
+ url,
152
+ headers=self.headers,
153
+ json=payload,
154
+ timeout=self.request_timeout,
155
+ )
156
+ resp.raise_for_status()
157
+ return resp
158
+ except Exception as exc: # noqa: BLE001
159
+ last_exc = exc
160
+ if attempt < self.max_retries - 1:
161
+ delay = self.retry_base_delay * (2 ** attempt)
162
+ print(
163
+ f" [vllm retry] attempt {attempt + 1}/"
164
+ f"{self.max_retries} failed: {exc}; sleep {delay:.1f}s"
165
+ )
166
+ time.sleep(delay)
167
+ raise RuntimeError(
168
+ f"vLLM request failed after {self.max_retries} attempts: {last_exc}"
169
+ )