File size: 8,774 Bytes
88dfad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()