| """ |
| Evaluate a Qwen3-VL checkpoint on the full training dataset. |
| |
| Design: |
| - One process per GPU; each GPU handles a shard of parquet files |
| - Supports resume: skips already-completed samples on restart |
| - Saves per-shard JSON incrementally every SAVE_INTERVAL samples |
| |
| Usage (single GPU, full data): |
| CUDA_VISIBLE_DEVICES=0 python -u eval.py --shard-id 0 --num-shards 1 |
| |
| Usage (8-GPU parallel via launcher): |
| bash run_parallel.sh |
| """ |
|
|
| import argparse |
| import base64 |
| import glob |
| import io |
| import json |
| import os |
| import time |
| from concurrent.futures import ThreadPoolExecutor |
| from pathlib import Path |
| from queue import Queue |
| from threading import Thread |
|
|
| import pyarrow.parquet as pq |
| from PIL import Image |
|
|
|
|
| |
|
|
| DEFAULT_MODEL = "/mnt/bn/bohanzhainas1/jiashuo/exp/new_policy7w_v2_reformat/checkpoint-1700/hf_model" |
| DEFAULT_DATA_DIR = "/mnt/hdfs/byte_tt_data_cu_vagcp/haogeng.liu/new_policy7w_v2_reformat" |
| DEFAULT_OUTPUT = "/mnt/bn/bohanzhainas1/jiashuo/exp/eval_ckpt1700_full" |
|
|
| FRAMES_PER_VIDEO = 4 |
| MAX_PIXELS = 336 * 336 |
| MAX_NEW_TOKENS = 96 |
| SAVE_INTERVAL = 50 |
|
|
|
|
| |
|
|
| def get_shard_files(data_dir: str, shard_id: int, num_shards: int) -> list[str]: |
| """Assign parquet files to this shard (round-robin by file index).""" |
| all_files = sorted(glob.glob(f"{data_dir}/*.parquet")) |
| if not all_files: |
| raise FileNotFoundError(f"No parquet files in {data_dir}") |
| return all_files[shard_id::num_shards] |
|
|
|
|
| def iter_file(parquet_path: str): |
| """Yield (file_idx, row_idx, messages, extra_info) for each row in a parquet file.""" |
| table = pq.read_table(parquet_path, columns=["messages", "extra_info"]) |
| for i in range(len(table)): |
| row = table.slice(i, 1).to_pydict() |
| yield json.loads(row["messages"][0]), json.loads(row["extra_info"][0]) |
|
|
|
|
| |
|
|
| def b64_to_pil(b64_str: str) -> Image.Image: |
| img = Image.open(io.BytesIO(base64.b64decode(b64_str))).convert("RGB") |
| |
| w, h = img.size |
| if w * h > MAX_PIXELS: |
| scale = (MAX_PIXELS / (w * h)) ** 0.5 |
| img = img.resize((int(w * scale), int(h * scale)), Image.BILINEAR) |
| return img |
|
|
|
|
| def parse_sample(msgs: list) -> tuple[list, str]: |
| """Returns (content_items for model input, ground_truth_text).""" |
| user_content = msgs[0]["content"] |
| ground_truth = msgs[1]["content"][0]["text"] |
|
|
| content_items = [] |
| for item in user_content: |
| if item["type"] == "video": |
| frames = item["video"] |
| step = max(1, len(frames) // FRAMES_PER_VIDEO) |
| for b64 in frames[::step][:FRAMES_PER_VIDEO]: |
| content_items.append({"type": "image", "image": b64_to_pil(b64)}) |
| elif item["type"] == "text": |
| content_items.append({"type": "text", "text": item["text"]}) |
| elif item["type"] == "image": |
| content_items.append({"type": "image", "image": b64_to_pil(item["image"])}) |
|
|
| return content_items, ground_truth |
|
|
|
|
| def extract_label(text: str) -> int | None: |
| import re |
| try: |
| stripped = text.strip() |
| if "```" in stripped: |
| m = re.search(r"```(?:json)?\s*([\s\S]+?)```", stripped) |
| if m: |
| stripped = m.group(1).strip() |
| return int(json.loads(stripped)["label"]) |
| except Exception: |
| m = re.search(r'"label"\s*:\s*([01])', text) |
| return int(m.group(1)) if m else None |
|
|
|
|
| |
|
|
| def load_model(model_path: str): |
| import torch |
| from transformers import Qwen3VLForConditionalGeneration, AutoProcessor |
|
|
| print(f"Loading model → cuda:0 ({model_path})", flush=True) |
| model = Qwen3VLForConditionalGeneration.from_pretrained( |
| model_path, |
| dtype=torch.bfloat16, |
| attn_implementation="flash_attention_2", |
| device_map="cuda:0", |
| trust_remote_code=True, |
| ) |
| model.eval() |
| processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) |
| print("Model loaded.", flush=True) |
| return model, processor |
|
|
|
|
| def run_inference(model, processor, content_items: list) -> str: |
| import torch |
| from qwen_vl_utils import process_vision_info |
|
|
| messages = [{"role": "user", "content": content_items}] |
| text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) |
| image_inputs, _ = process_vision_info(messages) |
|
|
| inputs = processor( |
| text=[text], |
| images=image_inputs, |
| return_tensors="pt", |
| ).to("cuda:0") |
|
|
| with torch.no_grad(): |
| output_ids = model.generate( |
| **inputs, |
| max_new_tokens=MAX_NEW_TOKENS, |
| do_sample=False, |
| pad_token_id=processor.tokenizer.eos_token_id, |
| ) |
|
|
| prompt_len = inputs["input_ids"].shape[1] |
| return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True) |
|
|
|
|
| |
|
|
| def compute_stats(results: list[dict]) -> dict: |
| from collections import defaultdict |
| label_stats = defaultdict(lambda: {"tp": 0, "fp": 0, "fn": 0, "tn": 0}) |
| correct = 0 |
| evaluated = 0 |
| parse_fail = 0 |
|
|
| for r in results: |
| if "error" in r: |
| continue |
| if r["pred_label"] is None: |
| parse_fail += 1 |
| continue |
| gt, pred = r["gt_label"], r["pred_label"] |
| if gt is None: |
| continue |
| evaluated += 1 |
| if gt == pred: |
| correct += 1 |
| for label in [0, 1]: |
| if gt == label and pred == label: |
| label_stats[label]["tp"] += 1 |
| elif gt != label and pred == label: |
| label_stats[label]["fp"] += 1 |
| elif gt == label and pred != label: |
| label_stats[label]["fn"] += 1 |
| else: |
| label_stats[label]["tn"] += 1 |
|
|
| per_class = {} |
| for label, s in label_stats.items(): |
| tp, fp, fn = s["tp"], s["fp"], s["fn"] |
| prec = tp / (tp + fp) if (tp + fp) > 0 else 0.0 |
| rec = tp / (tp + fn) if (tp + fn) > 0 else 0.0 |
| f1 = 2 * prec * rec / (prec + rec) if (prec + rec) > 0 else 0.0 |
| per_class[str(label)] = {"precision": prec, "recall": rec, "f1": f1, |
| "support": tp + fn} |
|
|
| return { |
| "accuracy": correct / evaluated if evaluated else 0.0, |
| "correct": correct, |
| "evaluated": evaluated, |
| "parse_failures": parse_fail, |
| "per_class": per_class, |
| } |
|
|
|
|
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--model-path", default=DEFAULT_MODEL) |
| parser.add_argument("--data-dir", default=DEFAULT_DATA_DIR) |
| parser.add_argument("--gpu-id", type=int, default=0) |
| parser.add_argument("--shard-id", type=int, default=0) |
| parser.add_argument("--num-shards", type=int, default=8) |
| parser.add_argument("--output", default=DEFAULT_OUTPUT) |
| args = parser.parse_args() |
|
|
| os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id) |
| gpu_tag = f"GPU{args.gpu_id}" |
|
|
| |
| out_path = Path(f"{args.output}_shard{args.shard_id:02d}.json") |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
|
|
| |
| done_keys: set[str] = set() |
| results: list[dict] = [] |
| if out_path.exists(): |
| try: |
| saved = json.loads(out_path.read_text()) |
| results = saved.get("results", []) |
| done_keys = {r["key"] for r in results if "key" in r} |
| print(f"[{gpu_tag}] Resuming: {len(done_keys)} already done", flush=True) |
| except Exception: |
| pass |
|
|
| |
| shard_files = get_shard_files(args.data_dir, args.shard_id, args.num_shards) |
| total_rows = len(shard_files) * 128 |
| print(f"[{gpu_tag}] Shard {args.shard_id}/{args.num_shards}: " |
| f"{len(shard_files)} files, ~{total_rows} samples", flush=True) |
|
|
| |
| model, processor = load_model(args.model_path) |
|
|
| |
| def sample_iter(): |
| for pf in shard_files: |
| fname = Path(pf).stem |
| for row_idx, (msgs, extra) in enumerate(iter_file(pf)): |
| key = f"{fname}:{row_idx}" |
| if key not in done_keys: |
| yield key, fname, row_idx, msgs |
|
|
| |
| |
| PREFETCH = 2 |
| prefetch_q: Queue = Queue(maxsize=PREFETCH) |
| _SENTINEL = object() |
|
|
| def prefetch_worker(): |
| for key, fname, row_idx, msgs in sample_iter(): |
| try: |
| content_items, ground_truth = parse_sample(msgs) |
| prefetch_q.put((key, fname, row_idx, content_items, ground_truth, None)) |
| except Exception as e: |
| prefetch_q.put((key, fname, row_idx, None, None, str(e))) |
| prefetch_q.put(_SENTINEL) |
|
|
| prefetch_thread = Thread(target=prefetch_worker, daemon=True) |
| prefetch_thread.start() |
|
|
| |
| t0 = time.time() |
| processed = 0 |
| last_save = time.time() |
|
|
| while True: |
| item = prefetch_q.get() |
| if item is _SENTINEL: |
| break |
|
|
| key, fname, row_idx, content_items, ground_truth, parse_err = item |
| result = {"key": key, "file": fname, "row": row_idx} |
|
|
| try: |
| if parse_err: |
| raise RuntimeError(parse_err) |
|
|
| gt_label = extract_label(ground_truth) |
| pred_text = run_inference(model, processor, content_items) |
| pred_label = extract_label(pred_text) |
|
|
| result.update({ |
| "gt_label": gt_label, |
| "pred_label": pred_label, |
| "match": (pred_label == gt_label) if (pred_label is not None and gt_label is not None) else None, |
| "prediction": pred_text, |
| "ground_truth": ground_truth, |
| }) |
| except Exception as e: |
| result["error"] = str(e) |
|
|
| results.append(result) |
| done_keys.add(key) |
| processed += 1 |
|
|
| |
| elapsed = time.time() - t0 |
| speed = processed / elapsed |
| stats = compute_stats(results) |
| eta_s = (total_rows - len(done_keys)) / speed if speed > 0 else 0 |
| eta_h = eta_s / 3600 |
| print( |
| f"[{gpu_tag}] [{len(done_keys)}/{total_rows}] " |
| f"acc={stats['accuracy']:.3f} " |
| f"p0={stats['per_class'].get('0',{}).get('precision',0):.2f}/" |
| f"r0={stats['per_class'].get('0',{}).get('recall',0):.2f} " |
| f"p1={stats['per_class'].get('1',{}).get('precision',0):.2f}/" |
| f"r1={stats['per_class'].get('1',{}).get('recall',0):.2f} " |
| f"| {speed:.3f} samp/s ETA {eta_h:.1f}h", |
| flush=True, |
| ) |
|
|
| |
| if time.time() - last_save > 60 or processed % SAVE_INTERVAL == 0: |
| _save(out_path, args, results, stats) |
| last_save = time.time() |
|
|
| prefetch_thread.join() |
|
|
| |
| stats = compute_stats(results) |
| _save(out_path, args, results, stats) |
|
|
| elapsed = time.time() - t0 |
| print(f"\n{'='*60}", flush=True) |
| print(f"[{gpu_tag}] DONE acc={stats['accuracy']:.4f} " |
| f"({stats['correct']}/{stats['evaluated']})", flush=True) |
| print(f"[{gpu_tag}] Per-class: {json.dumps(stats['per_class'], indent=2)}", flush=True) |
| print(f"[{gpu_tag}] Parse failures: {stats['parse_failures']}/{len(results)}", flush=True) |
| print(f"[{gpu_tag}] Time: {elapsed/3600:.2f}h ({len(results)/elapsed:.3f} samp/s)", flush=True) |
| print(f"[{gpu_tag}] Saved → {out_path}", flush=True) |
|
|
|
|
| def _save(path: Path, args, results: list, stats: dict): |
| path.write_text(json.dumps({ |
| "model_path": args.model_path, |
| "shard_id": args.shard_id, |
| "num_shards": args.num_shards, |
| "frames_per_video": FRAMES_PER_VIDEO, |
| "max_pixels": MAX_PIXELS, |
| "max_new_tokens": MAX_NEW_TOKENS, |
| **stats, |
| "results": results, |
| }, ensure_ascii=False, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|