Upload templates.py with huggingface_hub
Browse files1234567 unmodified lines1415161718192021222324259 unmodified lines353637383940411 unmodified line4344454647484950515219 unmodified lines727374757677787980818283847 unmodified lines92939495969751 unmodified lines14915015115215315415515615715815916016116216316416516616753 unmodified lines22122222322422522622722822923023123223323423523623723823924025 unmodified lines2662672682692702712722732747 unmodified lines2822832842852862872882892902917 unmodified lines2993003013023033043053063073083093103114 unmodified lines316317318319320321322323324import jsonfrom abc import abstractmethodfrom dataclasses import fieldfrom typing import Any, Dict, List, Optional, Tuplefrom .collections import ListCollection7 unmodified lines"""The role of template is to take the fields of every instance and verbalize it.Meaning the template is taking the instance and generating source, target and references."""skip_rendered_instance: bool = NonPositionalField(default=True)postprocessors: List[str] = NonPositionalField(default_factory=lambda: ["processors.to_string_stripped"])def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None9 unmodified linesinputs = instance.get("inputs")outputs = instance.get("outputs")source = self.inputs_to_source(inputs)target, references = self.outputs_to_target_and_references(outputs)return {1 unmodified line"source": source,"target": target,"references": references,}@abstractmethoddef inputs_to_source(self, inputs: Dict[str, object]) -> str:pass@abstractmethod19 unmodified linesdata = {k: ", ".join(v) if isinstance(v, list) else v for k, v in data.items()}return template.format(**data)def inputs_to_source(self, inputs: Dict[str, object]) -> str:try:return self.process_template(self.input_format, inputs)except KeyError as e:raise KeyError(f"Available inputs are {list(inputs.keys())} but input format requires a different ones: '{self.input_format}'") from edef outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:try:7 unmodified linesreturn target, referencesclass MultipleChoiceTemplate(Template):"""Formats the input (that specifies the question), the multiple choices to select the answer from, and specifies the field with the correct answer."""51 unmodified lines)return enumrated_choicesdef inputs_to_source(self, inputs: Dict[str, object]) -> str:choices = self.get_choices(inputs, self.source_choice_format)inputs = {"numerals": ",".join(self.get_choices(inputs, "{choice_numeral}")),**inputs,self.choices_field: self.choices_seperator.join(choices),}try:return self.input_format.format(**inputs)except KeyError as e:raise KeyError(f"Available inputs are {inputs.keys()} but input format requires a different one: {self.input_format}") from edef outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = outputs[self.target_field]53 unmodified lineslabel_field: str = Noneyes_answer: str = "Yes"no_answer: str = "No"postprocessors: List[str] = field(default_factory=lambda: ["processors.to_string_stripped"])def inputs_to_source(self, inputs: Dict[str, object]) -> str:try:data = {k: ", ".join(v) if isinstance(v, list) else v for k, v in inputs.items()}return self.input_format.format(**data)except KeyError as e:raise RuntimeError(f"Available inputs are {list(inputs.keys())} but input format requires a different one: {self.input_format}") from edef outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:try:25 unmodified linesreturn self.yes_answer, [self.yes_answer]return self.no_answer, [self.no_answer]def get_postprocessors(self) -> List[str]:return self.postprocessorsclass KeyValTemplate(Template):"""Generate field 'source' from fields designated as input, and fields 'target' and 'references' from fields designated as output, of the processed instance.7 unmodified linesoutputs_key_val_seperator: str = ": "use_keys_for_outputs: bool = Falsepostprocessors: List[str] = field(default_factory=lambda: ["processors.to_string_stripped"])def process_dict(self, dic: Dict[str, object], key_val_sep, pairs_sep, use_keys) -> str:7 unmodified linespairs.append(key_val_sep.join(key_val))return pairs_sep.join(pairs)def inputs_to_source(self, inputs: Dict[str, object]) -> str:return self.process_dict(inputs,key_val_sep=self.key_val_seperator,pairs_sep=self.pairs_seperator,use_keys=self.use_keys_for_inputs,)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = self.process_dict(4 unmodified lines)return target, [target]def get_postprocessors(self) -> List[str]:return self.postprocessorsclass OutputQuantizingTemplate(InputOutputTemplate):quantum: float = 0.1123457 unmodified lines1314151617181920212223242526272829303132339 unmodified lines434445464748491 unmodified line51525354555657585960616219 unmodified lines82838485868788899091929394959697987 unmodified lines10610710810911011111211311411511611711811912012112212312412512612712812913051 unmodified lines18218318418518618718818919019119219319419519619719819920020120220353 unmodified lines25725825926026126226326426526626726826927027127227327427527625 unmodified lines3023033043053063077 unmodified lines3153163173183193207 unmodified lines3283293303313323333343353363373383393403414 unmodified lines346347348349350351import jsonfrom abc import abstractmethodfrom typing import Any, Dict, List, Optional, Tuplefrom .collections import ListCollection7 unmodified lines"""The role of template is to take the fields of every instance and verbalize it.Meaning the template is taking the instance and generating source, target and references.Args:skip_rendered_instance (bool): if "source", "target", and "references" are already defined fields in the instance, skip its processingpostprocessors: a list of strings being artifact names of text processors, to be applied on the model outputinstruction: a formatting string that yields an instruction with potential participation of values from the "inputs" part of the instancetarget_prefix: a string to be used to format the prompt. Not a formatting string."""skip_rendered_instance: bool = NonPositionalField(default=True)postprocessors: List[str] = NonPositionalField(default_factory=lambda: ["processors.to_string_stripped"])instruction: str = NonPositionalField(default_factory=lambda: "")target_prefix: str = NonPositionalField(default_factory=lambda: "")def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None9 unmodified linesinputs = instance.get("inputs")outputs = instance.get("outputs")source, instruction = self.inputs_to_source(inputs)target, references = self.outputs_to_target_and_references(outputs)return {1 unmodified line"source": source,"target": target,"references": references,"instruction": instruction,"target_prefix": self.target_prefix.format(**inputs),}@abstractmethoddef inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:pass@abstractmethod19 unmodified linesdata = {k: ", ".join(v) if isinstance(v, list) else v for k, v in data.items()}return template.format(**data)def inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:formatted = []for formatting in [self.input_format, self.instruction]:try:formatted.append(self.process_template(formatting, inputs))except KeyError as e:raise KeyError(f"Available inputs are {list(inputs.keys())} but input format requires a different ones: '{formatting}'") from ereturn tuple(formatted)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:try:7 unmodified linesreturn target, referencesclass InputOutputReferenceTemplate(InputOutputTemplate):reference: strdef outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:output_fields = {}for name, val in [("target", self.output_format),("reference", self.reference),]:try:result = self.process_template(val, outputs)output_fields[name] = resultexcept KeyError as e:raise KeyError(f"Available outputs are {outputs.keys()} but {name} requires a different one: {val}") from ereturn output_fields["target"], [output_fields["reference"]]class MultipleChoiceTemplate(Template):"""Formats the input (that specifies the question), the multiple choices to select the answer from, and specifies the field with the correct answer."""51 unmodified lines)return enumrated_choicesdef inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:choices = self.get_choices(inputs, self.source_choice_format)inputs = {"numerals": ",".join(self.get_choices(inputs, "{choice_numeral}")),**inputs,self.choices_field: self.choices_seperator.join(choices),}formatted = []for formatting in [self.input_format, self.instruction]:try:formatted.append(formatting.format(**inputs))except KeyError as e:raise KeyError(f"Available inputs are {inputs.keys()} but input format requires a different one: {formatting}") from ereturn tuple(formatted)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = outputs[self.target_field]53 unmodified lineslabel_field: str = Noneyes_answer: str = "Yes"no_answer: str = "No"def inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:data = {k: ", ".join(v) if isinstance(v, list) else v for k, v in inputs.items()}formatted = []for formatting in [self.input_format, self.instruction]:try:formatted.append(formatting.format(**data))except KeyError as e:raise RuntimeError(f"Available inputs are {list(inputs.keys())} but input format requires a different one: {formatting}") from ereturn tuple(formatted)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:try:25 unmodified linesreturn self.yes_answer, [self.yes_answer]return self.no_answer, [self.no_answer]class KeyValTemplate(Template):"""Generate field 'source' from fields designated as input, and fields 'target' and 'references' from fields designated as output, of the processed instance.7 unmodified linesoutputs_key_val_seperator: str = ": "use_keys_for_outputs: bool = Falsedef process_dict(self, dic: Dict[str, object], key_val_sep, pairs_sep, use_keys) -> str:7 unmodified linespairs.append(key_val_sep.join(key_val))return pairs_sep.join(pairs)def inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:ret = self.process_dict(inputs,key_val_sep=self.key_val_seperator,pairs_sep=self.pairs_seperator,use_keys=self.use_keys_for_inputs,)return (ret, ret)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = self.process_dict(4 unmodified lines)return target, [target]class OutputQuantizingTemplate(InputOutputTemplate):quantum: float = 0.1
templates.py+69-42