import sys, os, json, torch, time from multiprocessing import Process from PIL import Image EVAL_DIR = "/workspace/rl4phyx/RL4Phyx/SFT/sft_eval_footprint" TEST_FILE = os.path.join(EVAL_DIR, "test_1533_openended.jsonl") MODEL_PATH = sys.argv[1] OUTPUT_NAME = sys.argv[2] NUM_GPUS = 8 def build_open_ended_prompt(sample): parts = [] desc = sample.get("description", "") q = sample.get("question", "") if desc: parts.append(desc) if q: parts.append(q) parts.append("Please reason step by step, and put your final answer within \\boxed{}.") return "\n\n".join(parts) def worker_inference(gpu_id, model_path, samples, out_file, model_name): os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id) from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor from qwen_vl_utils import process_vision_info model = Qwen2_5_VLForConditionalGeneration.from_pretrained( model_path, torch_dtype=torch.bfloat16, device_map="cuda", attn_implementation="sdpa" ) processor = AutoProcessor.from_pretrained(model_path) model.eval() results = [] for idx, sample in enumerate(samples): try: prompt_text = build_open_ended_prompt(sample) img = sample.get("image_path", "") content = [] if img and os.path.exists(img): content.append({"type": "image", "image": f"file://{img}"}) content.append({"type": "text", "text": prompt_text}) messages = [{"role": "user", "content": content}] text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) image_inputs, video_inputs = process_vision_info(messages) inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt").to("cuda") with torch.no_grad(): ids = model.generate(**inputs, max_new_tokens=2048, do_sample=False) out_ids = ids[0][len(inputs.input_ids[0]):] response = processor.decode(out_ids, skip_special_tokens=True) sample["model_output"] = response except Exception as e: sample["model_output"] = f"Error: {str(e)}" results.append(sample) if (idx + 1) % 50 == 0: print(f" [GPU {gpu_id}] {idx+1}/{len(samples)}", flush=True) with open(out_file, "w", encoding="utf-8") as f: for r in results: f.write(json.dumps(r, ensure_ascii=False) + "\n") print(f" [GPU {gpu_id}] Done: {len(results)} -> {out_file}", flush=True) def main(): print(f"\nModel: {MODEL_PATH}") print(f"Output: {OUTPUT_NAME}") samples = [] with open(TEST_FILE) as f: for line in f: if line.strip(): samples.append(json.loads(line)) print(f"Test samples: {len(samples)}") output_file = os.path.join(EVAL_DIR, f"inference_results_{OUTPUT_NAME}.jsonl") chunk_size = len(samples) // NUM_GPUS procs = [] for gpu in range(NUM_GPUS): s = gpu * chunk_size e = s + chunk_size if gpu < NUM_GPUS - 1 else len(samples) gpu_file = os.path.join(EVAL_DIR, f"_temp_{OUTPUT_NAME}_gpu{gpu}.jsonl") p = Process(target=worker_inference, args=(gpu, MODEL_PATH, samples[s:e], gpu_file, OUTPUT_NAME)) p.start() procs.append((p, gpu_file)) for p, _ in procs: p.join() all_results = [] for _, gf in procs: if os.path.exists(gf): with open(gf) as f: for line in f: if line.strip(): all_results.append(line) os.remove(gf) with open(output_file, "w") as f: for line in all_results: f.write(line) print(f"Total: {len(all_results)} results -> {output_file}") if __name__ == "__main__": main()