"vscode:/vscode.git/clone" did not exist on "5340d1f21f76074ead6953a92056ec48173d8473"
evaluate_cnn.py 2.48 KB
Newer Older
1
2
3
4
5
6
import argparse
from pathlib import Path

import torch
from tqdm import tqdm

7
from transformers import BartForConditionalGeneration, BartTokenizer
8
9
10
11
12
13
14
15
16
17
18


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]


19
20
21
def generate_summaries(
    examples: list, out_file: str, model_name: str, batch_size: int = 8, device: str = DEFAULT_DEVICE
):
22
    fout = Path(out_file).open("w")
23
    model = BartForConditionalGeneration.from_pretrained(model_name).to(device)
24
    tokenizer = BartTokenizer.from_pretrained("bart-large")
25
26
27
28

    max_length = 140
    min_length = 55

29
    for batch in tqdm(list(chunks(examples, batch_size))):
30
31
32
33
34
35
        dct = tokenizer.batch_encode_plus(batch, max_length=1024, return_tensors="pt", pad_to_max_length=True)
        summaries = model.generate(
            input_ids=dct["input_ids"].to(device),
            attention_mask=dct["attention_mask"].to(device),
            num_beams=4,
            length_penalty=2.0,
36
37
            max_length=max_length + 2,  # +2 from original because we start at step=1 and stop before max_length
            min_length=min_length + 1,  # +1 from original because we start at step=1
38
            no_repeat_ngram_size=3,
39
            early_stopping=True,
40
            decoder_start_token_id=model.config.eos_token_id,
41
42
43
44
45
46
47
        )
        dec = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in summaries]
        for hypothesis in dec:
            fout.write(hypothesis + "\n")
            fout.flush()


48
def run_generate():
49
50
51
52
53
54
55
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "source_path", type=str, help="like cnn_dm/test.source",
    )
    parser.add_argument(
        "output_path", type=str, help="where to save summaries",
    )
56
57
58
    parser.add_argument(
        "model_name", type=str, default="bart-large-cnn", help="like bart-large-cnn",
    )
59
60
61
62
63
64
65
    parser.add_argument(
        "--device", type=str, required=False, default=DEFAULT_DEVICE, help="cuda, cuda:1, cpu etc.",
    )
    parser.add_argument(
        "--bs", type=int, default=8, required=False, help="batch size: how many to summarize at a time",
    )
    args = parser.parse_args()
66
67
    examples = [" " + x.rstrip() for x in open(args.source_path).readlines()]
    generate_summaries(examples, args.output_path, args.model_name, batch_size=args.bs, device=args.device)
68
69
70


if __name__ == "__main__":
71
    run_generate()