File size: 23,438 Bytes
203a7fb | 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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 | #!/usr/bin/env python3
from __future__ import annotations
import argparse
import ctypes
import gc
import json
import os
import re
import site
import tempfile
import shutil
from pathlib import Path
from typing import Any, Dict, List, Optional
_npp_lib = Path(site.getsitepackages()[0]) / "nvidia" / "npp" / "lib"
_npp_so = _npp_lib / "libnppicc.so.12"
if _npp_so.is_file():
ctypes.CDLL(str(_npp_so), mode=ctypes.RTLD_GLOBAL)
import torch
from tqdm import tqdm
DEFAULT_VIDEO_DIR = Path("./data/lvbench")
DEFAULT_OUTPUT_DIR = Path("./eval_results/lvbench")
VIDEO_TYPES = ["cartoon", "documentary", "live", "selfmedia", "sport", "tv"]
MCQ_PROMPT = (
"Select the best answer to the following multiple-choice question "
"based on the video. Respond with only the letter (A, B, C, or D) "
"of the correct option.\n"
)
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Evaluate on LVBench benchmark.")
p.add_argument("--base-model", type=str,
default="Qwen/Qwen3-Omni-30B-A3B-Instruct")
p.add_argument("--adapter", type=str, default=None)
p.add_argument("--video-dir", type=Path, default=DEFAULT_VIDEO_DIR)
p.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
p.add_argument("--max-samples", type=int, default=-1)
p.add_argument("--max-new-tokens", type=int, default=32)
p.add_argument("--temperature", type=float, default=0.0)
p.add_argument("--label", type=str, default=None)
p.add_argument("--vllm", action="store_true", default=False)
p.add_argument("--tp", type=int, default=None)
p.add_argument("--batch-size", type=int, default=16)
p.add_argument("--gpu-memory-utilization", type=float, default=0.90)
p.add_argument("--max-model-len", type=int, default=65536)
p.add_argument("--max-num-seqs", type=int, default=4)
p.add_argument("--vllm-batch-size", type=int, default=1)
p.add_argument("--enforce-eager", action="store_true", default=False)
p.add_argument("--shard", type=int, default=0)
p.add_argument("--num-shards", type=int, default=1)
p.add_argument("--merge-only", action="store_true", default=False)
return p.parse_args()
def load_model(base_model: str, adapter: Optional[str]):
from omni_model_loading import load_qwen_omni_model
model, processor, _ = load_qwen_omni_model(base_model, adapter)
return model, processor
def run_inference(model, processor, video_path: str, prompt: str,
max_new_tokens: int, temperature: float,
cached_mm: Optional[Dict[str, Any]] = None) -> str:
from qwen_omni_utils import process_mm_info
tmp_dir = tempfile.mkdtemp(prefix="eval_lvb_")
masked_video = os.path.join(tmp_dir, "clip.mp4")
os.symlink(os.path.abspath(video_path), masked_video)
conversation = [
{
"role": "user",
"content": [
{"type": "video", "video": masked_video},
{"type": "text", "text": prompt},
],
}
]
text = processor.apply_chat_template(
conversation, add_generation_prompt=True, tokenize=False,
)
if cached_mm is not None:
audios, images, videos = cached_mm["audios"], cached_mm["images"], cached_mm["videos"]
else:
audios, images, videos = process_mm_info(conversation, use_audio_in_video=True)
inputs = processor(
text=text, audio=audios, images=images, videos=videos,
return_tensors="pt", padding=True, use_audio_in_video=True,
)
model_dtype = next(model.parameters()).dtype
converted = {}
for k, v in inputs.items():
if hasattr(v, "to"):
v = v.to(model.device)
if torch.is_floating_point(v):
v = v.to(model_dtype)
converted[k] = v
inputs = converted
from omni_model_loading import is_omni_thinker_model
is_thinker = is_omni_thinker_model(model)
if is_thinker:
gen_kwargs = {"max_new_tokens": max_new_tokens, "do_sample": temperature > 0}
else:
gen_kwargs = {
"thinker_max_new_tokens": max_new_tokens,
"use_audio_in_video": True,
"return_audio": False,
"do_sample": temperature > 0,
}
if temperature > 0:
gen_kwargs["temperature"] = temperature
gen_kwargs["top_p"] = 0.9
with torch.inference_mode():
output_ids = model.generate(**inputs, **gen_kwargs)
if isinstance(output_ids, tuple):
output_ids = output_ids[0]
prompt_len = inputs["input_ids"].shape[1]
response = processor.batch_decode(
output_ids[:, prompt_len:], skip_special_tokens=True,
)[0].strip()
shutil.rmtree(tmp_dir, ignore_errors=True)
return response
def preprocess_video_for_vllm(video_path: str):
from qwen_omni_utils import process_mm_info
import numpy as np
messages = [{
"role": "user",
"content": [
{"type": "video", "video": video_path, "fps": 2.0, "max_frames": 128},
{"type": "text", "text": "placeholder"},
],
}]
audios, images, videos = process_mm_info(messages, use_audio_in_video=True)
video_tensor = videos[0]
video_np = (video_tensor * 255).byte().numpy()
audio_tuple = None
if audios:
aud = audios[0]
if isinstance(aud, tuple):
audio_tuple = (aud[0].numpy() if hasattr(aud[0], "numpy") else np.asarray(aud[0]),
aud[1])
elif hasattr(aud, "numpy"):
audio_tuple = (aud.numpy(), 16000)
else:
audio_tuple = (np.asarray(aud), 16000)
return video_np, audio_tuple
SYSTEM_PROMPT = (
"You are Qwen, a virtual human developed by the Qwen Team, Alibaba "
"Group, capable of perceiving auditory and visual inputs, as well as "
"generating text and speech."
)
def build_vllm_prompt(question: str, base_model: str) -> str:
from omni_model_loading import vllm_user_mm_prefix
mm = vllm_user_mm_prefix(base_model, include_audio=True)
return (
f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n"
f"<|im_start|>user\n"
f"{mm}"
f"{question}<|im_end|>\n"
f"<|im_start|>assistant\n"
)
def extract_answer(text: str) -> str:
text = text.strip()
prefixes = [
"The best answer is", "The correct answer is",
"The answer is", "The answer", "Best answer:", "Best option:",
]
for prefix in prefixes:
text = text.replace(prefix, "")
if len(text.split()) > 10 and not re.search(r"[ABCD]", text):
return ""
m = re.search(r"[ABCD]", text)
return m[0] if m else ""
def load_lvbench(video_dir: Path, max_samples: int) -> List[Dict[str, Any]]:
from datasets import load_dataset
ds = load_dataset("lmms-lab/LVBench", split="train")
data = []
skipped = 0
for row in ds:
vid = row["key"]
video_path = video_dir / f"{vid}.mp4"
if not video_path.exists():
skipped += 1
continue
prompt = MCQ_PROMPT + row["question"] + "\nThe best answer is:"
data.append({
"uid": row["uid"],
"video_id": vid,
"video_path": str(video_path),
"video_type": row["type"],
"question_type": row["question_type"],
"question": row["question"],
"gt_answer": row["answer"],
"time_reference": row.get("time_reference", ""),
"prompt": prompt,
})
if skipped:
print(f"[data] Skipped {skipped} questions (video not found)")
if max_samples > 0:
data = data[:max_samples]
return data
def compute_metrics(results: List[Dict[str, Any]]) -> Dict[str, Any]:
total = len(results)
if total == 0:
return {}
correct = sum(1 for r in results if r["pred_answer"].upper() == r["gt_answer"].upper())
overall_acc = correct / total
def acc_for(items):
if not items:
return None
c = sum(1 for r in items if r["pred_answer"].upper() == r["gt_answer"].upper())
return round(c / len(items), 4)
per_type = {}
for vt in VIDEO_TYPES:
subset = [r for r in results if r["video_type"] == vt]
if subset:
per_type[vt] = {"accuracy": acc_for(subset), "count": len(subset)}
q_types = set()
for r in results:
if isinstance(r.get("question_type"), list):
q_types.update(r["question_type"])
elif r.get("question_type"):
q_types.add(r["question_type"])
per_qtype = {}
for qt in sorted(q_types):
subset = [r for r in results if qt in (r.get("question_type", [])
if isinstance(r.get("question_type"), list) else [r.get("question_type")])]
if subset:
per_qtype[qt] = {"accuracy": acc_for(subset), "count": len(subset)}
return {
"total_samples": total,
"overall_accuracy": round(overall_acc, 4),
"per_video_type": per_type,
"per_question_type": per_qtype,
}
def print_summary(metrics: Dict[str, Any], label: str) -> None:
print()
print(f"{'=' * 65}")
print(f" LVBench Summary: {label}")
print(f"{'=' * 65}")
print(f" Total samples: {metrics['total_samples']}")
print(f" Overall Accuracy: {metrics['overall_accuracy']:.1%}")
print(f" βββ Per Video Type βββ")
for vt in VIDEO_TYPES:
if vt in metrics.get("per_video_type", {}):
d = metrics["per_video_type"][vt]
print(f" {vt:15s}: {d['accuracy']:.1%} ({d['count']} questions)")
print(f" βββ Per Question Type βββ")
for qt, d in sorted(metrics.get("per_question_type", {}).items()):
print(f" {qt:30s}: {d['accuracy']:.1%} ({d['count']})")
print(f"{'=' * 65}")
def _load_processed_uids(out_dir: Path) -> set:
processed: set = set()
for p in sorted(out_dir.glob("eval_results*.jsonl")):
try:
with open(p) as f:
for line in f:
try:
processed.add(json.loads(line)["uid"])
except Exception:
continue
except FileNotFoundError:
continue
return processed
def _finalize_metrics(out_dir: Path, label: str, args: argparse.Namespace,
vllm_preprocess_stats: Optional[Dict[str, int]] = None) -> None:
results_by_uid: Dict[str, Dict[str, Any]] = {}
source_files = sorted(out_dir.glob("eval_results*.jsonl"))
for p in source_files:
with open(p) as f:
for line in f:
try:
obj = json.loads(line)
except Exception:
continue
results_by_uid[obj["uid"]] = obj
if not results_by_uid:
print("[warn] No results to compute metrics from.")
return
all_results = list(results_by_uid.values())
merged_jsonl = out_dir / "eval_results.jsonl"
with open(merged_jsonl, "w", encoding="utf-8") as f:
for r in all_results:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"[merge] Wrote {len(all_results)} unique results to {merged_jsonl} "
f"(merged {len(source_files)} source file(s)).")
metrics = compute_metrics(all_results)
metrics["eval_config"] = {
"base_model": args.base_model,
"adapter": args.adapter,
"video_dir": str(args.video_dir),
"max_new_tokens": args.max_new_tokens,
"temperature": args.temperature,
"vllm": bool(args.vllm),
"max_num_seqs": args.max_num_seqs,
"vllm_batch_size": args.vllm_batch_size,
"max_model_len": args.max_model_len,
"num_shards": args.num_shards,
}
if vllm_preprocess_stats is not None:
metrics["eval_config"]["vllm_preprocess_skips"] = vllm_preprocess_stats
metrics_json = out_dir / "metrics.json"
summary_txt = out_dir / "summary.txt"
with open(metrics_json, "w", encoding="utf-8") as f:
json.dump(metrics, f, indent=2, ensure_ascii=False)
print_summary(metrics, label)
with open(summary_txt, "w", encoding="utf-8") as f:
import io, contextlib
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
print_summary(metrics, label)
f.write(buf.getvalue())
print(f"\n[output] Results: {merged_jsonl}")
print(f"[output] Metrics: {metrics_json}")
print(f"[output] Summary: {summary_txt}")
def main() -> None:
args = parse_args()
label = args.label or (
Path(args.adapter).name if args.adapter
else Path(args.base_model).name
)
out_dir = args.output_dir / label
out_dir.mkdir(parents=True, exist_ok=True)
if args.num_shards < 1 or args.shard < 0 or args.shard >= args.num_shards:
raise SystemExit(f"Invalid --shard {args.shard} / --num-shards {args.num_shards}")
is_sharded = args.num_shards > 1
shard_tag = f".shard{args.shard}of{args.num_shards}" if is_sharded else ""
results_jsonl = out_dir / f"eval_results{shard_tag}.jsonl"
if args.merge_only:
print(f"[merge-only] out_dir={out_dir}")
_finalize_metrics(out_dir, label, args)
return
print("[data] Loading LVBench dataset...")
test_data = load_lvbench(args.video_dir, args.max_samples)
print(f"[data] {len(test_data)} total questions")
if is_sharded:
shard_data = [x for i, x in enumerate(test_data)
if i % args.num_shards == args.shard]
print(f"[shard] shard={args.shard}/{args.num_shards} -> "
f"{len(shard_data)} questions in this shard")
test_data = shard_data
processed = _load_processed_uids(out_dir)
if processed:
print(f"[resume] {len(processed)} uids already processed across all "
f"eval_results*.jsonl under {out_dir}")
use_vllm = args.vllm
model = processor = llm = None
vllm_preprocess_stats: Dict[str, int] | None = None
if use_vllm:
from vllm import LLM, SamplingParams
tp = args.tp or torch.cuda.device_count()
model_path = args.base_model
print(f"[vllm] Preprocessing videos (before model load) ...")
todo = [item for item in test_data if item["uid"] not in processed]
unique_videos = list(dict.fromkeys(item["video_path"] for item in todo))
from omni_model_loading import parallel_preprocess_videos
preprocessed, preprocessed_audio, preprocess_failed_paths = parallel_preprocess_videos(
unique_videos, preprocess_video_for_vllm,
)
n_pp_skip = sum(1 for item in todo if item["video_path"] in preprocess_failed_paths)
if preprocess_failed_paths:
print(
f"[vllm] Preprocess failed for {len(preprocess_failed_paths)} video(s), "
f"{n_pp_skip} question(s) will not use vLLM (run continues)."
)
vllm_preprocess_stats = {
"preprocess_failed_videos": len(preprocess_failed_paths),
"preprocess_skipped_questions": n_pp_skip,
}
from omni_model_loading import cap_vllm_max_model_len
vllm_max_len = cap_vllm_max_model_len(model_path, args.max_model_len)
print(f"[vllm] Loading {model_path} with tp={tp} "
f"(max_num_seqs={args.max_num_seqs}, max_model_len={vllm_max_len}) ...")
llm_kwargs = dict(
model=model_path,
tensor_parallel_size=tp,
max_model_len=vllm_max_len,
max_num_seqs=args.max_num_seqs,
gpu_memory_utilization=args.gpu_memory_utilization,
dtype="bfloat16",
trust_remote_code=True,
limit_mm_per_prompt={"video": 1, "audio": 1},
enforce_eager=args.enforce_eager,
)
llm = LLM(**llm_kwargs)
sampling_params = SamplingParams(
temperature=args.temperature if args.temperature > 0 else 0.0,
top_p=0.9 if args.temperature > 0 else 1.0,
max_tokens=args.max_new_tokens,
)
vllm_todo = [item for item in todo if item["video_path"] in preprocessed]
fallback_items = []
print(f"[vllm] {len(vllm_todo)} questions ready, running inference "
f"(batch={args.vllm_batch_size}) ...")
def _write_result(item: Dict[str, Any], raw_output: str) -> None:
pred = extract_answer(raw_output)
result = {
"uid": item["uid"],
"video_id": item["video_id"],
"video_type": item["video_type"],
"question_type": item["question_type"],
"gt_answer": item["gt_answer"],
"pred_answer": pred,
"correct": pred.upper() == item["gt_answer"].upper(),
"raw_output": raw_output,
}
with open(results_jsonl, "a", encoding="utf-8") as f:
f.write(json.dumps(result, ensure_ascii=False) + "\n")
processed.add(item["uid"])
def _build_inp(item: Dict[str, Any]) -> Dict[str, Any]:
inp = {
"prompt": build_vllm_prompt(item["prompt"], args.base_model),
"multi_modal_data": {"video": preprocessed[item["video_path"]]},
}
if item["video_path"] in preprocessed_audio:
inp["multi_modal_data"]["audio"] = preprocessed_audio[item["video_path"]]
return inp
def _flush(batch: List[Dict[str, Any]]) -> None:
if not batch:
return
inps = [b["inp"] for b in batch]
try:
outs = llm.generate(inps, sampling_params=sampling_params)
for b, o in zip(batch, outs):
_write_result(b["item"], o.outputs[0].text.strip())
return
except (ValueError, RuntimeError) as exc:
if "longer than the maximum model length" not in str(exc):
raise
for b in batch:
try:
outs = llm.generate([b["inp"]], sampling_params=sampling_params)
_write_result(b["item"], outs[0].outputs[0].text.strip())
except (ValueError, RuntimeError) as exc2:
if "longer than the maximum model length" in str(exc2):
print(f" [too long] {b['item']['uid']} -> fallback")
fallback_items.append(b["item"])
else:
raise
batch: List[Dict[str, Any]] = []
for i, item in enumerate(vllm_todo):
if item["uid"] in processed:
continue
batch.append({"inp": _build_inp(item), "item": item})
if len(batch) >= max(1, args.vllm_batch_size):
_flush(batch)
batch = []
if (i + 1) % 50 == 0:
print(f" [vllm] [{i+1}/{len(vllm_todo)}] submitted, "
f"{len(fallback_items)} deferred")
_flush(batch)
preprocessed.clear()
preprocessed_audio.clear()
if fallback_items:
print(f"[fallback] Running {len(fallback_items)} long-video questions with transformers ...")
del llm
gc.collect()
torch.cuda.empty_cache()
fallback_items.sort(key=lambda it: it["video_path"])
model, processor = load_model(args.base_model, args.adapter)
last_vp: Optional[str] = None
cached_mm: Optional[Dict[str, Any]] = None
for item in tqdm(fallback_items, desc="Fallback", unit="q"):
if item["uid"] in processed:
continue
if item["video_path"] != last_vp:
cached_mm = None
last_vp = item["video_path"]
try:
if cached_mm is None:
from qwen_omni_utils import process_mm_info as _pmi
tmp_conv = [{"role": "user", "content": [
{"type": "video", "video": item["video_path"]},
{"type": "text", "text": item["prompt"]},
]}]
a, im, v = _pmi(tmp_conv, use_audio_in_video=True)
cached_mm = {"audios": a, "images": im, "videos": v}
raw_output = run_inference(
model, processor, item["video_path"], item["prompt"],
args.max_new_tokens, args.temperature,
cached_mm=cached_mm,
)
except Exception as exc:
import traceback
print(f" [error] {item['uid']}: {exc}")
traceback.print_exc()
raw_output = ""
cached_mm = None
pred = extract_answer(raw_output)
result = {
"uid": item["uid"],
"video_id": item["video_id"],
"video_type": item["video_type"],
"question_type": item["question_type"],
"gt_answer": item["gt_answer"],
"pred_answer": pred,
"correct": pred.upper() == item["gt_answer"].upper(),
"raw_output": raw_output,
}
with open(results_jsonl, "a", encoding="utf-8") as f:
f.write(json.dumps(result, ensure_ascii=False) + "\n")
processed.add(item["uid"])
gc.collect()
torch.cuda.empty_cache()
else:
print("[model] Loading model...")
model, processor = load_model(args.base_model, args.adapter)
for item in tqdm(test_data, desc="LVBench", unit="q"):
if item["uid"] in processed:
continue
try:
raw_output = run_inference(
model, processor, item["video_path"], item["prompt"],
args.max_new_tokens, args.temperature,
)
except Exception as exc:
import traceback
print(f" [error] {item['uid']}: {exc}")
traceback.print_exc()
raw_output = ""
pred = extract_answer(raw_output)
result = {
"uid": item["uid"],
"video_id": item["video_id"],
"video_type": item["video_type"],
"question_type": item["question_type"],
"gt_answer": item["gt_answer"],
"pred_answer": pred,
"correct": pred.upper() == item["gt_answer"].upper(),
"raw_output": raw_output,
}
with open(results_jsonl, "a", encoding="utf-8") as f:
f.write(json.dumps(result, ensure_ascii=False) + "\n")
processed.add(item["uid"])
gc.collect()
torch.cuda.empty_cache()
if is_sharded:
print(f"[shard {args.shard}/{args.num_shards}] finished inference. "
f"Run `--merge-only` after all shards complete to produce final metrics.")
return
_finalize_metrics(out_dir, label, args, vllm_preprocess_stats)
if __name__ == "__main__":
main()
|