|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import enum |
| 4 | +import itertools |
| 5 | +from dataclasses import dataclass |
| 6 | +from typing import Optional |
| 7 | + |
| 8 | +import torch |
| 9 | +import transformers |
| 10 | +from bert_score import BERTScorer |
| 11 | +from simple_parsing.helpers.fields import choice |
| 12 | +from torch import Tensor |
| 13 | + |
| 14 | +from mbrs import timer |
| 15 | + |
| 16 | +from . import Metric, register |
| 17 | + |
| 18 | +transformers.logging.set_verbosity_error() |
| 19 | + |
| 20 | + |
| 21 | +class BERTScoreScoreType(int, enum.Enum): |
| 22 | + precision = 0 |
| 23 | + recall = 1 |
| 24 | + f1 = 2 |
| 25 | + |
| 26 | + |
| 27 | +@register("bertscore") |
| 28 | +class MetricBERTScore(Metric): |
| 29 | + """BERTScore metric class.""" |
| 30 | + |
| 31 | + scorer: BERTScorer |
| 32 | + |
| 33 | + @dataclass |
| 34 | + class Config(Metric.Config): |
| 35 | + """BERTScore metric configuration. |
| 36 | +
|
| 37 | + - score_type (BERTScoreScoreType): The output score type, i.e., |
| 38 | + precision, recall, or f1. |
| 39 | + - model_type (str): Contexual embedding model specification, default using the |
| 40 | + suggested model for the target langauge; has to specify at least one of |
| 41 | + `model_type` or `lang`. |
| 42 | + - num_layers (int): The layer of representation to use. Default using the number |
| 43 | + of layer tuned on WMT16 correlation data. |
| 44 | + - idf (bool): A booling to specify whether to use idf or not. (This should be |
| 45 | + True even if `idf_sents` is given.) |
| 46 | + - idf_sents (list[str]): List of sentences used to compute the idf weights. |
| 47 | + - batch_size (int): Bert score processing batch size |
| 48 | + - nthreads (int): Number of threads. |
| 49 | + - lang (str): Language of the sentences; has to specify at least one of |
| 50 | + `model_type` or `lang`. `lang` needs to be specified when |
| 51 | + `rescale_with_baseline` is True. |
| 52 | + - rescale_with_baseline (bool): Rescale bertscore with pre-computed baseline. |
| 53 | + - baseline_path (str): Customized baseline file. |
| 54 | + - use_fast_tokenizer (bool): `use_fast` parameter passed to HF tokenizer. |
| 55 | + - fp16 (bool): Use float16 for the forward computation. |
| 56 | + - bf16 (bool): Use bfloat16 for the forward computation. |
| 57 | + - cpu (bool): Use CPU for the forward computation. |
| 58 | + """ |
| 59 | + |
| 60 | + score_type: BERTScoreScoreType = choice( |
| 61 | + BERTScoreScoreType, default=BERTScoreScoreType.f1 |
| 62 | + ) |
| 63 | + model_type: Optional[str] = None |
| 64 | + num_layers: Optional[int] = None |
| 65 | + batch_size: int = 64 |
| 66 | + nthreads: int = 4 |
| 67 | + all_layers: bool = False |
| 68 | + idf: bool = False |
| 69 | + idf_sents: Optional[list[str]] = None |
| 70 | + lang: Optional[str] = None |
| 71 | + rescale_with_baseline: bool = False |
| 72 | + baseline_path: Optional[str] = None |
| 73 | + use_fast_tokenizer: bool = False |
| 74 | + fp16: bool = False |
| 75 | + bf16: bool = False |
| 76 | + cpu: bool = False |
| 77 | + |
| 78 | + def __init__(self, cfg: MetricBERTScore.Config): |
| 79 | + self.cfg = cfg |
| 80 | + self.scorer = BERTScorer( |
| 81 | + model_type=cfg.model_type, |
| 82 | + num_layers=cfg.num_layers, |
| 83 | + batch_size=cfg.batch_size, |
| 84 | + nthreads=cfg.nthreads, |
| 85 | + all_layers=cfg.all_layers, |
| 86 | + idf=cfg.idf, |
| 87 | + idf_sents=cfg.idf_sents, |
| 88 | + device="cpu" if cfg.cpu else None, |
| 89 | + lang=cfg.lang, |
| 90 | + rescale_with_baseline=cfg.rescale_with_baseline, |
| 91 | + baseline_path=cfg.baseline_path, |
| 92 | + use_fast_tokenizer=cfg.use_fast_tokenizer, |
| 93 | + ) |
| 94 | + self.scorer._model.eval() |
| 95 | + for param in self.scorer._model.parameters(): |
| 96 | + param.requires_grad = False |
| 97 | + |
| 98 | + if not cfg.cpu and torch.cuda.is_available(): |
| 99 | + if cfg.fp16: |
| 100 | + self.scorer._model = self.scorer._model.half() |
| 101 | + elif cfg.bf16: |
| 102 | + self.scorer._model = self.scorer._model.bfloat16() |
| 103 | + self.scorer._model = self.scorer._model.cuda() |
| 104 | + |
| 105 | + @property |
| 106 | + def device(self) -> torch.device: |
| 107 | + """Returns the device of the model.""" |
| 108 | + return self.scorer._model.device |
| 109 | + |
| 110 | + def _choose_output_score(self, triplet: tuple[Tensor, Tensor, Tensor]) -> Tensor: |
| 111 | + """Choose the output score from the triplet of precision, recall, and f1 scores. |
| 112 | +
|
| 113 | + Args: |
| 114 | + triplet (tuple[Tensor, Tensor, Tensor]): A triplet of precision, recall, and f1 scores. |
| 115 | +
|
| 116 | + Returns: |
| 117 | + Tensor: Output score. |
| 118 | + """ |
| 119 | + return triplet[self.cfg.score_type] |
| 120 | + |
| 121 | + def score(self, hypothesis: str, reference: str, *_, **__) -> float: |
| 122 | + """Calculate the score of the given hypothesis. |
| 123 | +
|
| 124 | + Args: |
| 125 | + hypothesis (str): A hypothesis. |
| 126 | + reference (str): A reference. |
| 127 | +
|
| 128 | + Returns: |
| 129 | + float: The score of the given hypothesis. |
| 130 | + """ |
| 131 | + return self._choose_output_score( |
| 132 | + self.scorer.score( |
| 133 | + [hypothesis], |
| 134 | + [reference], |
| 135 | + batch_size=self.cfg.batch_size, |
| 136 | + ) |
| 137 | + ).item() |
| 138 | + |
| 139 | + def scores(self, hypotheses: list[str], references: list[str], *_, **__) -> Tensor: |
| 140 | + """Calculate the scores of the given hypothesis. |
| 141 | +
|
| 142 | + Args: |
| 143 | + hypotheses (list[str]): N hypotheses. |
| 144 | + references (list[str]): N references. |
| 145 | +
|
| 146 | + Returns: |
| 147 | + Tensor: The N scores of the given hypotheses. |
| 148 | + """ |
| 149 | + |
| 150 | + with timer.measure("score") as t: |
| 151 | + t.set_delta_ncalls(len(hypotheses)) |
| 152 | + return self._choose_output_score( |
| 153 | + self.scorer.score( |
| 154 | + hypotheses, |
| 155 | + references, |
| 156 | + batch_size=self.cfg.batch_size, |
| 157 | + ) |
| 158 | + ).view(len(hypotheses)) |
| 159 | + |
| 160 | + def pairwise_scores( |
| 161 | + self, hypotheses: list[str], references: list[str], *_, **__ |
| 162 | + ) -> Tensor: |
| 163 | + """Calculate the pairwise scores. |
| 164 | +
|
| 165 | + Args: |
| 166 | + hypotheses (list[str]): Hypotheses. |
| 167 | + references (list[str]): References. |
| 168 | +
|
| 169 | + Returns: |
| 170 | + Tensor: Score matrix of shape `(H, R)`, where `H` is the number |
| 171 | + of hypotheses and `R` is the number of references. |
| 172 | + """ |
| 173 | + hyps, refs = tuple(zip(*itertools.product(hypotheses, references))) |
| 174 | + with timer.measure("score") as t: |
| 175 | + t.set_delta_ncalls(len(hypotheses) * len(references)) |
| 176 | + return self._choose_output_score( |
| 177 | + self.scorer.score(hyps, refs, batch_size=self.cfg.batch_size) |
| 178 | + ).view(len(hypotheses), len(references)) |
| 179 | + |
| 180 | + def corpus_score( |
| 181 | + self, hypotheses: list[str], references: list[str], *_, **__ |
| 182 | + ) -> float: |
| 183 | + """Calculate the corpus-level score. |
| 184 | +
|
| 185 | + Args: |
| 186 | + hypotheses (list[str]): Hypotheses. |
| 187 | + references (list[str]): References. |
| 188 | +
|
| 189 | + Returns: |
| 190 | + float: The corpus score. |
| 191 | + """ |
| 192 | + return self.scores(hypotheses, references).mean().item() |
0 commit comments