import os
import json
import random
import warnings
import requests
import cv2
import numpy as np
import torch
import torch.multiprocessing as mp
from tqdm import trange
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
from PIL import Image
import re
warnings.filterwarnings("ignore")
# ================== 可根据需要修改的路径与配置 ==================
# MODEL_PATH = 'CodeGoat24/UnifiedReward-qwen-7b'
MODEL_PATH = "qunwang13/vr-thinker"
metadata = './VideoAlign/videogen_metadata.json'
model_rwft = 'Oct31_1'
steps = 2000
model_base = 'pretrain'
video_root_rwft = f'/nfs/ywang29/Reward_finetuning/VideoX-Fun/validation_samples/samples_videogen_eval/wan-videos-t2v-512*288-30-seed-1/output_{model_rwft}/steps_{steps}'
video_root_base = f'/nfs/ywang29/Reward_finetuning/VideoX-Fun/validation_samples/samples_videogen_eval1/wan-videos-t2v-512*288-30-seed42/output_{model_base}'
output_json_path = f'preference_eval/results1/{model_base}_{model_rwft}_unireward.json'
os.makedirs(os.path.dirname(output_json_path), exist_ok=True)
# ============================================================
def load_metadata(meta_path):
if meta_path.endswith('.json'):
with open(meta_path, 'r', encoding='utf-8') as f:
data = json.load(f) # 期望是 { "0001": {...}, "0002": {...} } 或 { "0001": "prompt", ...}
items = sorted(data.items(), key=lambda kv: int(kv[0]))
return items
elif meta_path.endswith('.txt'):
with open(meta_path, 'r', encoding='utf-8') as f:
lines = [line.strip() for line in f.readlines()]
# 若是 txt,就用行号当 prefix,整行当 prompt
return [(str(i), line) for i, line in enumerate(lines)]
else:
raise ValueError(f"Unsupported metadata file: {meta_path}")
def extract_prompt(value):
"""兼容两种格式:value 是字符串 / 或 dict 里含 'prompt' 字段。"""
if isinstance(value, str):
return value
if isinstance(value, dict):
# 优先常见字段名
for k in ['prompt', 'caption', 'text']:
if k in value:
return value[k]
# 兜底:把可序列化内容转成字符串
return json.dumps(value, ensure_ascii=False)
return str(value)
def get_results(model, processor, video_path_1, video_path_2, prompt):
prompt_for_videos = prompt
dim_name_1, dim_explain_1 = "Temporal Alignment (TA)", "How well the video adheres to the temporal aspects of the prompt."
dim_name_2, dim_explain_2 = "Video Quality (VQ)", "The visual and aesthetic quality of the video."
dim_name_3, dim_explain_3 = "Motion Quality (MQ)", "The smoothness and realism of the motion in the video."
N = 49
prompt_text = \
f"""Task Description: Your task is to compare two videos generated based on the same prompt by analyzing their frames in detail and provide an overall judgment along with a judgment for each dimension.
This involves:
- Iterative reasoning,
- Zooming in on details,
- Dynamically selecting frames for further analysis.
The provided frames are downsampled from these videos:
- Video 1: First four input frames.
- Video 2: Next four input frames.
The prompt is: {prompt_for_videos}
Evaluation Dimensions:
1. **{dim_name_1}**: {dim_explain_1}
2. **{dim_name_2}**: {dim_explain_2}
3. **{dim_name_3}**: {dim_explain_3}
Frames and Analysis Rules:
- 8 sampled frames are provided, evenly downsampled from {N} frames.
- First 4 input frames sampled from {N/2} actual frames of Video 1, next 4 input frames sampled from {N/2} actual frames of Video
- Insufficient frames? Request more using the tool.
Format Requirement:
1. Snapshot:
Every time you receive new visual information, summarize any information that might be useful for your final judgment within tags.
2. Think:\nPlace all reasoning content within tags.\n\n3. Answer:\nIf the final answer can be determined, output the answer within tags. If the answer is still uncertain, output the recommended answer and confidence level within tags.
- For TA, MQ, VQ, and OA: 1 represents Video 1 is better, 2 represents Video 2 is better, and 0 represents a Tie.
- For CF (Confidence level): 1 (low), 2 (medium), 3 (high), 4 (very high), 5 (confirmed).
Examples:\nTA=0, VQ=1, MQ=0, OA=1, CF=2
TA=1, VQ=1, MQ=0, OA=1."""
sys_prompt = \
"""You are a helpful assistant.\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:
\n{\"type\": \"function\", \"function\": {\"name\": \"select_frames\", \"description\": \"Select frames from a video.\", \"parameters\": {\"type\": \"object\", \"properties\":
{\"target_frames\": {\"type\": \"array\", \"description\": \"List of frame indices to select from the video (no more than 8 frames in total).\", \"items\": {\"type\": \"integer\", \"description\": \"Frame index from 1 to N.\"}}},
\"required\": [\"target_frames\"]}}}\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }"""
content_list = [{"type": "video", "video": video_path, "nframes": 4 } for video_path in [video_path_1, video_path_2]]
content_list.append({"type": "text", "text": prompt_text})
messages = [
{
"role": "system",
"content": sys_prompt,
},
{
"role": "user",
"content": content_list,
}
]
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
image_inputs, video_inputs, video_kwargs = process_vision_info(messages, return_video_kwargs=True)
inputs = processor(text=[text], images=image_inputs, videos=video_inputs,
return_tensors="pt", **video_kwargs).to(model.device)
with torch.inference_mode():
generated_ids = model.generate(**inputs, max_new_tokens=1024)
generated_ids_trimmed = [out[len(inp):] for inp, out in zip(inputs.input_ids, generated_ids)]
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True)[0]
import pdb
# pdb.set_trace()
m = re.search(r"\s*(.*?)\s*", output_text, flags=re.S)
block = m.group(1) if m else ""
# 提取形如 KEY=VALUE 的对,并转成 int
result = {k: int(v) for k, v in re.findall(r"\b([A-Z]{2})\s*=\s*([+-]?\d+)", block)}
# print(result)
return result
def worker(rank, world_size, items, output_json_path):
device = f'cuda:{rank}'
torch.cuda.set_device(device)
# 每个进程独立加载一份模型到自己的 GPU(避免跨卡拷贝)
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
MODEL_PATH, torch_dtype="auto", device_map={"": device}
)
processor = AutoProcessor.from_pretrained(MODEL_PATH)
A_win = 0
B_win = 0
tie = 0
results = []
# 每个进程处理 i % world_size == rank 的样本子集
local_indices = [i for i in range(len(items)) if i % world_size == rank]
# tqdm 在多进程里容易抢 stdout,这里给每个进程单独的条,或直接关闭
for idx in local_indices:
prefix, meta_val = items[idx]
prompt = extract_prompt(meta_val)
base_path = f'{video_root_base}/{prefix}.mp4'
rwft_path = f'{video_root_rwft}/{prefix}.mp4'
# 简单的存在性检查,缺文件就跳过,避免中断
if not (os.path.isfile(base_path) and os.path.isfile(rwft_path)):
# 你也可以把缺失样本记录下来
continue
try:
output = get_results(model, processor, rwft_path, base_path, prompt)
results.append(output)
except Exception as e:
# 个别样本异常时跳过,保证整体不崩
print(f"[Rank {rank}] Error on {prefix}: {e}")
continue
# 写入局部统计
part_path = f"{output_json_path}.part{rank}"
with open(part_path, 'w') as f:
json.dump(results, f, indent=2)
def aggregate(world_size, output_json_path):
all_results = []
for r in range(world_size):
part_path = f"{output_json_path}.part{r}"
if not os.path.isfile(part_path):
continue
with open(part_path, 'r') as f:
d = json.load(f)
all_results += d
with open(output_json_path, 'w') as f:
json.dump(all_results, f, indent=4)
# 清理所有分片文件
import glob
for p in glob.glob(f"{output_json_path}.part*"):
try:
os.remove(p)
except FileNotFoundError:
pass
def main():
# 读入任务列表
items = load_metadata(metadata)
# 自动检测 GPU 数量;也可用环境变量限制 GPU 可见性
world_size = torch.cuda.device_count()
if world_size <= 0:
raise RuntimeError("No CUDA device is available.")
print(f"Using {world_size} GPUs.")
# 先清理旧的 part
for r in range(world_size):
p = f"{output_json_path}.part{r}"
if os.path.isfile(p):
os.remove(p)
mp.set_start_method("spawn", force=True)
ctx = mp.get_context("spawn")
procs = []
for rank in range(world_size):
p = ctx.Process(target=worker, args=(rank, world_size, items, output_json_path), daemon=False)
p.start()
procs.append(p)
for p in procs:
p.join()
# 汇总
aggregate(world_size, output_json_path)
if __name__ == "__main__":
main()