Download src/evaluate.py from huohuo0345/0716: direct link, hf CLI and curl.
- Browser
- Download file 4.41 kB
-
https://huggingface.co/datasets/huohuo0345/0716/resolve/main/src/evaluate.py
- Command line
-
hf download hf://datasets/huohuo0345/0716/src/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/huohuo0345/0716/resolve/main/src/evaluate.py
4.41 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| from collections import Counter | |
| import torch | |
| from peft import PeftModel | |
| from .common import ( | |
| apply_chat_template, | |
| build_messages, | |
| load_rows, | |
| move_to_device, | |
| normalized_row, | |
| ) | |
| from .modeling import load_base_model, load_processor | |
| def normalize(text: str) -> list[str]: | |
| return re.findall(r"[a-z0-9]+", text.lower()) | |
| def token_f1(prediction: str, reference: str) -> float: | |
| pred = normalize(prediction) | |
| ref = normalize(reference) | |
| if not pred or not ref: | |
| return float(pred == ref) | |
| overlap = sum((Counter(pred) & Counter(ref)).values()) | |
| if overlap == 0: | |
| return 0.0 | |
| precision = overlap / len(pred) | |
| recall = overlap / len(ref) | |
| return 2 * precision * recall / (precision + recall) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="Generate DriveLM validation predictions") | |
| parser.add_argument("--model", required=True) | |
| parser.add_argument("--adapter-path", default=None) | |
| parser.add_argument("--data-dir", required=True) | |
| parser.add_argument("--output", required=True) | |
| parser.add_argument("--split", default="val") | |
| parser.add_argument("--num-views", type=int, default=1) | |
| parser.add_argument("--max-length", type=int, default=4096) | |
| parser.add_argument("--max-new-tokens", type=int, default=128) | |
| parser.add_argument("--max-samples", type=int, default=None) | |
| parser.add_argument("--attn-implementation", default="sdpa") | |
| args = parser.parse_args() | |
| processor = load_processor(args.model) | |
| model = load_base_model( | |
| args.model, attn_implementation=args.attn_implementation | |
| ) | |
| if args.adapter_path: | |
| model = PeftModel.from_pretrained(model, args.adapter_path, is_trainable=False) | |
| model = model.cuda().eval() | |
| rows = load_rows(args.data_dir, args.split) | |
| if args.max_samples: | |
| rows = rows[: args.max_samples] | |
| os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True) | |
| exact_sum = 0.0 | |
| f1_sum = 0.0 | |
| with open(args.output, "w", encoding="utf-8") as handle: | |
| for index, raw in enumerate(rows): | |
| row = normalized_row(raw) | |
| prompt = apply_chat_template( | |
| processor, | |
| build_messages(row["question"], row["image_paths"], args.num_views), | |
| add_generation_prompt=True, | |
| max_length=args.max_length, | |
| ) | |
| prompt = move_to_device(prompt, torch.device("cuda")) | |
| prompt_len = int(prompt["input_ids"].shape[1]) | |
| generation_tokens = min( | |
| args.max_new_tokens, args.max_length - prompt_len | |
| ) | |
| if generation_tokens < 1: | |
| raise RuntimeError( | |
| f"Sample {index} prompt reaches max_length={args.max_length}" | |
| ) | |
| with torch.inference_mode(): | |
| sequences = model.generate( | |
| **prompt, | |
| max_new_tokens=generation_tokens, | |
| do_sample=False, | |
| use_cache=True, | |
| ) | |
| prediction = processor.tokenizer.decode( | |
| sequences[0, prompt_len:], skip_special_tokens=True | |
| ).strip() | |
| exact = float(normalize(prediction) == normalize(row["answer"])) | |
| f1 = token_f1(prediction, row["answer"]) | |
| exact_sum += exact | |
| f1_sum += f1 | |
| record = { | |
| **{key: row[key] for key in ("scene_id", "frame_token", "task_type")}, | |
| "question": row["question"], | |
| "reference": row["answer"], | |
| "prediction": prediction, | |
| "exact_match": exact, | |
| "token_f1": f1, | |
| } | |
| handle.write(json.dumps(record, ensure_ascii=False) + "\n") | |
| if (index + 1) % 20 == 0: | |
| print(f"evaluated={index + 1}/{len(rows)}", flush=True) | |
| count = len(rows) | |
| metrics = { | |
| "samples": count, | |
| "exact_match": exact_sum / count if count else 0.0, | |
| "token_f1": f1_sum / count if count else 0.0, | |
| } | |
| with open(args.output + ".metrics.json", "w", encoding="utf-8") as handle: | |
| json.dump(metrics, handle, ensure_ascii=False, indent=2) | |
| print(json.dumps(metrics, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |