File size: 1,687 Bytes
fcc2240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from BARTScore.bart_score import BARTScorer


def get_scorers():
    assert os.path.isfile(
        os.path.join("BARTScore", "bart.pth")
    ), "You must download `bart.pth` to use BARTScore.\nUse `gdown --id 1_7JfF7KOInb7ZrxKHIigTMR4ChVET01m --output bart.pth`"

    scorers = {}

    scorers["vanilla"] = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large")

    scorers["cnn"] = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large-cnn")

    # for the parabank model, first init a bart model, then load the local para model from BARTScore/bart.pth
    # see the documentation from https://github.com/neulab/BARTScore for reference
    scorers["para"] = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large-cnn")
    scorers["para"].load(path="BARTScore/bart.pth")

    return scorers


def compute_bart_score_for_scorer(predictions, references, scorer_name, scorer):
    precisions = scorer.score(predictions, references, batch_size=4)
    recalls = scorer.score(references, predictions, batch_size=4)
    f_scores = 0.5 * (precisions + recalls)

    return [
        {
            f"{scorer_name}_f_score": f_scores[i],
            f"{scorer_name}_precision": precisions[i],
            f"{scorer_name}_recall": recalls[i],
        }
        for i in len(range(predictions))
    ]


def compute_bart_score(predictions, references, scorers):
    result = [{} for _ in len(range(predictions))]
    for scorer_name, scorer in scorers.items():
        scorer_result = compute_bart_score_for_scorer(predictions, references, scorer_name, scorer)
        for i, element in enumerate(scorer_result):
            result[i].update(element)
    return result