run_eval.py 7.11 KB
Newer Older
1
#!/usr/bin/env python
Sylvain Gugger's avatar
Sylvain Gugger committed
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
15

16
import argparse
17
import datetime
18
import json
19
20
21
import time
import warnings
from logging import getLogger
22
from pathlib import Path
23
from typing import Dict, List
24
25
26
27
28

import torch
from tqdm import tqdm

from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
29
from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params
30
31


32
33
logger = getLogger(__name__)

34
35
36
37

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


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

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

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


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
def datetime_now():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def run_generate(verbose=True):
    """

    Takes input text, generates output, and then using reference calculates the BLEU scores.

    The results are saved to a file and returned to the caller, and printed out unless ``verbose=False`` is passed.

    Args:
        verbose (:obj:`bool`, `optional`, defaults to :obj:`True`): print results to stdout

    Returns:
        a tuple: ``(scores, params}``
        - ``scores``: a dict of scores data ``{'bleu': 39.6501, 'n_obs': 2000, 'runtime': 186, 'seconds_per_sample': 0.093}``
        - ``params``: a dict of custom params, e.g. ``{'num_beams': 5, 'length_penalty': 0.8}``
    """

102
103
    parser = argparse.ArgumentParser()
    parser.add_argument("model_name", type=str, help="like facebook/bart-large-cnn,t5-base, etc.")
104
105
    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")
106
107
    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")
108
    parser.add_argument("--device", type=str, required=False, default=DEFAULT_DEVICE, help="cuda, cuda:1, cpu etc.")
109
110
111
    parser.add_argument(
        "--prefix", type=str, required=False, default=None, help="will be added to the begininng of src examples"
    )
112
    parser.add_argument("--task", type=str, default="summarization", help="used for task_specific_params + metrics")
113
    parser.add_argument("--bs", type=int, default=8, required=False, help="batch size")
114
115
116
    parser.add_argument(
        "--n_obs", type=int, default=-1, required=False, help="How many observations. Defaults to all."
    )
117
    parser.add_argument("--fp16", action="store_true")
118
119
120
121
122
123
124
125
    parser.add_argument("--dump-args", action="store_true", help="print the custom hparams with the results")
    parser.add_argument(
        "--info",
        nargs="?",
        type=str,
        const=datetime_now(),
        help="use in conjunction w/ --dump-args to print with the results whatever other info you'd like, e.g. lang=en-ru. If no value is passed, the current datetime string will be used.",
    )
126
127
    # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate
    args, rest = parser.parse_known_args()
128
129
130
    parsed_args = parse_numeric_n_bool_cl_kwargs(rest)
    if parsed_args and verbose:
        print(f"parsed the following generate kwargs: {parsed_args}")
131
    examples = [" " + x.rstrip() if "t5" in args.model_name else x.rstrip() for x in open(args.input_path).readlines()]
132
133
    if args.n_obs > 0:
        examples = examples[: args.n_obs]
134
    Path(args.save_path).parent.mkdir(exist_ok=True)
135

136
137
    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.")
138
139
140
141
142

    if args.device == "cpu" and args.fp16:
        # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half'
        raise ValueError("Can't mix --fp16 and --device cpu")

143
    runtime_metrics = generate_summaries_or_translations(
144
145
146
147
148
149
150
        examples,
        args.save_path,
        args.model_name,
        batch_size=args.bs,
        device=args.device,
        fp16=args.fp16,
        task=args.task,
151
        prefix=args.prefix,
152
        **parsed_args,
153
    )
154

155
    if args.reference_path is None:
156
157
        return {}

158
    # Compute scores
159
    score_fn = calculate_bleu if "translation" in args.task else calculate_rouge
160
161
162
    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)
163
    scores.update(runtime_metrics)
164
165
166
167
168
169
170

    if args.dump_args:
        scores.update(parsed_args)
    if args.info:
        scores["info"] = args.info

    if verbose:
171
        print(scores)
172

173
    if args.score_path is not None:
174
        json.dump(scores, open(args.score_path, "w"))
175

176
    return scores
177
178
179


if __name__ == "__main__":
180
181
    # 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 $@
182
    run_generate(verbose=True)