devboxbackup / playground /inference /active_cases /eval_active_cases.py
jasonfan's picture
Add files using upload-large-folder tool
cb5f642 verified
"""
Evaluate a single VLM on the 238 active (hard) cases.
Usage:
python eval_active_cases.py \
--model-name qwen3vl_finetuned \
--frames-dir /mlx/users/jiashuo.fan/playground/inference/active_cases/frames_cache \
--output-dir /mnt/bn/bohanzhainas1/jiashuo/exp/active_cases_eval
# Override model path:
python eval_active_cases.py --model-name internvl3_8b --model-path /some/other/path ...
Model types supported:
qwen3vl - Qwen3-VL (uses Qwen3VLForConditionalGeneration + qwen_vl_utils)
qwen25vl - Qwen2.5-VL / Qwen2-VL (uses Qwen2VLForConditionalGeneration + qwen_vl_utils)
internvl - InternVL (uses InternVLChatModel with trust_remote_code)
llava - LLaVA-OneVision (LlavaQwenForCausalLM)
generic - AutoModelForCausalLM with AutoProcessor / AutoTokenizer
"""
import argparse
import base64
import glob
import io
import json
import os
import re
import sys
import time
import traceback
import types
from pathlib import Path
# Stub xformers so models that optionally import it (e.g. CogVLM2) can still
# load without having xformers installed. Replace memory_efficient_attention
# with PyTorch's scaled_dot_product_attention.
if "xformers" not in sys.modules:
import torch as _torch
_xops = types.ModuleType("xformers.ops")
def _mem_eff_attn(query, key, value, attn_bias=None, scale=None, **kw):
# xformers layout: (B, S, H, D); torch SDPA layout: (B, H, S, D)
q = query.transpose(1, 2)
k = key.transpose(1, 2)
v = value.transpose(1, 2)
out = _torch.nn.functional.scaled_dot_product_attention(
q, k, v, attn_mask=attn_bias, scale=scale,
)
return out.transpose(1, 2) # back to (B, S, H, D)
_xops.memory_efficient_attention = _mem_eff_attn
_xformers = types.ModuleType("xformers")
_xformers.ops = _xops
sys.modules["xformers"] = _xformers
sys.modules["xformers.ops"] = _xops
from PIL import Image
# ── defaults ──────────────────────────────────────────────────────────────────
FRAMES_DIR = Path("/mlx/users/jiashuo.fan/playground/inference/active_cases/frames_cache")
OUTPUT_DIR = Path("/mnt/bn/bohanzhainas1/jiashuo/exp/active_cases_eval")
FRAMES_PER_VIDEO = 8 # subsample from the 16 stored frames
MAX_PIXELS = 336 * 336
MAX_NEW_TOKENS = 128
SAVE_INTERVAL = 20
# ── SYSTEM prompt for non-fine-tuned models ───────────────────────────────────
BASE_SYSTEM_PROMPT = """You are an expert at analyzing pairs of TikTok videos for a "Proactive Publish" attribution task. Given two videos, you must determine whether watching Video 1 (consumption video) CAUSED or INSPIRED the user to create Video 2 (publish video).
label=1 means the videos are causally related (e.g., same meme/challenge/song, same viral format, same template).
label=0 means they are NOT causally related (they may be in the same broad category but lack direct inspiration).
You MUST respond with a JSON object and nothing else."""
BASE_USER_TEMPLATE = """Analyze these two TikTok videos:
Video 1 (consumption video - what the user watched):
{view_frames_placeholder}
Video 2 (publish video - what the user then created):
{pub_frames_placeholder}
Category: {class_name}
Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?
Respond with JSON only:
{{"reasoning": "<brief explanation>", "label": 0 or 1}}"""
# ── helpers ───────────────────────────────────────────────────────────────────
def load_sample_files(frames_dir: Path) -> list[dict]:
files = sorted(frames_dir.glob("*.json"))
samples = []
for f in files:
try:
data = json.loads(f.read_text())
if data.get("source") == "failed" or not data.get("messages"):
print(f" [SKIP] {f.stem} (no frames / failed extraction)", flush=True)
continue
samples.append(data)
except Exception as e:
print(f" [SKIP] {f.name}: {e}", flush=True)
return samples
def b64_to_pil(b64_str: str) -> Image.Image:
img = Image.open(io.BytesIO(base64.b64decode(b64_str))).convert("RGB")
w, h = img.size
if w * h > MAX_PIXELS:
scale = (MAX_PIXELS / (w * h)) ** 0.5
img = img.resize((int(w * scale), int(h * scale)), Image.BILINEAR)
return img
def subsample_frames(frames: list[str], n: int = FRAMES_PER_VIDEO) -> list[str]:
"""Pick n evenly-spaced frames from a list of base64 frames."""
if len(frames) <= n:
return frames
step = len(frames) / n
return [frames[int(i * step)] for i in range(n)]
def parse_sample_for_finetuned(sample: dict) -> tuple[list, int]:
"""
Parse sample in training format: return (content_items, gt_label).
content_items match the format used during training.
"""
msgs = sample["messages"]
user_content = msgs[0]["content"]
gt_text = msgs[1]["content"][0]["text"] if len(msgs) > 1 else '{"label": 1}'
gt_label = extract_label(gt_text)
content_items = []
for item in user_content:
if item["type"] == "video":
frames = subsample_frames(item["video"], FRAMES_PER_VIDEO)
for b64 in frames:
content_items.append({"type": "image", "image": b64_to_pil(b64)})
elif item["type"] == "text":
content_items.append({"type": "text", "text": item["text"]})
elif item["type"] == "image":
content_items.append({"type": "image", "image": b64_to_pil(item["image"])})
return content_items, gt_label
def parse_sample_for_base(sample: dict) -> tuple[list, int]:
"""
Parse sample for non-fine-tuned models: build a natural language prompt
with PIL images interleaved with text.
"""
msgs = sample["messages"]
user_content = msgs[0]["content"]
gt_text = msgs[1]["content"][0]["text"] if len(msgs) > 1 else '{"label": 1}'
gt_label = extract_label(gt_text)
class_name = sample.get("class_name", "")
# Collect video frame lists
video_lists = []
for item in user_content:
if item["type"] == "video":
video_lists.append(item["video"])
view_frames_b64 = subsample_frames(video_lists[0], FRAMES_PER_VIDEO) if len(video_lists) > 0 else []
pub_frames_b64 = subsample_frames(video_lists[1], FRAMES_PER_VIDEO) if len(video_lists) > 1 else []
view_pil = [b64_to_pil(b) for b in view_frames_b64]
pub_pil = [b64_to_pil(b) for b in pub_frames_b64]
return view_pil, pub_pil, class_name, gt_label
def extract_label(text: str) -> int | None:
try:
stripped = text.strip()
if "```" in stripped:
m = re.search(r"```(?:json)?\s*([\s\S]+?)```", stripped)
if m:
stripped = m.group(1).strip()
return int(json.loads(stripped)["label"])
except Exception:
m = re.search(r'"label"\s*:\s*([01])', text)
return int(m.group(1)) if m else None
def compute_stats(results: list[dict]) -> dict:
from collections import defaultdict
label_stats = defaultdict(lambda: {"tp": 0, "fp": 0, "fn": 0, "tn": 0})
correct = evaluated = parse_fail = 0
for r in results:
if "error" in r:
continue
if r.get("pred_label") is None:
parse_fail += 1
continue
gt, pred = r.get("gt_label"), r["pred_label"]
if gt is None:
continue
evaluated += 1
if gt == pred:
correct += 1
for label in [0, 1]:
if gt == label and pred == label:
label_stats[label]["tp"] += 1
elif gt != label and pred == label:
label_stats[label]["fp"] += 1
elif gt == label and pred != label:
label_stats[label]["fn"] += 1
else:
label_stats[label]["tn"] += 1
per_class = {}
for label, s in label_stats.items():
tp, fp, fn = s["tp"], s["fp"], s["fn"]
prec = tp / (tp + fp) if (tp + fp) > 0 else 0.0
rec = tp / (tp + fn) if (tp + fn) > 0 else 0.0
f1 = 2 * prec * rec / (prec + rec) if (prec + rec) > 0 else 0.0
per_class[str(label)] = {
"precision": round(prec, 4),
"recall": round(rec, 4),
"f1": round(f1, 4),
"support": tp + fn,
}
return {
"accuracy": round(correct / evaluated, 4) if evaluated else 0.0,
"correct": correct,
"evaluated": evaluated,
"parse_failures": parse_fail,
"per_class": per_class,
}
def save_results(out_path: Path, model_name: str, model_path: str,
results: list, stats: dict):
out_path.write_text(json.dumps({
"model_name": model_name,
"model_path": model_path,
"frames_per_video": FRAMES_PER_VIDEO,
"max_pixels": MAX_PIXELS,
"total_samples": len(results),
**stats,
"results": results,
}, ensure_ascii=False, indent=2))
# ══════════════════════════════════════════════════════════════════════════════
# Model loaders
# ══════════════════════════════════════════════════════════════════════════════
def load_qwen3vl(model_path: str):
import torch
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
print(f"Loading Qwen3-VL from {model_path}", flush=True)
model = Qwen3VLForConditionalGeneration.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
device_map="cuda:0",
trust_remote_code=True,
)
model.eval()
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
return model, processor
def load_qwen25vl(model_path: str):
import torch
from transformers import AutoProcessor
print(f"Loading Qwen2-VL / Qwen2.5-VL from {model_path}", flush=True)
# Qwen2.5-VL uses Qwen2_5_VLForConditionalGeneration; Qwen2-VL uses Qwen2VLForConditionalGeneration
try:
from transformers import Qwen2_5_VLForConditionalGeneration
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
device_map="cuda:0",
trust_remote_code=True,
)
print("Loaded as Qwen2_5_VL", flush=True)
except Exception:
from transformers import Qwen2VLForConditionalGeneration
model = Qwen2VLForConditionalGeneration.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
device_map="cuda:0",
trust_remote_code=True,
)
print("Loaded as Qwen2VL (fallback)", flush=True)
model.eval()
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
return model, processor
def load_internvl(model_path: str):
import torch
from transformers import AutoModel, AutoTokenizer
print(f"Loading InternVL from {model_path}", flush=True)
model = AutoModel.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
device_map="cuda:0",
trust_remote_code=True,
)
model.eval()
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
return model, tokenizer
def load_llava(model_path: str):
import torch
from transformers import AutoProcessor, AutoModelForVision2Seq
print(f"Loading LLaVA from {model_path}", flush=True)
model = AutoModelForVision2Seq.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="cuda:0",
trust_remote_code=True,
)
model.eval()
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
return model, processor
def load_llama32_vision(model_path: str):
import torch
from transformers import MllamaForConditionalGeneration, AutoProcessor
print(f"Loading Llama-3.2-Vision from {model_path}", flush=True)
model = MllamaForConditionalGeneration.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="cuda:0",
)
model.eval()
processor = AutoProcessor.from_pretrained(model_path)
return model, processor
def load_phi3_vision(model_path: str):
import torch
from transformers import AutoModelForCausalLM, AutoProcessor
print(f"Loading Phi-3.5-vision from {model_path}", flush=True)
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="cuda:0",
trust_remote_code=True,
_attn_implementation="flash_attention_2",
)
model.eval()
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True, num_crops=4)
return model, processor
def load_minicpm_v(model_path: str):
import torch
from transformers import AutoModel, AutoTokenizer
print(f"Loading MiniCPM-V from {model_path}", flush=True)
model = AutoModel.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="cuda:0",
trust_remote_code=True,
)
model.eval()
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
return model, tokenizer
def load_pixtral(model_path: str):
import torch
from transformers import LlavaForConditionalGeneration, AutoProcessor
print(f"Loading Pixtral from {model_path}", flush=True)
model = LlavaForConditionalGeneration.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="cuda:0",
)
model.eval()
processor = AutoProcessor.from_pretrained(model_path)
return model, processor
def load_janus(model_path: str):
import torch
from transformers import AutoModelForCausalLM, AutoProcessor
print(f"Loading Janus-Pro from {model_path}", flush=True)
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="cuda:0",
trust_remote_code=True,
)
model.eval()
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
return model, processor
def load_cogvlm2(model_path: str):
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
print(f"Loading CogVLM2 from {model_path}", flush=True)
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="cuda:0",
trust_remote_code=True,
)
model.eval()
return model, tokenizer
def run_cogvlm2(model, tokenizer, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for CogVLM2 (requires build_conversation_input_ids)."""
import torch
from PIL import Image
# CogVLM2 supports only a single image; create a 4x2 grid:
# top row: 4 frames from video 1, bottom row: 4 frames from video 2
n = min(4, len(view_pil))
m = min(4, len(pub_pil))
frames = view_pil[:n] + pub_pil[:m]
cell_w, cell_h = 224, 224
cols = 4
rows = (len(frames) + cols - 1) // cols
grid = Image.new("RGB", (cols * cell_w, rows * cell_h), (0, 0, 0))
for idx, fr in enumerate(frames):
fr_r = fr.resize((cell_w, cell_h))
grid.paste(fr_r, ((idx % cols) * cell_w, (idx // cols) * cell_h))
query = (
f"The image shows a grid of video frames: "
f"top row has {n} frames from Video 1 (consumption), "
f"bottom row has {m} frames from Video 2 (publish). "
f"Category: {class_name}. "
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2? "
"label=1: causally related, label=0: not causally related. "
'JSON only: {"reasoning": "...", "label": 0 or 1}'
)
input_by_model = model.build_conversation_input_ids(
tokenizer,
query=query,
history=[],
images=[grid],
template_version="chat",
)
device = next(model.parameters()).device
inputs = {
"input_ids": input_by_model["input_ids"].unsqueeze(0).to(device),
"token_type_ids": input_by_model["token_type_ids"].unsqueeze(0).to(device),
"attention_mask": input_by_model["attention_mask"].unsqueeze(0).to(device),
"images": [[img.to(device).to(torch.bfloat16)
for img in input_by_model["images"]]],
}
# Patch methods removed from transformers >= 4.46 that CogVLM2 relies on.
if not hasattr(model, "_extract_past_from_model_output"):
def _extract_past(model_output, standardize_cache_format=False):
return getattr(model_output, "past_key_values", None)
model._extract_past_from_model_output = _extract_past
# Patch llm_forward to handle ((None,None),...) past_key_values from newer transformers
_orig_llm_forward = model.model.llm_forward
def _patched_llm_forward(self_or_first, *args, **kwargs):
# Detect if called as bound method (self is model.model) or unbound
if callable(_orig_llm_forward):
# get past_key_values from kwargs or args
pkv = kwargs.get("past_key_values", None)
if pkv is not None and hasattr(pkv, "__len__"):
# If all layers are None, treat as None
if all((layer is None or (hasattr(layer, "__len__") and all(t is None for t in layer)))
for layer in pkv):
kwargs["past_key_values"] = None
return _orig_llm_forward(*args, **kwargs) if args else _orig_llm_forward(**kwargs)
# simpler: just patch at the module level
import types as _types
def _safe_llm_forward(self, *args, **kwargs):
pkv = kwargs.get("past_key_values", None)
if pkv is not None and hasattr(pkv, "__len__"):
if all((layer is None or (hasattr(layer, "__len__") and all(t is None for t in layer)))
for layer in pkv):
kwargs["past_key_values"] = None
return _orig_llm_forward(*args, **kwargs)
model.model.llm_forward = _types.MethodType(_safe_llm_forward, model.model)
gen_kwargs = {
"max_new_tokens": MAX_NEW_TOKENS,
"pad_token_id": tokenizer.eos_token_id,
"do_sample": False,
}
with torch.no_grad():
outputs = model.generate(**inputs, **gen_kwargs)
outputs = outputs[:, inputs["input_ids"].shape[1]:]
return tokenizer.decode(outputs[0], skip_special_tokens=True)
def load_molmo(model_path: str):
import sys, torch
from transformers import AutoModelForCausalLM, AutoProcessor
# Molmo's image_preprocessing_molmo.py has a conditional `import tensorflow` that
# causes check_imports to fail if tensorflow is not installed. Stub it out.
if "tensorflow" not in sys.modules:
# Create a permissive tensorflow stub: any attribute access returns a
# no-op callable/class so Molmo's check_imports and processor don't crash.
class _TFStub(types.ModuleType):
def __getattr__(self, name):
if name.startswith("_"):
raise AttributeError(name)
# Return a dummy class / callable for unknown attrs
dummy = type(name, (), {"__call__": lambda self, *a, **kw: False})()
setattr(self, name, dummy)
return dummy
tf_stub = _TFStub("tensorflow")
tf_stub.Tensor = type("Tensor", (), {})
tf_stub.Variable = type("Variable", (), {})
tf_stub.is_tensor = lambda x: False
tf_stub.string = str
tf_stub.float32 = "float32"
tf_stub.int32 = "int32"
_keras = _TFStub("tensorflow.keras")
_keras_backend = _TFStub("tensorflow.keras.backend")
_keras_backend.image_data_format = lambda: "channels_last"
_keras.backend = _keras_backend
tf_stub.keras = _keras
tf_stub.io = _TFStub("tensorflow.io")
sys.modules["tensorflow"] = tf_stub
sys.modules["tensorflow.io"] = tf_stub.io
sys.modules["tensorflow.keras"] = _keras
sys.modules["tensorflow.keras.backend"] = _keras_backend
print(f"Loading Molmo from {model_path}", flush=True)
processor = AutoProcessor.from_pretrained(
model_path, trust_remote_code=True,
torch_dtype=torch.bfloat16,
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="cuda:0",
trust_remote_code=True,
)
model.eval()
return model, processor
def load_moondream(model_path: str):
import shutil, torch
from pathlib import Path
from transformers import AutoModelForCausalLM, AutoTokenizer
# Pre-populate HF modules cache with ALL .py files from the local model dir
# so that transformers' dynamic_module_utils can resolve all relative imports.
model_name = Path(model_path).name
cache_dir = Path.home() / ".cache" / "huggingface" / "modules" / "transformers_modules" / model_name
if cache_dir.exists():
shutil.rmtree(cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True)
for py_file in Path(model_path).glob("*.py"):
shutil.copy2(py_file, cache_dir / py_file.name)
print(f"Pre-populated cache with {len(list(cache_dir.glob('*.py')))} .py files", flush=True)
print(f"Loading Moondream from {model_path}", flush=True)
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="cuda:0",
trust_remote_code=True,
)
model.eval()
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
return model, tokenizer
def load_generic(model_path: str):
"""Generic loader: try AutoModelForCausalLM, fallback to AutoModelForVision2Seq, then AutoModel."""
import torch
from transformers import AutoModelForCausalLM, AutoModelForVision2Seq, AutoModel, AutoProcessor, AutoTokenizer
print(f"Loading generic model from {model_path}", flush=True)
try:
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
except Exception:
processor = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
load_kwargs = dict(torch_dtype=torch.bfloat16, device_map="cuda:0", trust_remote_code=True)
model = None
for cls in (AutoModelForCausalLM, AutoModelForVision2Seq, AutoModel):
try:
model = cls.from_pretrained(model_path, **load_kwargs)
print(f"Loaded with {cls.__name__}", flush=True)
break
except Exception as e:
print(f" {cls.__name__} failed: {e}", flush=True)
if model is None:
raise RuntimeError(f"Could not load model from {model_path} with any loader")
model.eval()
return model, processor
# ══════════════════════════════════════════════════════════════════════════════
# Inference functions
# ══════════════════════════════════════════════════════════════════════════════
def run_qwenvl_finetuned(model, processor, content_items: list) -> str:
"""Inference for fine-tuned Qwen3-VL / Qwen2.5-VL (uses training message format)."""
import torch
from qwen_vl_utils import process_vision_info
messages = [{"role": "user", "content": content_items}]
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
image_inputs, _ = process_vision_info(messages)
inputs = processor(
text=[text],
images=image_inputs,
return_tensors="pt",
).to("cuda:0")
with torch.no_grad():
output_ids = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
pad_token_id=processor.tokenizer.eos_token_id,
)
prompt_len = inputs["input_ids"].shape[1]
return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)
def run_qwenvl_base(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for base/instruct Qwen3-VL / Qwen2.5-VL (natural language prompt)."""
import torch
from qwen_vl_utils import process_vision_info
# Build content: system + interleaved images + text
content = []
content.append({"type": "text", "text": "Video 1 (consumption video):"})
for img in view_pil:
content.append({"type": "image", "image": img})
content.append({"type": "text", "text": "\nVideo 2 (publish video):"})
for img in pub_pil:
content.append({"type": "image", "image": img})
content.append({
"type": "text",
"text": (
f"\nCategory: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related (same meme/challenge/song/template)\n"
"label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
),
})
messages = [
{"role": "system", "content": BASE_SYSTEM_PROMPT},
{"role": "user", "content": content},
]
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
image_inputs, _ = process_vision_info(messages)
inputs = processor(
text=[text],
images=image_inputs,
return_tensors="pt",
).to("cuda:0")
with torch.no_grad():
output_ids = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
pad_token_id=processor.tokenizer.eos_token_id,
)
prompt_len = inputs["input_ids"].shape[1]
return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)
def run_internvl(model, tokenizer, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for InternVL models."""
import torch
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode
IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)
# Use 448 with downsample; each image → 1 tile → 256 tokens after pixel shuffle
def build_transform(input_size=448):
return T.Compose([
T.Lambda(lambda img: img.convert("RGB")),
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
T.ToTensor(),
T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
])
transform = build_transform(448)
all_images = view_pil + pub_pil
pixel_values = torch.stack([transform(img) for img in all_images]).to(torch.bfloat16).cuda()
n_view = len(view_pil)
n_pub = len(pub_pil)
# InternVL uses plain <image>\n tokens — one per image
view_img_tokens = "<image>\n" * n_view
pub_img_tokens = "<image>\n" * n_pub
question = (
f"Video 1 (consumption video) - {n_view} frames:\n{view_img_tokens}"
f"Video 2 (publish video) - {n_pub} frames:\n{pub_img_tokens}"
f"Category: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related, label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
)
# num_patches_list: one tile per image
num_patches_list = [1] * len(all_images)
generation_config = dict(max_new_tokens=MAX_NEW_TOKENS, do_sample=False)
response = model.chat(
tokenizer,
pixel_values,
question,
generation_config,
num_patches_list=num_patches_list,
history=None,
return_history=False,
)
return response
def run_llava(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for LLaVA-OneVision."""
import torch
# Build conversation with image tokens
n_view = len(view_pil)
n_pub = len(pub_pil)
view_img_str = "\n".join(["<image>"] * n_view)
pub_img_str = "\n".join(["<image>"] * n_pub)
text_prompt = (
f"Video 1 (consumption video):\n{view_img_str}\n\n"
f"Video 2 (publish video):\n{pub_img_str}\n\n"
f"Category: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related, label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
)
conversation = [
{"role": "system", "content": BASE_SYSTEM_PROMPT},
{"role": "user", "content": text_prompt},
]
all_images = view_pil + pub_pil
prompt = processor.apply_chat_template(
conversation, tokenize=False, add_generation_prompt=True
)
inputs = processor(
images=all_images,
text=prompt,
return_tensors="pt",
).to("cuda:0")
inputs = {k: v.to(torch.bfloat16) if v.dtype == torch.float32 else v
for k, v in inputs.items()}
with torch.no_grad():
output_ids = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
)
prompt_len = inputs["input_ids"].shape[1]
return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)
def run_llama32_vision(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for Llama-3.2-Vision."""
import torch
all_images = view_pil + pub_pil
n_view = len(view_pil)
n_pub = len(pub_pil)
view_img_str = "".join([f"<|image|>" for _ in view_pil])
pub_img_str = "".join([f"<|image|>" for _ in pub_pil])
messages = [
{"role": "user", "content": [
{"type": "text", "text": (
f"Video 1 (consumption video) - {n_view} frames:\n"
)},
*[{"type": "image"} for _ in view_pil],
{"type": "text", "text": (
f"\nVideo 2 (publish video) - {n_pub} frames:\n"
)},
*[{"type": "image"} for _ in pub_pil],
{"type": "text", "text": (
f"\nCategory: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related, label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
)},
]},
]
text = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(
images=all_images,
text=text,
return_tensors="pt",
).to("cuda:0")
with torch.no_grad():
output_ids = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
)
prompt_len = inputs["input_ids"].shape[1]
return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)
def run_phi3_vision(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for Phi-3.5-vision."""
import torch
# Phi-3.5 uses seen_tokens / get_usable_length on DynamicCache; patch if missing
try:
from transformers.cache_utils import DynamicCache
if not hasattr(DynamicCache, "seen_tokens"):
DynamicCache.seen_tokens = property(lambda self: self.get_seq_length())
if not hasattr(DynamicCache, "get_usable_length"):
def _get_usable_length(self, new_seq_length, layer_idx=0):
return self.get_seq_length(layer_idx)
DynamicCache.get_usable_length = _get_usable_length
except Exception:
pass
all_images = view_pil + pub_pil
n_view = len(view_pil)
n_pub = len(pub_pil)
view_img_tags = "".join([f"<|image_{i+1}|>\n" for i in range(n_view)])
pub_img_tags = "".join([f"<|image_{n_view+i+1}|>\n" for i in range(n_pub)])
messages = [
{"role": "user", "content": (
f"Video 1 (consumption video):\n{view_img_tags}"
f"Video 2 (publish video):\n{pub_img_tags}"
f"Category: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related, label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
)},
]
prompt = processor.tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
inputs = processor(prompt, all_images, return_tensors="pt").to("cuda:0")
with torch.no_grad():
output_ids = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
eos_token_id=processor.tokenizer.eos_token_id,
)
prompt_len = inputs["input_ids"].shape[1]
return processor.tokenizer.decode(output_ids[0, prompt_len:], skip_special_tokens=True)
def run_minicpm_v(model, tokenizer, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for MiniCPM-V."""
import torch
all_images = view_pil + pub_pil
question = (
f"Video 1 (consumption video) - {len(view_pil)} frames (shown above)\n"
f"Video 2 (publish video) - {len(pub_pil)} frames (shown above)\n\n"
f"Category: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related, label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
)
msgs = [{"role": "user", "content": all_images + [question]}]
res = model.chat(
image=None,
msgs=msgs,
tokenizer=tokenizer,
sampling=False,
max_new_tokens=MAX_NEW_TOKENS,
)
return res
def run_pixtral(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for Pixtral-12B."""
import torch
all_images = view_pil + pub_pil
n_view = len(view_pil)
n_pub = len(pub_pil)
content = []
content.append({"type": "text", "text": f"Video 1 (consumption video) - {n_view} frames:"})
for _ in view_pil:
content.append({"type": "image"})
content.append({"type": "text", "text": f"\nVideo 2 (publish video) - {n_pub} frames:"})
for _ in pub_pil:
content.append({"type": "image"})
content.append({"type": "text", "text": (
f"\nCategory: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related, label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
)})
messages = [{"role": "user", "content": content}]
text = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(
images=all_images,
text=text,
return_tensors="pt",
).to("cuda:0")
with torch.no_grad():
output_ids = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
)
prompt_len = inputs["input_ids"].shape[1]
return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)
def run_janus(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for Janus-Pro (DeepSeek multi-modal understanding)."""
import torch
all_images = view_pil + pub_pil
n_view, n_pub = len(view_pil), len(pub_pil)
# Janus uses image tokens in conversation format
img_tags_view = "<image_placeholder>" * n_view
img_tags_pub = "<image_placeholder>" * n_pub
conversation = [
{"role": "User", "content": (
f"Video 1 (consumption video) - {n_view} frames:\n{img_tags_view}\n"
f"Video 2 (publish video) - {n_pub} frames:\n{img_tags_pub}\n\n"
f"Category: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related, label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
)},
{"role": "Assistant", "content": ""},
]
prepare = processor(
conversations=conversation,
images=all_images,
force_batchify=True,
).to("cuda:0")
inputs_embeds = model.prepare_inputs_embeds(**prepare)
with torch.no_grad():
output_ids = model.language_model.generate(
inputs_embeds=inputs_embeds,
attention_mask=prepare.attention_mask,
pad_token_id=processor.tokenizer.eos_token_id,
bos_token_id=processor.tokenizer.bos_token_id,
eos_token_id=processor.tokenizer.eos_token_id,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
)
return processor.tokenizer.decode(output_ids[0].cpu(), skip_special_tokens=True)
def run_molmo(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for Molmo (AllenAI)."""
import torch
all_images = view_pil + pub_pil
prompt = (
f"Video 1 (consumption video) - {len(view_pil)} frames and "
f"Video 2 (publish video) - {len(pub_pil)} frames are shown above.\n"
f"Category: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related, label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
)
inputs = processor.process(
images=all_images,
text=prompt,
)
inputs = {k: v.to("cuda:0").unsqueeze(0) if hasattr(v, "to") else v
for k, v in inputs.items()}
from transformers import GenerationConfig
gen_cfg = getattr(model.config, "generation_config", None) or GenerationConfig(
max_new_tokens=MAX_NEW_TOKENS, do_sample=False,
)
with torch.no_grad():
output = model.generate_from_batch(
inputs,
generation_config=gen_cfg,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
)
generated = output[0, inputs["input_ids"].size(1):]
return processor.tokenizer.decode(generated, skip_special_tokens=True)
def run_moondream(model, tokenizer, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for Moondream2."""
# Moondream encodes each image independently, then does text generation
question = (
f"These are frames from two TikTok videos. "
f"Video 1 ({len(view_pil)} frames) then Video 2 ({len(pub_pil)} frames). "
f"Category: {class_name}. "
"Did Video 1 CAUSE or INSPIRE the creation of Video 2? "
"label=1: yes, label=0: no. "
'JSON only: {"reasoning": "...", "label": 0 or 1}'
)
all_images = view_pil + pub_pil
enc_images = [model.encode_image(img) for img in all_images]
# Use first encoded image as primary, append others in question context
answer = model.answer_question(
enc_images[0],
question,
tokenizer,
max_new_tokens=MAX_NEW_TOKENS,
)
return answer
def run_generic(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
"""Inference for generic AutoModel (best-effort)."""
import torch
# Patch config.num_hidden_layers if missing (e.g. ChatGLM uses num_layers)
cfg = getattr(model, "config", None)
if cfg is not None and not hasattr(cfg, "num_hidden_layers"):
for alt in ("num_layers", "n_layer", "n_layers"):
if hasattr(cfg, alt):
cfg.num_hidden_layers = getattr(cfg, alt)
break
all_images = view_pil + pub_pil
n_view = len(view_pil)
n_pub = len(pub_pil)
text_question = (
f"Category: {class_name}\n\n"
"Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
"label=1: causally related, label=0: not causally related\n\n"
'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
)
# Build messages using dict content (works for Idefics3 and most VLMs)
# String content with <image> tokens gets stripped by some chat templates.
user_content = (
[{"type": "text", "text": "Video 1 (consumption video):"}]
+ [{"type": "image"} for _ in view_pil]
+ [{"type": "text", "text": "\nVideo 2 (publish video):"}]
+ [{"type": "image"} for _ in pub_pil]
+ [{"type": "text", "text": f"\n{text_question}"}]
)
messages = [
{"role": "system", "content": BASE_SYSTEM_PROMPT},
{"role": "user", "content": user_content},
]
# Try dict-content template first; fall back to string-content template
prompt = None
if hasattr(processor, "apply_chat_template"):
try:
prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
# Verify image tokens are present
img_token = getattr(processor, "image_token", "<image>")
if img_token not in prompt and "<image" not in prompt:
raise ValueError("no image tokens in template output")
except Exception:
# Fall back: string content with <image> placeholders
view_img_str = "\n".join(["<image>"] * n_view)
pub_img_str = "\n".join(["<image>"] * n_pub)
messages_str = [
{"role": "system", "content": BASE_SYSTEM_PROMPT},
{"role": "user", "content": (
f"Video 1 (consumption video):\n{view_img_str}\n\n"
f"Video 2 (publish video):\n{pub_img_str}\n\n{text_question}"
)},
]
try:
prompt = processor.apply_chat_template(messages_str, tokenize=False, add_generation_prompt=True)
except Exception:
prompt = messages_str[-1]["content"]
if prompt is None:
view_img_str = "\n".join(["<image>"] * n_view)
pub_img_str = "\n".join(["<image>"] * n_pub)
prompt = (f"Video 1:\n{view_img_str}\nVideo 2:\n{pub_img_str}\n{text_question}")
try:
if hasattr(processor, "image_processor") or hasattr(processor, "feature_extractor"):
# Idefics3/SmolVLM requires images as List[List[PIL.Image]] (batch of samples)
proc_cls = type(processor).__name__
if "Idefics" in proc_cls or "SmolVLM" in proc_cls or hasattr(processor, "image_seq_len"):
images_arg = [all_images]
else:
images_arg = all_images
inputs = processor(
images=images_arg,
text=prompt,
return_tensors="pt",
).to("cuda:0")
else:
inputs = processor(prompt, return_tensors="pt").to("cuda:0")
except Exception:
inputs = processor(prompt, return_tensors="pt").to("cuda:0")
with torch.no_grad():
output_ids = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
)
if hasattr(processor, "decode"):
prompt_len = inputs["input_ids"].shape[1]
return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)
else:
return processor.batch_decode(output_ids, skip_special_tokens=True)[0]
# ══════════════════════════════════════════════════════════════════════════════
# Main
# ══════════════════════════════════════════════════════════════════════════════
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model-name", required=True,
help="Model name from models.py registry (e.g. qwen3vl_finetuned)")
parser.add_argument("--model-path", default=None,
help="Override model path (otherwise uses registry)")
parser.add_argument("--model-type", default=None,
help="Override model type: qwen3vl|qwen25vl|internvl|llava|generic")
parser.add_argument("--finetuned", action="store_true",
help="Use training-format prompt (for fine-tuned models)")
parser.add_argument("--frames-dir", default=str(FRAMES_DIR))
parser.add_argument("--output-dir", default=str(OUTPUT_DIR))
parser.add_argument("--gpu-id", type=int, default=0)
parser.add_argument("--frames-per-video", type=int, default=None,
help="Override FRAMES_PER_VIDEO (default: 8)")
args = parser.parse_args()
if args.frames_per_video is not None:
global FRAMES_PER_VIDEO
FRAMES_PER_VIDEO = args.frames_per_video
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id)
# Resolve model config from registry
sys.path.insert(0, str(Path(__file__).parent))
from models import MODELS_BY_NAME
registry = MODELS_BY_NAME.get(args.model_name, {})
model_path = args.model_path or registry.get("model_path", args.model_name)
model_type = args.model_type or registry.get("model_type", "generic")
# Fine-tuned flag: auto-detect if model name is qwen3vl_finetuned, else use --finetuned flag
is_finetuned = args.finetuned or (args.model_name == "qwen3vl_finetuned")
print(f"Model: {args.model_name}", flush=True)
print(f"Model path: {model_path}", flush=True)
print(f"Model type: {model_type}", flush=True)
print(f"Fine-tuned: {is_finetuned}", flush=True)
# Output
out_dir = Path(args.output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{args.model_name}.json"
# Load existing results (resume)
done_keys: set[str] = set()
results: list[dict] = []
if out_path.exists():
try:
saved = json.loads(out_path.read_text())
results = saved.get("results", [])
done_keys = {r["key"] for r in results if "key" in r}
print(f"Resuming: {len(done_keys)} already done", flush=True)
except Exception:
pass
# Load samples
frames_dir = Path(args.frames_dir)
samples = load_sample_files(frames_dir)
print(f"Loaded {len(samples)} samples from {frames_dir}", flush=True)
pending = [s for s in samples
if f"{s['view_gid']}_{s['pub_gid']}" not in done_keys]
print(f"Pending: {len(pending)}", flush=True)
if not pending:
print("Nothing to evaluate!", flush=True)
return
# Load model
loader_map = {
"qwen3vl": load_qwen3vl,
"qwen25vl": load_qwen25vl,
"internvl": load_internvl,
"llava": load_llava,
"llama32_vision": load_llama32_vision,
"phi3_vision": load_phi3_vision,
"minicpm_v": load_minicpm_v,
"pixtral": load_pixtral,
"janus": load_janus,
"molmo": load_molmo,
"moondream": load_moondream,
"cogvlm2": load_cogvlm2,
"generic": load_generic,
}
loader = loader_map.get(model_type, load_generic)
model, processor = loader(model_path)
# Inference loop
t0 = time.time()
for i, sample in enumerate(pending):
key = f"{sample['view_gid']}_{sample['pub_gid']}"
result = {
"key": key,
"view_gid": sample["view_gid"],
"pub_gid": sample["pub_gid"],
"class_name": sample.get("class_name", ""),
}
try:
if is_finetuned and model_type in ("qwen3vl", "qwen25vl"):
content_items, gt_label = parse_sample_for_finetuned(sample)
pred_text = run_qwenvl_finetuned(model, processor, content_items)
else:
view_pil, pub_pil, class_name, gt_label = parse_sample_for_base(sample)
if model_type in ("qwen3vl", "qwen25vl"):
pred_text = run_qwenvl_base(model, processor, view_pil, pub_pil, class_name)
elif model_type == "internvl":
pred_text = run_internvl(model, processor, view_pil, pub_pil, class_name)
elif model_type == "llava":
pred_text = run_llava(model, processor, view_pil, pub_pil, class_name)
elif model_type == "llama32_vision":
pred_text = run_llama32_vision(model, processor, view_pil, pub_pil, class_name)
elif model_type == "phi3_vision":
pred_text = run_phi3_vision(model, processor, view_pil, pub_pil, class_name)
elif model_type == "minicpm_v":
pred_text = run_minicpm_v(model, processor, view_pil, pub_pil, class_name)
elif model_type == "pixtral":
pred_text = run_pixtral(model, processor, view_pil, pub_pil, class_name)
elif model_type == "janus":
pred_text = run_janus(model, processor, view_pil, pub_pil, class_name)
elif model_type == "molmo":
pred_text = run_molmo(model, processor, view_pil, pub_pil, class_name)
elif model_type == "moondream":
pred_text = run_moondream(model, processor, view_pil, pub_pil, class_name)
elif model_type == "cogvlm2":
pred_text = run_cogvlm2(model, processor, view_pil, pub_pil, class_name)
else:
pred_text = run_generic(model, processor, view_pil, pub_pil, class_name)
pred_label = extract_label(pred_text)
result.update({
"gt_label": gt_label,
"pred_label": pred_label,
"match": (pred_label == gt_label) if (pred_label is not None and gt_label is not None) else None,
"prediction": pred_text,
})
except Exception as e:
result["error"] = str(e)
result["traceback"] = traceback.format_exc()[:500]
print(f" ERROR on {key}: {e}", flush=True)
results.append(result)
done_keys.add(key)
# Progress
elapsed = time.time() - t0
speed = (i + 1) / elapsed
total_done = len(done_keys)
stats = compute_stats(results)
print(
f"[{total_done}/{len(samples)}] {key} | "
f"acc={stats['accuracy']:.3f} "
f"(correct={stats['correct']}/{stats['evaluated']}) "
f"| {speed:.2f} samp/s",
flush=True,
)
# Save periodically
if (i + 1) % SAVE_INTERVAL == 0:
stats = compute_stats(results)
save_results(out_path, args.model_name, model_path, results, stats)
# Final save
stats = compute_stats(results)
save_results(out_path, args.model_name, model_path, results, stats)
elapsed = time.time() - t0
print(f"\n{'='*60}", flush=True)
print(f"DONE model={args.model_name}", flush=True)
print(f" accuracy: {stats['accuracy']:.4f} ({stats['correct']}/{stats['evaluated']})", flush=True)
print(f" per-class: {json.dumps(stats['per_class'], indent=4)}", flush=True)
print(f" parse_failures: {stats['parse_failures']}", flush=True)
print(f" time: {elapsed:.1f}s ({len(results)/elapsed:.2f} samp/s)", flush=True)
print(f" saved -> {out_path}", flush=True)
if __name__ == "__main__":
main()