"INSTALL/grub/vscode:/vscode.git/clone" did not exist on "4707b76bb22e1ca60893bb6e9e79ac8331bf68b3"
run_eval.py 5.27 KB
Newer Older
1
2
import argparse
import json
3
4
5
import time
import warnings
from logging import getLogger
6
from pathlib import Path
7
from typing import Dict, List
8
9
10
11
12
13
14

import torch
from tqdm import tqdm

from transformers import AutoModelForSeq2SeqLM, AutoTokenizer


15
16
logger = getLogger(__name__)

17
try:
18
    from .utils import calculate_bleu, calculate_rouge, parse_numeric_cl_kwargs, use_task_specific_params
19
except ImportError:
20
    from utils import calculate_bleu, calculate_rouge, parse_numeric_cl_kwargs, use_task_specific_params
21
22
23
24
25
26
27
28
29
30

DEFAULT_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"


def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i : i + n]


31
def generate_summaries_or_translations(
32
    examples: List[str],
33
34
35
36
37
    out_file: str,
    model_name: str,
    batch_size: int = 8,
    device: str = DEFAULT_DEVICE,
    fp16=False,
38
    task="summarization",
39
    prefix=None,
40
41
42
    **generate_kwargs,
) -> Dict:
    """Save model.generate results to <out_file>, and return how long it took."""
43
    fout = Path(out_file).open("w", encoding="utf-8")
44
    model_name = str(model_name)
45
46
47
48
49
    model = AutoModelForSeq2SeqLM.from_pretrained(model_name).to(device)
    if fp16:
        model = model.half()

    tokenizer = AutoTokenizer.from_pretrained(model_name)
50
    logger.info(f"Inferred tokenizer type: {tokenizer.__class__}")  # if this is wrong, check config.model_type.
51

52
53
    start_time = time.time()
    # update config with task specific params
54
    use_task_specific_params(model, task)
55
56
    if prefix is None:
        prefix = prefix or getattr(model.config, "prefix", "") or ""
57
    for examples_chunk in tqdm(list(chunks(examples, batch_size))):
58
        examples_chunk = [prefix + text for text in examples_chunk]
59
        batch = tokenizer(examples_chunk, return_tensors="pt", truncation=True, padding="longest").to(device)
60
        summaries = model.generate(
61
62
63
            input_ids=batch.input_ids,
            attention_mask=batch.attention_mask,
            **generate_kwargs,
64
        )
65
66
67
68
        dec = tokenizer.batch_decode(summaries, skip_special_tokens=True, clean_up_tokenization_spaces=False)
        for hypothesis in dec:
            fout.write(hypothesis + "\n")
            fout.flush()
69
    fout.close()
70
    runtime = int(time.time() - start_time)  # seconds
71
72
    n_obs = len(examples)
    return dict(n_obs=n_obs, runtime=runtime, seconds_per_sample=round(runtime / n_obs, 4))
73
74
75
76
77


def run_generate():
    parser = argparse.ArgumentParser()
    parser.add_argument("model_name", type=str, help="like facebook/bart-large-cnn,t5-base, etc.")
78
79
    parser.add_argument("input_path", type=str, help="like cnn_dm/test.source")
    parser.add_argument("save_path", type=str, help="where to save summaries")
80
81
    parser.add_argument("--reference_path", type=str, required=False, help="like cnn_dm/test.target")
    parser.add_argument("--score_path", type=str, required=False, default="metrics.json", help="where to save metrics")
82
    parser.add_argument("--device", type=str, required=False, default=DEFAULT_DEVICE, help="cuda, cuda:1, cpu etc.")
83
84
85
    parser.add_argument(
        "--prefix", type=str, required=False, default=None, help="will be added to the begininng of src examples"
    )
86
    parser.add_argument("--task", type=str, default="summarization", help="used for task_specific_params + metrics")
87
    parser.add_argument("--bs", type=int, default=8, required=False, help="batch size")
88
89
90
    parser.add_argument(
        "--n_obs", type=int, default=-1, required=False, help="How many observations. Defaults to all."
    )
91
    parser.add_argument("--fp16", action="store_true")
92
93
94
95
96
    # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate
    args, rest = parser.parse_known_args()
    parsed = parse_numeric_cl_kwargs(rest)
    if parsed:
        print(f"parsed the following generate kwargs: {parsed}")
97
    examples = [" " + x.rstrip() if "t5" in args.model_name else x.rstrip() for x in open(args.input_path).readlines()]
98
99
    if args.n_obs > 0:
        examples = examples[: args.n_obs]
100
    Path(args.save_path).parent.mkdir(exist_ok=True)
101
102
103
    if args.reference_path is None and Path(args.score_path).exists():
        warnings.warn(f"score_path {args.score_path} will be overwritten unless you type ctrl-c.")
    runtime_metrics = generate_summaries_or_translations(
104
105
106
107
108
109
110
        examples,
        args.save_path,
        args.model_name,
        batch_size=args.bs,
        device=args.device,
        fp16=args.fp16,
        task=args.task,
111
        prefix=args.prefix,
112
        **parsed,
113
    )
114
115
116
    if args.reference_path is None:
        return
    # Compute scores
117
    score_fn = calculate_bleu if "translation" in args.task else calculate_rouge
118
119
120
    output_lns = [x.rstrip() for x in open(args.save_path).readlines()]
    reference_lns = [x.rstrip() for x in open(args.reference_path).readlines()][: len(output_lns)]
    scores: dict = score_fn(output_lns, reference_lns)
121
    scores.update(runtime_metrics)
122
    print(scores)
123
    if args.score_path is not None:
124
        json.dump(scores, open(args.score_path, "w"))
125
    return scores
126
127
128


if __name__ == "__main__":
129
130
    # Usage for MT:
    # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json  --task translation $@
131
    run_generate()