eladsegal commited on
Commit
fd669ce
1 Parent(s): 7f1631c

Update metrics/bart_score.py

Browse files
Files changed (1) hide show
  1. metrics/bart_score.py +31 -122
metrics/bart_score.py CHANGED
@@ -1,137 +1,46 @@
1
  import os
2
  import numpy as np
3
  from BARTScore.bart_score import BARTScorer
4
- from src.metrics import Metric
5
- import logging
6
- from tqdm import tqdm
7
 
8
- logger = logging.getLogger(__name__)
9
 
 
 
 
 
10
 
11
- class BartScore(Metric):
12
- """
13
- The BARTScore metric, based on the example from https://github.com/neulab/BARTScore
14
- """
15
 
16
- def __init__(self, **kwargs) -> None:
17
- super().__init__(**kwargs)
18
 
19
- assert os.path.isfile(
20
- os.path.join("BARTScore", "bart.pth")
21
- ), "You must download `bart.pth` to use BARTScore.\nUse `gdown --id 1_7JfF7KOInb7ZrxKHIigTMR4ChVET01m --output bart.pth`"
22
 
23
- # we use 3 bart scorers: the vanilla, cnn, and para variants
24
- self.bart_scorers_initializers = {
25
- "vanilla": self.get_vanilla_scorer,
26
- "cnn": self.get_cnn_scorer,
27
- "para": self.get_para_scorer,
28
- }
29
- self.requires_decoded = True
30
-
31
- @staticmethod
32
- def get_vanilla_scorer():
33
- """
34
- returns the the vanilla bart scorer
35
- """
36
- bart_scorer = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large")
37
- return bart_scorer
38
-
39
- @staticmethod
40
- def get_cnn_scorer():
41
- """
42
- returns the the cnn version of bart sore
43
- """
44
- bart_scorer = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large-cnn")
45
- return bart_scorer
46
-
47
- @staticmethod
48
- def get_para_scorer():
49
- """
50
- returns the parabank version of bart score
51
- """
52
- # for the parabank model, first init a bart model, then load the local para model from BARTScore/bart.pth
53
- # See the documentation from https://github.com/neulab/BARTScore for reference
54
- bart_scorer = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large-cnn")
55
- bart_scorer.load(path="BARTScore/bart.pth")
56
- return bart_scorer
57
-
58
- def calc_bart_score(self, scorer, prediction, gold_labels):
59
- """
60
- calculate the bart score for a prediction given the gold labels for a specific scorer
61
- """
62
-
63
- # num_gold_labels
64
- num_gold_labels = len(gold_labels)
65
-
66
- # ref to hypo scores are the precision
67
- ref_hypo_scores = np.array(scorer.score(gold_labels, [prediction] * num_gold_labels, batch_size=4))
68
-
69
- # hypo to ref scores are the recall
70
- hypo_ref_scores = np.array(scorer.score([prediction] * num_gold_labels, gold_labels, batch_size=4))
71
-
72
- # take max and average
73
- max_avg_f = (0.5 * (ref_hypo_scores + hypo_ref_scores)).max()
74
- hypo_ref = hypo_ref_scores.max()
75
- ref_hypo = ref_hypo_scores.max()
76
-
77
- return {"f_score": max_avg_f, "precision": ref_hypo, "recall": hypo_ref}
78
-
79
- def _compute_metrics(self, id_to_pred, id_to_labels):
80
 
81
- # init results dict
82
- result = {}
83
 
84
- # iterate scorers
85
- for scorer_name, scorer_getter in self.bart_scorers_initializers.items():
86
- scorer = scorer_getter()
87
 
88
- # calculate BARTScores
89
- logger.info(f"Calculating {scorer_name} BART scores...")
 
 
90
 
91
- # init bart_scores list
92
- num_missing_predictions = 0
93
- bart_scores = []
94
-
95
- # iterate question ids
96
- for question_id, question_gold_labels in tqdm(id_to_labels.items()):
97
-
98
- # check if there was a prediction to the question
99
- if question_id not in id_to_pred:
100
- num_missing_predictions += 1
101
- bart_scores.append(0.0)
102
- continue
103
-
104
- # get pred
105
- pred = id_to_pred[question_id]
106
-
107
- # calculate bart scores
108
- bart_scores.append(
109
- self.calc_bart_score(scorer=scorer, prediction=pred, gold_labels=question_gold_labels)
110
- )
111
-
112
- # Aggregate scorer metrics
113
- bart_score_f = np.mean([score["f_score"] for score in bart_scores])
114
- bart_score_precision = np.mean([score["precision"] for score in bart_scores])
115
- bart_score_recall = np.mean([score["recall"] for score in bart_scores])
116
-
117
- # scorer_results
118
- scorer_result = {
119
- f"{scorer_name}_BARTScore_f": bart_score_f,
120
- f"{scorer_name}_BARTScore_precision": bart_score_precision,
121
- f"{scorer_name}_BARTScore_recall": bart_score_recall,
122
- }
123
-
124
- logger.info(scorer_name)
125
- logger.info(scorer_result)
126
-
127
- # union results
128
- result = {**result, **scorer_result}
129
-
130
- # add results metadata
131
- result["num_missing_predictions"] = num_missing_predictions
132
 
133
- result = {k: round(v, 4) for k, v in result.items()}
134
 
135
- logger.info("### Bart scores: ###")
136
- logger.info(result)
137
- return result
 
 
 
 
 
1
  import os
2
  import numpy as np
3
  from BARTScore.bart_score import BARTScorer
 
 
 
4
 
 
5
 
6
+ def get_scorers():
7
+ assert os.path.isfile(
8
+ os.path.join("BARTScore", "bart.pth")
9
+ ), "You must download `bart.pth` to use BARTScore.\nUse `gdown --id 1_7JfF7KOInb7ZrxKHIigTMR4ChVET01m --output bart.pth`"
10
 
11
+ scorers = {}
 
 
 
12
 
13
+ scorers["vanilla"] = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large")
 
14
 
15
+ scorers["cnn"] = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large-cnn")
 
 
16
 
17
+ # for the parabank model, first init a bart model, then load the local para model from BARTScore/bart.pth
18
+ # see the documentation from https://github.com/neulab/BARTScore for reference
19
+ scorers["para"] = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large-cnn")
20
+ scorers["para"].load(path="BARTScore/bart.pth")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ return scorers
 
23
 
 
 
 
24
 
25
+ def compute_bart_score_for_scorer(predictions, references, scorer_name, scorer):
26
+ precisions = np.array(scorer.score(references, predictions, batch_size=4))
27
+ recalls = np.array(scorer.score(predictions, references, batch_size=4))
28
+ f_scores = 0.5 * (precisions + recalls)
29
 
30
+ return [
31
+ {
32
+ f"{scorer_name}_f_score": f_scores[i],
33
+ f"{scorer_name}_precision": precisions[i],
34
+ f"{scorer_name}_recall": recalls[i],
35
+ }
36
+ for i in range(len(predictions))
37
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
 
39
 
40
+ def compute_bart_score(predictions, references, scorers):
41
+ result = [{} for _ in range(len(predictions))]
42
+ for scorer_name, scorer in scorers.items():
43
+ scorer_result = compute_bart_score_for_scorer(predictions, references, scorer_name, scorer)
44
+ for i, element in enumerate(scorer_result):
45
+ result[i].update(element)
46
+ return result