Upload metrics.py with huggingface_hub
Browse files1234567891011121377 unmodified lines91929394959637 unmodified lines13413513613713813914014175 unmodified lines217218219220221222223224225226227228229230231232233234235236237238239240129 unmodified lines3703713723733743753763 unmodified lines38038138238338438538629 unmodified lines4164174184194204214224234244254264274283 unmodified lines432433434435436437438439440441442443444445446447448449450451112 unmodified lines564565566import uuidfrom abc import ABC, abstractmethodfrom collections import Counterfrom dataclasses import fieldfrom typing import Any, Dict, Generator, List, Optionalimport evaluateimport numpyfrom .dataclass import InternalFieldfrom .operator import (MultiStreamOperator,SingleStreamOperator,77 unmodified linespassclass InstanceMetric(SingleStreamOperator, Metric):implemented_reductions: List[str] = field(default_factory=lambda: ["mean"])37 unmodified linesfor instance in instances:yield instancedef _compute(self, references: List[List[str]], predictions: List[str]) -> dict:result = self.compute(references=references, predictions=predictions)result["score"] = result[self.main_score]result["score_name"] = self.main_scorereturn result75 unmodified linesclass HuggingfaceMetric(GlobalMetric):metric_name: str = Nonemain_score: str = Nonescale: float = 1.0hf_compute_args: dict = {}def prepare(self):super().prepare()self.metric = evaluate.load(self.metric_name)def compute(self, references: List[List[str]], predictions: List[str]) -> dict:result = self.metric.compute(predictions=predictions, references=references, **self.hf_compute_args)if self.scale != 1.0:for key in result:if isinstance(result[key], float):result[key] /= self.scalereturn resultclass F1(GlobalMetric):_metric = Nonemain_score = "f1_macro"129 unmodified linesclass Rouge(HuggingfaceMetric):metric_name = "rouge"main_score = "rougeL"scale = 1.03 unmodified linessent_split_newline: bool = Truedef prepare(self):self.hf_compute_args = {"use_aggregator": self.use_aggregator, "rouge_types": self.rouge_types}super().prepare()import nltk29 unmodified linesclass Wer(HuggingfaceMetric):metric_name = "wer"main_score = "wer"def prepare(self):super().prepare()self.metric = evaluate.load(self.metric_name)def compute(self, references: List[List[str]], predictions: List[str]) -> dict:assert all(len(reference) == 1 for reference in references3 unmodified linesreturn {self.main_score: result}class Bleu(HuggingfaceMetric):metric_name = "bleu"main_score = "bleu"scale = 1.0class SacreBleu(HuggingfaceMetric):metric_name = "sacrebleu"main_score = "score"scale = 1.0class MatthewsCorrelation(HuggingfaceMetric):metric_name = "matthews_correlation"main_score = "matthews_correlation"str_to_id: dict = InternalField(default_factory=dict)112 unmodified linesdef get_element_representation(self, element):return str(element)12345678910111213141577 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215337 unmodified lines19119219319419519619719875 unmodified lines274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335129 unmodified lines4654664674684694704713 unmodified lines47547647747847948048129 unmodified lines5115125135145155165175185193 unmodified lines523524525526527528529530112 unmodified lines643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764import reimport stringimport uuidfrom abc import ABC, abstractmethodfrom collections import Counterfrom dataclasses import fieldfrom typing import Any, Dict, Generator, List, Optional, Tupleimport evaluateimport numpyfrom .dataclass import InternalField, OptionalFieldfrom .operator import (MultiStreamOperator,SingleStreamOperator,77 unmodified linespassclass BulkInstanceMetric(SingleStreamOperator, Metric):main_score: strreduction_map: Dict[str, List[str]]implemented_reductions: List[str] = field(default_factory=lambda: ["mean"])def process(self, stream: Stream, stream_name: str = None) -> Generator:global_score = {}instances = []# consume the streamreferences, predictions = map(list, zip(*[(instance["references"], instance["prediction"]) for instance in stream]))# compute the metric over all refs and predsinstance_scores = self.compute(references=references, predictions=predictions)# add the score and score_name fieldsfor instance_score in instance_scores:instance_score["score"] = instance_score[self.main_score]instance_score["score_name"] = self.main_scorefor instance, score in zip(stream, instance_scores):if "score" not in instance:instance["score"] = {"global": global_score, "instance": {}}else:global_score = instance["score"]["global"]instance["score"]["instance"].update(score)instances.append(instance)for reduction, fields in self.reduction_map.items():assert (reduction in self.implemented_reductions), f"Reduction {reduction} is not implemented, use one of {self.implemented_reductions}"if reduction == "mean":from statistics import meanfor field in fields:global_score[field] = mean([instance["score"]["instance"][field] for instance in instances])if field == self.main_score:global_score["score"] = global_score[field]global_score["score_name"] = self.main_scorefor instance in instances:yield instance@abstractmethoddef compute(self, references: List[List[Any]], predictions: List[Any]) -> Dict[str, Any]:passclass InstanceMetric(SingleStreamOperator, Metric):implemented_reductions: List[str] = field(default_factory=lambda: ["mean"])37 unmodified linesfor instance in instances:yield instancedef _compute(self, references: List[str], prediction: str) -> dict:result = self.compute(references=references, prediction=prediction)result["score"] = result[self.main_score]result["score_name"] = self.main_scorereturn result75 unmodified linesclass HuggingfaceMetric(GlobalMetric):hf_metric_name: str = Nonemain_score: str = None # The main score returned from the metrichf_main_score: str = None # USed if HF returns uses a different score name for the main metricscale: float = 1.0 # optional scaling of main resultsscaled_fields: list = Nonehf_compute_args: Dict[str, Any] = OptionalField(default_factory=dict)experiment_id: str = OptionalField(default_factory=lambda: str(uuid.uuid4()))def prepare(self):super().prepare()self.metric = evaluate.load(self.hf_metric_name, experiment_id=self.experiment_id)def compute(self, references: List[List[str]], predictions: List[str]) -> dict:result = self.metric.compute(predictions=predictions, references=references, **self.hf_compute_args)if self.hf_main_score:result[self.main_score] = result[self.hf_main_score]del result[self.hf_main_score]if self.scale != 1.0:assert self.scaled_fields is not None, f"Scaling factor was set to {self.scale}, but no fields specified"for key in self.scaled_fields:assert key in result, f"Trying to scale field '{key}' which is not in results of metrics: {result}"if isinstance(result[key], list):assert all(isinstance(v, float) for v in result[key]), "Not all scaled field '{key}' values are floats: {result[key]}"result[key] = [v / self.scale for v in result[key]]else:assert isinstance(result[key], float), "Scaled field '{key}' is not float: {result[key]}"result[key] /= self.scalereturn resultclass HuggingfaceBulkMetric(BulkInstanceMetric):hf_metric_name: strhf_metric_fields: List[str]hf_compute_args: dict = {}def prepare(self):super().prepare()self.metric = evaluate.load(self.hf_metric_name)def compute(self, references: List[List[str]], predictions: List[str]) -> List[Dict[str, Any]]:scores = self.metric.compute(predictions=predictions, references=references, **self.hf_compute_args)# convert dict of lists to a list of dictsresults = [{} for _ in range(len(scores[self.hf_metric_fields[0]]))]for key in self.hf_metric_fields:values = scores[key]for result_id, result in enumerate(results):result[key] = values[result_id]return resultsclass F1(GlobalMetric):_metric = Nonemain_score = "f1_macro"129 unmodified linesclass Rouge(HuggingfaceMetric):hf_metric_name = "rouge"main_score = "rougeL"scale = 1.03 unmodified linessent_split_newline: bool = Truedef prepare(self):self.hf_compute_args.update({"use_aggregator": self.use_aggregator, "rouge_types": self.rouge_types})super().prepare()import nltk29 unmodified linesclass Wer(HuggingfaceMetric):hf_metric_name = "wer"main_score = "wer"def compute(self, references: List[List[str]], predictions: List[str]) -> dict:assert all(len(reference) == 1 for reference in references3 unmodified linesreturn {self.main_score: result}class MatthewsCorrelation(HuggingfaceMetric):hf_metric_name = "matthews_correlation"main_score = "matthews_correlation"str_to_id: dict = InternalField(default_factory=dict)112 unmodified linesdef get_element_representation(self, element):return str(element)def normalize_answer(s):"""Lower text and remove punctuation, articles and extra whitespace."""def remove_articles(text):return re.sub(r"\b(a|an|the)\b", " ", text)def white_space_fix(text):return " ".join(text.split())def remove_punc(text):exclude = set(string.punctuation)return "".join(ch for ch in text if ch not in exclude)def lower(text):return text.lower()return white_space_fix(remove_articles(remove_punc(lower(s))))class TokenOverlap(InstanceMetric):reduction_map = {"mean": ["f1", "precision", "recall"]}main_score = "f1"def compute(self, references: List[Any], prediction: Any) -> dict:results = [self._compute_single_ref(reference, prediction) for reference in references]return {measure: max(r[i] for r in results) for i, measure in enumerate(["precision", "recall", "f1"])}def _compute_single_ref(self, reference: Any, prediction: Any) -> Tuple[float, float, float]:prediction_tokens = normalize_answer(prediction).split()reference_tokens = normalize_answer(reference).split()common = Counter(prediction_tokens) & Counter(reference_tokens)num_same = sum(common.values())if num_same == 0:pr, rc, f1 = 0, 0, 0else:pr = 1.0 * num_same / len(prediction_tokens)rc = 1.0 * num_same / len(reference_tokens)f1 = (2 * pr * rc) / (pr + rc)return pr, rc, f1class BertScore(HuggingfaceBulkMetric):hf_metric_name = "bertscore"main_score = "f1"reduction_map = {"mean": ["f1", "precision", "recall"]}hf_metric_fields = ["f1", "precision", "recall"]model_name: strdef prepare(self):super().prepare()self.hf_compute_args = {"model_type": self.model_name}class SentenceBert(BulkInstanceMetric):reduction_map = {"mean": ["score"]}main_score = "score"batch_size: int = 32model_name: strdef prepare(self):super().prepare()from sentence_transformers import SentenceTransformerfrom sentence_transformers import util as sbert_utilself.model = SentenceTransformer(self.model_name)self.util = sbert_utildef compute(self, references: List[List[Any]], predictions: List[Any]) -> List[Any]:scores = []# we are in a multi-reference case (each prediction may have multiple# references), so we need to flatten the refs in order to compute the# embeddings in one batch, but first we have to store the spans of# reference groups, so we can recover it later on.ref_group_boundaries = []count = 0for ref_group in references:ref_group_boundaries.append((count, count + len(ref_group)))count += len(ref_group)# compute s-bert embeddingspreds_emb = self.model.encode(predictions)refs_emb = self.model.encode([ref for ref_group in references for ref in ref_group])# for each candidate, pick the reference with the highest scorefor pred_emb, ref_group_bounds in zip(preds_emb, ref_group_boundaries):refs_group_emb = refs_emb[ref_group_bounds[0] : ref_group_bounds[1]]scores.append(self.util.cos_sim(pred_emb, refs_group_emb).max().item())return [{"score": score} for score in scores]class Reward(BulkInstanceMetric):reduction_map = {"mean": ["score"]}main_score = "score"batch_size: int = 32model_name: strdef prepare(self):from transformers import pipelineself.pipe = pipeline("text-classification", model=self.model_name)def compute(self, references: List[List[Any]], predictions: List[Any]) -> List[Any]:# treat the references as the questions and the predictions as answers# assume a single referencequestions = [refs[0] for refs in references]answers = predictions# prepare for computationinputs = [{"text": q, "text_pair": a} for q, a in zip(questions, answers)]# compute the metric# add function_to_apply="none" to disable sigmoidreturn self.pipe(inputs, batch_size=self.batch_size)
metrics.py+229-31