|
| 1 | +import os |
| 2 | +import re |
| 3 | +import sys |
| 4 | +import json |
| 5 | +import random |
| 6 | +import argparse |
| 7 | +from tqdm import tqdm |
| 8 | +from vllm import LLM, SamplingParams |
| 9 | +from transformers import AutoTokenizer |
| 10 | +from videomathqa.utils import (extract_characters_regex, |
| 11 | + videomathqa_process_results, |
| 12 | + videomathqa_mcq_aggregate_results, |
| 13 | + videomathqa_multi_binary_aggregate_results) |
| 14 | + |
| 15 | + |
| 16 | +mcq_prompt = ( |
| 17 | + "Given the original multiple-choice options and a model-generated answer containing reasoning and a final answer, identify the option that best matches the final answer and return only the corresponding letter (A, B, C, D, or E)." |
| 18 | +) |
| 19 | +mbin_prommpt = "Given the original binary options and a model-generated answer containing reasoning and a final answer, identify the option that best matches the final answer and return only the corresponding letter (A or B)." |
| 20 | + |
| 21 | + |
| 22 | +def extract_choice_vllm(llm, sampling_params, tokenizer, model_prompt, mcq=True): |
| 23 | + if mcq: |
| 24 | + prompt_type = mcq_prompt |
| 25 | + else: |
| 26 | + prompt_type = mbin_prommpt |
| 27 | + chat_prompt = [ |
| 28 | + { |
| 29 | + "role": "user", |
| 30 | + "content": f"""{prompt_type}: |
| 31 | +
|
| 32 | +Text: |
| 33 | +{model_prompt} |
| 34 | +
|
| 35 | +Only return the letter A, B, C, D, or E. If none is found, return "None".""", |
| 36 | + } |
| 37 | + ] |
| 38 | + text = tokenizer.apply_chat_template(chat_prompt, tokenize=False, add_generation_prompt=True, enable_thinking=False) |
| 39 | + output = llm.generate([text], sampling_params=sampling_params) |
| 40 | + reply = output[0].outputs[0].text.strip().upper() |
| 41 | + if mcq: |
| 42 | + if re.fullmatch(r"[A-E]", reply): |
| 43 | + return reply |
| 44 | + else: |
| 45 | + if re.fullmatch(r"[A-B]", reply): |
| 46 | + return reply |
| 47 | + return None |
| 48 | + |
| 49 | + |
| 50 | +def refine_samples_vllm(llm, sampling_params, tokenizer, sample_jsonl, output_jsonl, mcq=True): |
| 51 | + raw_samples = [] |
| 52 | + with open(sample_jsonl, "r") as f: |
| 53 | + for line in f: |
| 54 | + raw_samples.append(json.loads(line)) |
| 55 | + print(f"Loaded {len(raw_samples)} samples from {sample_jsonl}") |
| 56 | + |
| 57 | + updated_samples = [] |
| 58 | + for sample in tqdm(raw_samples, desc="Postprocessing samples with Qwen"): |
| 59 | + options = sample["doc"]["options"] |
| 60 | + raw_pred = sample["resps"][0][0] |
| 61 | + input_text = f"The options are: {options}\n\n The model response is: {raw_pred}" |
| 62 | + try: |
| 63 | + choice = extract_choice_vllm(llm, sampling_params, tokenizer, input_text, mcq) |
| 64 | + except Exception as e: |
| 65 | + choice = None |
| 66 | + if choice is None: |
| 67 | + answer = sample["target"] |
| 68 | + if mcq: |
| 69 | + options = ["A", "B", "C", "D", "E"] |
| 70 | + else: |
| 71 | + options = ["A", "B"] |
| 72 | + options.remove(answer) |
| 73 | + random.shuffle(options) |
| 74 | + choice = options[0] |
| 75 | + sample["resps"][0][0] = choice |
| 76 | + updated_samples.append(sample) |
| 77 | + |
| 78 | + with open(output_jsonl, "w") as f: |
| 79 | + for sample in updated_samples: |
| 80 | + f.write(json.dumps(sample) + "\n") |
| 81 | + print(f"Saved {len(updated_samples)} updated samples to {output_jsonl}") |
| 82 | + return updated_samples |
| 83 | + |
| 84 | + |
| 85 | +def postprocess_jsonl(llm, sampling_params, tokenizer, sample_jsonl, output_jsonl): |
| 86 | + if "mcq" in sample_jsonl: |
| 87 | + mcq = True |
| 88 | + elif "mbin" in sample_jsonl: |
| 89 | + mcq = False |
| 90 | + |
| 91 | + updated_samples = refine_samples_vllm(llm, sampling_params, tokenizer, sample_jsonl, output_jsonl, mcq) |
| 92 | + |
| 93 | + print(f"Computing score ...") |
| 94 | + processed = [] |
| 95 | + for item in tqdm(updated_samples, desc="Computing scores..."): |
| 96 | + pred_raw = item["resps"][0][0] if isinstance(item["resps"][0], list) else item["resps"][0] |
| 97 | + pred_clean = extract_characters_regex(pred_raw) |
| 98 | + item["filtered_resps"] = [pred_clean] |
| 99 | + result = videomathqa_process_results(item["doc"], [pred_clean]) |
| 100 | + processed.append(result["videomathqa_perception_score"]) |
| 101 | + |
| 102 | + if mcq: |
| 103 | + final_score = videomathqa_mcq_aggregate_results(processed) |
| 104 | + else: |
| 105 | + final_score = videomathqa_multi_binary_aggregate_results(processed) |
| 106 | + print(f"Final Postprocessed VideoMathQA Score: {final_score:.2f}") |
| 107 | + print(f"Saved {len(updated_samples)} updated samples to {output_jsonl}") |
| 108 | + |
| 109 | + |
| 110 | +def main(): |
| 111 | + parser = argparse.ArgumentParser(description="Postprocess a CoT predictions using the Qwen model.") |
| 112 | + parser.add_argument("--input_file", type=str, required=True, help="Path to the input JSONL file.") |
| 113 | + parser.add_argument("--output_file", type=str, required=True, help="Path to save the postprocessed output JSONL file.") |
| 114 | + parser.add_argument("--model_path", type=str, default="Qwen/Qwen3-4B", help="Path to the pretrained Qwen model (default: Qwen3-4B).") |
| 115 | + |
| 116 | + args = parser.parse_args() |
| 117 | + |
| 118 | + if not os.path.exists(args.input_file): |
| 119 | + print(f"Input file '{args.input_file}' does not exist.") |
| 120 | + return |
| 121 | + |
| 122 | + if os.path.exists(args.output_file): |
| 123 | + print(f"Output file '{args.output_file}' already exists. Skipping.") |
| 124 | + return |
| 125 | + |
| 126 | + print("Loading Qwen-3 model...") |
| 127 | + tokenizer = AutoTokenizer.from_pretrained(args.model_path) |
| 128 | + llm = LLM(model=args.model_path) |
| 129 | + sampling_params = SamplingParams(temperature=0.7, top_p=0.8, top_k=20, min_p=0, max_tokens=16) |
| 130 | + |
| 131 | + print(f"Processing {args.input_file} ...") |
| 132 | + postprocess_jsonl(llm, sampling_params, tokenizer, args.input_file, args.output_file) |
| 133 | + print(f"Saved postprocessed output to {args.output_file}") |
| 134 | + |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + main() |
0 commit comments