Download ActionFollowing/run_eval.py from TANDREWYANG/optimism_train: direct link, hf CLI and curl.
- Browser
- Download file 5.45 kB
-
https://huggingface.co/datasets/TANDREWYANG/optimism_train/resolve/main/ActionFollowing/run_eval.py
- Command line
-
hf download hf://datasets/TANDREWYANG/optimism_train/ActionFollowing/run_eval.py
-
curl -L -o run_eval.py https://huggingface.co/datasets/TANDREWYANG/optimism_train/resolve/main/ActionFollowing/run_eval.py
5.45 kB
| #!/usr/bin/env python3 | |
| """ | |
| run_eval.py — Evaluate fine-tuned Qwen2.5-VL scorer on the 30-episode eval set. | |
| Usage: | |
| python run_eval.py | |
| python run_eval.py --model_path /path/to/Qwen2.5-VL-7B-Instruct | |
| python run_eval.py --ckpt checkpoints/sft --gpu 0 | |
| """ | |
| import argparse | |
| import json | |
| import statistics | |
| from pathlib import Path | |
| import torch | |
| from peft import PeftModel | |
| from scipy import stats | |
| from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration | |
| from qwen_vl_utils import process_vision_info | |
| import re | |
| ROOT = Path(__file__).parent | |
| CKPT_DIR = ROOT / "checkpoints/sft" | |
| EVAL_JSONL = ROOT / "eval_set/eval.jsonl" | |
| DEFAULT_MODEL = "/mnt/public/models/qwen_vl/Qwen2.5-VL-7B-Instruct" | |
| ALL_METRICS = ["TCR", "OPS", "CFS", "PP", "MQ", "TC", "VS", "OS"] | |
| MAX_FRAMES = 16 | |
| MAX_PIXELS = 360 * 640 | |
| def load_model(model_path, ckpt_path): | |
| processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) | |
| base = Qwen2_5_VLForConditionalGeneration.from_pretrained( | |
| model_path, torch_dtype=torch.bfloat16, | |
| attn_implementation="flash_attention_2", | |
| trust_remote_code=True, device_map="auto", | |
| ) | |
| model = PeftModel.from_pretrained(base, str(ckpt_path)) | |
| model.eval() | |
| return model, processor | |
| def run_inference(model, processor, sample): | |
| messages = [{ | |
| "role": "user", | |
| "content": [ | |
| {"type": "video", "video": sample["pred_video"], | |
| "max_pixels": MAX_PIXELS, "nframes": MAX_FRAMES}, | |
| {"type": "video", "video": sample["gt_video"], | |
| "max_pixels": MAX_PIXELS, "nframes": MAX_FRAMES}, | |
| {"type": "text", "text": sample["conversations"][0]["value"].replace("<video><video>\n", "")}, | |
| ], | |
| }] | |
| try: | |
| text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| _, video_inputs = process_vision_info(messages) | |
| inputs = processor(text=[text], videos=video_inputs or None, return_tensors="pt") | |
| inputs = {k: v.to(model.device) for k, v in inputs.items() if isinstance(v, torch.Tensor)} | |
| with torch.no_grad(): | |
| out = model.generate(**inputs, max_new_tokens=256, do_sample=False, | |
| temperature=None, top_p=None) | |
| raw = processor.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True) | |
| return parse_scores(raw) | |
| except Exception as e: | |
| print(f" inference error: {e}") | |
| return None | |
| def parse_scores(text): | |
| clean = re.sub(r"```(?:json)?", "", text).strip() | |
| m = re.search(r"\{[\s\S]*\}", clean) | |
| if not m: | |
| return None | |
| try: | |
| parsed = json.loads(m.group()) | |
| scores = {} | |
| for k in ALL_METRICS: | |
| v = parsed.get(k) | |
| if v is not None: | |
| val = float(v) | |
| if k in ("PP", "MQ", "TC", "VS", "OS"): | |
| val *= 100.0 | |
| scores[k] = val | |
| return scores if len(scores) == len(ALL_METRICS) else None | |
| except Exception: | |
| return None | |
| def get_gt(sample): | |
| try: | |
| parsed = json.loads(sample["conversations"][1]["value"]) | |
| return {k: float(parsed[k]) * (100 if k in ("PP","MQ","TC","VS","OS") else 1) | |
| for k in ALL_METRICS if k in parsed} | |
| except Exception: | |
| return {} | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--model_path", default=DEFAULT_MODEL) | |
| parser.add_argument("--ckpt", default=str(CKPT_DIR)) | |
| parser.add_argument("--gpu", default="0") | |
| args = parser.parse_args() | |
| import os; os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu | |
| print(f"Loading model from {args.model_path}") | |
| print(f"Loading adapter from {args.ckpt}") | |
| model, processor = load_model(args.model_path, args.ckpt) | |
| samples = [json.loads(l) for l in open(EVAL_JSONL)] | |
| print(f"Evaluating {len(samples)} episodes from eval_set/\n") | |
| records = [] | |
| for i, sample in enumerate(samples): | |
| gt = get_gt(sample) | |
| pred = run_inference(model, processor, sample) | |
| if pred and gt: | |
| records.append({"id": sample["id"], "gt": gt, "pred": pred}) | |
| print(f" [{i:2d}] {sample['id']} OS: gt={gt.get('OS',0):.0f} pred={pred.get('OS',0):.0f}") | |
| else: | |
| print(f" [{i:2d}] {sample['id']} FAILED") | |
| print(f"\n{'='*55}") | |
| print(f"Results — {len(records)}/{len(samples)} episodes") | |
| print(f"{'='*55}") | |
| print(f"{'Metric':6s} {'Pearson':>8s} {'Spearman':>9s} {'MAE':>7s}") | |
| print("-" * 38) | |
| out_metrics = {} | |
| for metric in ALL_METRICS: | |
| gt_v = [r["gt"].get(metric) for r in records if metric in r["gt"]] | |
| pred_v = [r["pred"].get(metric) for r in records if metric in r["pred"]] | |
| if len(gt_v) < 2: | |
| continue | |
| mae = statistics.mean(abs(g - p) for g, p in zip(gt_v, pred_v)) | |
| p = stats.pearsonr(gt_v, pred_v).statistic | |
| sp = stats.spearmanr(gt_v, pred_v).statistic | |
| print(f"{metric:6s} {p:+8.3f} {sp:+9.3f} {mae:7.2f}") | |
| out_metrics[metric] = {"pearson": round(p,4), "spearman": round(sp,4), "mae": round(mae,4)} | |
| out_path = Path(args.ckpt) / "eval_results.json" | |
| with open(out_path, "w") as f: | |
| json.dump({"metrics": out_metrics, "samples": records, "n_valid": len(records)}, f, indent=2) | |
| print(f"\nSaved to {out_path}") | |
| if __name__ == "__main__": | |
| main() | |