Upload metrics.py with huggingface_hub
Browse files1234567353 unmodified lines361362363364365366367275 unmodified lines643644645646647648649597 unmodified lines124712481249125012511252125338 unmodified lines12921293129412951296129712987 unmodified lines130613071308130913101311import reimport stringimport uuidfrom abc import abstractmethodfrom collections import Counterfrom dataclasses import fieldfrom typing import Any, Dict, Generator, List, Optional, Tuple353 unmodified linesreferences: List[List[Any]],predictions: List[Any],additional_inputs: List[Dict],) -> Dict[str, Any]:pass275 unmodified linespredictions: List[str],additional_inputs: List[Any],) -> List[Dict[str, Any]]:passed_additional_inputs = {}passed_additional_inputs = {}for additional_input_field in self.hf_additional_input_fields:assert (597 unmodified linesreferences: List[List[Any]],predictions: List[Any],additional_inputs: List[Dict],) -> List[Any]:scores = []# we are in a multi-reference case (each prediction may have multiple38 unmodified linesreferences: List[List[Any]],predictions: List[Any],additional_inputs: List[Dict],) -> List[Any]:# treat the references as the questions and the predictions as answers# assume a single referencequestions = [refs[0] for refs in references]7 unmodified linesreturn self.pipe(inputs, batch_size=self.batch_size)class NDCG(GlobalMetric):"""Normalized Discounted Cumulative Gain: measures the quality of ranking with respect to ground truth ranking scores.1234567353 unmodified lines361362363364365366367275 unmodified lines643644645646647648597 unmodified lines124612471248124912501251125238 unmodified lines12911292129312941295129612977 unmodified lines1305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500import reimport stringimport uuidfrom abc import ABC, abstractmethodfrom collections import Counterfrom dataclasses import fieldfrom typing import Any, Dict, Generator, List, Optional, Tuple353 unmodified linesreferences: List[List[Any]],predictions: List[Any],additional_inputs: List[Dict],) -> List[Dict[str, Any]]:pass275 unmodified linespredictions: List[str],additional_inputs: List[Any],) -> List[Dict[str, Any]]:passed_additional_inputs = {}for additional_input_field in self.hf_additional_input_fields:assert (597 unmodified linesreferences: List[List[Any]],predictions: List[Any],additional_inputs: List[Dict],) -> List[Dict[str, Any]]:scores = []# we are in a multi-reference case (each prediction may have multiple38 unmodified linesreferences: List[List[Any]],predictions: List[Any],additional_inputs: List[Dict],) -> List[Dict[str, Any]]:# treat the references as the questions and the predictions as answers# assume a single referencequestions = [refs[0] for refs in references]7 unmodified linesreturn self.pipe(inputs, batch_size=self.batch_size)class Perplexity(BulkInstanceMetric):"""Computes the likelihood of generating text Y after text X - P(Y|X)."""main_score = "perplexity"reduction_map = {"mean": ["perplexity"]}perplexity_prompt: strbatch_size: int = 32model_name: strdef compute(self,references: List[List[Any]],predictions: List[Any],additional_inputs: List[Dict],) -> List[Dict[str, Any]]:"""Computes the likelihood of generating text Y after text X - P(Y|X).:param references: the list of Y texts as a list of singletons.:param predictions: the list of X texts as a plain list of strings:return: the likelihood of generating text Y_i after text X_i = P(Y_i|X_i) for every i."""# make sure all references are singletonsassert all(len(ref) == 1 for ref in references)# add the instruction as prefixpredictions = [f"{self.perplexity_prompt} {x}" for x in predictions]references = [y[0] for y in references]# check if the model is enc-dec or dec-only to use the right perplexity computationfrom transformers import AutoConfigconfig = AutoConfig.from_pretrained(self.model_name, trust_remote_code=True)lm = (self.EncoderDecoderLM(model_name=self.model_name)if config.is_encoder_decoder is Trueelse self.DecoderOnlyLM(model_name=self.model_name))# compute P(Q|P) and store in queuescores = lm.compute_lm(source=predictions, target=references, batch_size=self.batch_size)return [{self.main_score: score} for score in scores]class AbstractLM(ABC):def __init__(self, model_name):import torchfrom transformers import AutoTokenizerself.model_name = model_nameself.tokenizer = AutoTokenizer.from_pretrained(self.model_name)self.model = self.model_class().from_pretrained(self.model_name)self.is_cuda = torch.cuda.is_available()def compute_lm(self, source, target, batch_size: int) -> List[float]:import torchscores = []with torch.no_grad():# break the documents to batchesn_batches = int(len(source) / batch_size)batch_range = range(n_batches + 1)for batch in batch_range:batch_source = source[batch * batch_size : (batch + 1) * batch_size]batch_target = target[batch * batch_size : (batch + 1) * batch_size]if len(batch_source) > 0:# tokenize the source and targettokens_source = self.tokenizer(batch_source, padding=True, return_tensors="pt")tokens_target = self.tokenizer(batch_target, padding=True, return_tensors="pt")# compute the logitslogits, labels = self.compute_batch(tokens_source, tokens_target)# the model returns mean over all batch. We run the CE again without reduction# and extarct the mean for each documentloss_fct = torch.nn.CrossEntropyLoss(ignore_index=-100, reduction="none")loss = loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))loss = loss.view(len(batch_source), -1)# for each document, do mean only over the non zero values (sum(labels>0))batch_loss = torch.sum(loss, dim=1) / torch.sum(labels > 0, dim=1)# append the batch scores to the list of all scoresscores.append(batch_loss)return torch.cat(scores, dim=0).tolist()@abstractmethoddef model_class(self):pass@abstractmethoddef compute_batch(self, tokens_source, tokens_target):passclass EncoderDecoderLM(AbstractLM):def model_class(self):from transformers import AutoModelForSeq2SeqLMreturn AutoModelForSeq2SeqLMdef compute_batch(self, tokens_source, tokens_target):tokens_docs_ids = tokens_source["input_ids"]attention = tokens_source["attention_mask"]labels = tokens_target["input_ids"]if self.is_cuda:tokens_docs_ids, attention, labels = (tokens_docs_ids.cuda(),attention.cuda(),labels.cuda(),)logits = self.model(input_ids=tokens_docs_ids.long(),attention_mask=attention.long(),labels=labels.long(),).logits# replace the padding token in the labels by -100labels[labels == self.tokenizer.pad_token_id] = -100return logits, labelsclass DecoderOnlyLM(AbstractLM):def model_class(self):from transformers import AutoModelForCausalLMreturn AutoModelForCausalLMdef compute_batch(self, tokens_source, tokens_target):import torchtokens = torch.cat([tokens_source["input_ids"], tokens_target["input_ids"]], dim=1)attention = torch.cat([tokens_source["attention_mask"], tokens_target["attention_mask"]],dim=1,)labels = torch.cat([torch.zeros_like(tokens_source["input_ids"]).fill_(-100),tokens_target["input_ids"],],dim=1,)# replace the padding token in the labels by -100labels[labels == self.tokenizer.pad_token_id] = -100if self.is_cuda:tokens, attention, labels = (tokens.cuda(),attention.cuda(),labels.cuda(),)# no need to pass labels as we calculate the loss below per documentmodel_output = self.model(input_ids=tokens.long(), attention_mask=attention.long())logits = model_output.logits# in decoder only, the first token is not being generated, it is taken from the input,# so the model is generating from token 2 to n+1. therefore, we need to skip the last# logit and the first label.shifted_logits = logits[..., :-1, :].contiguous()shifted_labels = labels[..., 1:].contiguous()return shifted_logits, shifted_labelsclass NDCG(GlobalMetric):"""Normalized Discounted Cumulative Gain: measures the quality of ranking with respect to ground truth ranking scores.
metrics.py+194-5