File size: 4,408 Bytes
d5049a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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()