Download VideoX-Fun/preference_eval/vrthinker_reward_eval.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 8.77 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/VideoX-Fun/preference_eval/vrthinker_reward_eval.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/VideoX-Fun/preference_eval/vrthinker_reward_eval.py
-
curl -L -o vrthinker_reward_eval.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/VideoX-Fun/preference_eval/vrthinker_reward_eval.py
8.77 kB
| import os | |
| import re | |
| 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 | |
| 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/results/{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 <snapshot></snapshot> tags. | |
| 2. Think:\nPlace all reasoning content within <think></think> tags.\n\n3. Answer:\nIf the final answer can be determined, output the answer within <final answer></final answer> tags. If the answer is still uncertain, output the recommended answer and confidence level within <recommend answer></recommend answer> 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:\n<recommend answer>TA=0, VQ=1, MQ=0, OA=1, CF=2</recommend answer> | |
| <final answer>TA=1, VQ=1, MQ=0, OA=1</final answer>.""" | |
| 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 <tools></tools> XML tags: | |
| <tools>\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</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}</tool_call>""" | |
| 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"<recommend answer>\s*(.*?)\s*</recommend answer>", s, 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 main(): | |
| device = f'cuda' | |
| items = load_metadata(metadata) | |
| # 每个进程独立加载一份模型到自己的 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 = [] | |
| # tqdm 在多进程里容易抢 stdout,这里给每个进程单独的条,或直接关闭 | |
| for idx in range(len(items)): | |
| 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, base_path, rwft_path, prompt) | |
| results.append(output) | |
| except Exception as e: | |
| # 个别样本异常时跳过,保证整体不崩 | |
| print(f"[Rank {rank}] Error on {prefix}: {e}") | |
| continue | |
| # if 'Video 1 is better' in output: | |
| # A_win += 1 | |
| # elif 'Video 2 is better' in output: | |
| # B_win += 1 | |
| # else: | |
| # tie += 1 | |
| # 写入局部统计 | |
| part_path = f"{output_json_path}.part{rank}" | |
| with open(part_path, 'w') as f: | |
| json.dump(results, f, indent=2) | |
| # with open(part_path, 'w') as f: | |
| # json.dump({"A_win": A_win, "B_win": B_win, "tie": tie, "count": len(local_indices)}, f, indent=2) | |
| # print(f"[Rank {rank}] Done. A_win={A_win}, tie={tie}, B_win={B_win}, count={len(local_indices)}") | |
| if __name__ == "__main__": | |
| main() | |