Upload metrics.py with huggingface_hub
Browse files1878 unmodified lines1879188018811882188318841 unmodified line188618871888188918901891189254 unmodified lines194719481949195019511952188 unmodified lines21412142214321442145214621472148214910 unmodified lines21602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218316 unmodified lines220022012202220322042205220622073 unmodified lines22112212221322142215221615 unmodified lines22322233223422352236223722381114 unmodified lines33533354335533563357335833591 unmodified line3361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333841878 unmodified lineshf_metric_fields = ["f1", "precision", "recall"]ci_scores = ["f1", "precision", "recall"]model_name: strprediction_type = "str"1 unmodified linedef prepare(self):super().prepare()self.hf_compute_args = {"model_type": self.model_name, "batch_size": 16}class SentenceBert(BulkInstanceMetric):54 unmodified linesmodel_name: str_requirements_list: List[str] = ["transformers", "torch"]def prepare(self):188 unmodified linesreduction_map = {"mean": ["perplexity"]}prediction_type = "str"perplexity_prompt: strbatch_size: int = 32model_name: str_requirements_list: List[str] = ["transformers", "torch"]10 unmodified lines:return: the likelihood of generating text Y_i after each text X_i_j = P(Y_i|X_i_1), ..., P(Y_i|X_i_n) for every i."""sources = []targets = []for prediction, instance_references in zip(predictions, references):for instance_reference in instance_references:sources.append(f"{self.perplexity_prompt} {instance_reference}")targets.append(prediction)from 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=sources, target=targets, batch_size=self.batch_size)16 unmodified linesreturn all_instances_scoresclass AbstractLM(ABC):def __init__(self, model_name):import torchfrom transformers import AutoTokenizer3 unmodified linesself.model_class().from_pretrained(self.model_name).to(self.device))self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)def compute_lm(self, source: List[str], target: List[str], batch_size: int15 unmodified linesbatch_source, padding=True, return_tensors="pt")tokens_target = self.tokenizer(batch_target, padding=True, return_tensors="pt")# compute the logits1114 unmodified linesdef compute(self,references: List[List[str]],predictions: List[List[str]],task_data: List[Dict],) -> dict:float_predictions = [to_float_or_default(p) for p in predictions]1 unmodified line["1"] if r[0].lower() in self.pos_classes else ["0"] for r in references]best_thr = -1best_acc = -1for thr in set(float_predictions):new_predictions = ["1" if float_prediction >= thr else "0"for float_prediction in float_predictions]acc = np.mean([[prediction] == referencefor prediction, reference in zip(new_predictions, references)])if acc > best_acc:best_acc = accbest_thr = thrreturn {self.main_score: best_acc, "best_thr_max_acc": best_thr}######################1878 unmodified lines18791880188118821883188418851 unmodified line18871888188918901891189218931894189554 unmodified lines195019511952195319541955195619571958188 unmodified lines214721482149215021512152215321542155215621572158215910 unmodified lines2170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221016 unmodified lines22272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022513 unmodified lines225522562257225822592260226115 unmodified lines22772278227922802281228222832284228522861114 unmodified lines34013402340334043405340634071 unmodified line340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034611878 unmodified lineshf_metric_fields = ["f1", "precision", "recall"]ci_scores = ["f1", "precision", "recall"]model_name: strmodel_layer: int = Noneprediction_type = "str"1 unmodified linedef prepare(self):super().prepare()self.hf_compute_args = {"model_type": self.model_name, "batch_size": 32}if self.model_layer:self.hf_compute_args["num_layers"] = self.model_layerclass SentenceBert(BulkInstanceMetric):54 unmodified linesmodel_name: strprediction_type = "str"single_reference_per_prediction = True_requirements_list: List[str] = ["transformers", "torch"]def prepare(self):188 unmodified linesreduction_map = {"mean": ["perplexity"]}prediction_type = "str"source_template: strtarget_template: strbatch_size: int = 32model_name: strsingle_token_mode: bool = Falselm = None_requirements_list: List[str] = ["transformers", "torch"]10 unmodified lines:return: the likelihood of generating text Y_i after each text X_i_j = P(Y_i|X_i_1), ..., P(Y_i|X_i_n) for every i."""if self.lm is None:from transformers import AutoConfigconfig = AutoConfig.from_pretrained(self.model_name, trust_remote_code=True)self.lm = (self.EncoderDecoderLM(model_name=self.model_name, single_token_mode=self.single_token_mode)if config.is_encoder_decoder is Trueelse self.DecoderOnlyLM(model_name=self.model_name, single_token_mode=self.single_token_mode))sources = []targets = []for prediction, instance_references in zip(predictions, references):for instance_reference in instance_references:sources.append(self.Template.apply(self.source_template,prediction=prediction,reference=instance_reference,))targets.append(self.Template.apply(self.target_template,prediction=prediction,reference=instance_reference,))# compute P(Q|P) and store in queuescores = self.lm.compute_lm(source=sources, target=targets, batch_size=self.batch_size)16 unmodified linesreturn all_instances_scoresclass Template:regex = re.compile(r"\{(\w+)}")@classmethoddef apply(cls, template, **kwargs):matches = Perplexity.Template.regex.finditer(template)output = []cursor = 0for match in matches:start = match.start()end = match.end()output.append(template[cursor:start])output.append(kwargs[match.group(1)])cursor = endoutput.append(template[cursor:])return "".join(output)class AbstractLM(ABC):def __init__(self, model_name, single_token_mode):import torchfrom transformers import AutoTokenizer3 unmodified linesself.model_class().from_pretrained(self.model_name).to(self.device))self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)self.single_token_mode = single_token_modedef compute_lm(self, source: List[str], target: List[str], batch_size: int15 unmodified linesbatch_source, padding=True, return_tensors="pt")tokens_target = self.tokenizer(batch_target,padding=True,return_tensors="pt",add_special_tokens=not self.single_token_mode,)# compute the logits1114 unmodified linesdef compute(self,references: List[List[str]],predictions: List[str],task_data: List[Dict],) -> dict:float_predictions = [to_float_or_default(p) for p in predictions]1 unmodified line["1"] if r[0].lower() in self.pos_classes else ["0"] for r in references]# Sticking to the test >= thr, accuracy induced by threshold thr is the number of float predictions# that pass the test (are >= thr) and are paired with reference "1" plus the number of float predictions that# fail the test (are < thr) and are paired with reference "0".# A given threshold thr induces the same partition over the float predictions into passing and failing# as threshold thr' induces, with thr' being the smallest among the ones passing the test of thr.# Hence, we only need to review thresholds being float predictions, plus a threshold being larger than# the largest float predictions, to induce the partition into all-failing , none-passing.fp = [(float_predictions[i], i, -1 if references[i][0] == "1" else +1)for i in range(len(float_predictions))]fp.sort()# each triplet above: float-prediction f; f's ordinal position in float_predictions, which is also# a means to obtain distinct triplets; and: the change in number of predictions that the test sends# to the reference they are paired with, a change implied by a move of thr that transfers f# from the set of passing the test to the set of failing it.rightmost_thr = 1.0 if fp[-1][0] < 1 else fp[-1][0] + 0.01# trying to be esthetic, have the threshold within [0,1], although this is not a requirement,# and even the float predictions are not guaranteed to be within the range [0,1]current_thr = fp[0][0]# partition float_predictions into all-passing, none-failingcurrent_acc = sum(r[0] == "1" for r in references)# number of predictions that thr sends to the reference they are paired withbest_acc = current_accbest_thr = current_thri = 0while (i < len(predictions)) and (best_acc < len(predictions)):# best_acc can not exceed len(predictions)delta = fp[i][2]i += 1while i < len(predictions) and fp[i][0] <= fp[i - 1][0]:delta += fp[i][2]i += 1current_acc += deltaif current_acc > best_acc:best_acc = current_accbest_thr = fp[i][0] if i < len(predictions) else rightmost_thrreturn {self.main_score: float(best_acc) / len(predictions),"best_thr_max_acc": best_thr,}######################
metrics.py+111-34