Upload folder using huggingface_hub
Browse filesFiles changed (5)
- _version.pyDeleted-1
- common.pyDeleted-104
- load.pyDeleted-15
- renderers.pyDeleted-132
- serializers.pyDeleted-130
1def get_current_version(): return '1.0.31'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104from typing import Union
from .card import TaskCardfrom .collections import ItemPicker, RandomPickerfrom .dataclass import OptionalFieldfrom .operator import SourceOperatorfrom .recipe import Recipe, SequentialRecipefrom .schema import ToUnitxtGroupfrom .splitters import RandomSampler, Sampler, SeparateSplit, SliceSplit, SpreadSplitfrom .stream import MultiStreamfrom .templates import RenderTemplatedICL
class CommonRecipe(Recipe, SourceOperator): card: TaskCard demos_pool_name: str = "demos_pool" demos_taken_from: str = "train" demos_pool_size: int = None demos_field: str = "demos" num_demos: int = None sampler: Sampler = None instruction_item: Union[str, int] = None template_item: Union[str, int] = None system_prompt: str = None
def verify(self): super().verify()
def prepare(self): steps = [ self.card.loader, ]
if self.card.preprocess_steps is not None: steps.extend(self.card.preprocess_steps)
steps.append(self.card.task)
if self.demos_pool_size is not None: steps.append( SeparateSplit( from_split=self.demos_taken_from, to_split_names=[self.demos_pool_name, self.demos_taken_from], to_split_sizes=[int(self.demos_pool_size)], ) )
if self.num_demos is not None: sampler = self.card.sampler
if self.sampler is not None: sampler = self.sampler
sampler.set_size(self.num_demos)
steps.append( SpreadSplit( source_stream=self.demos_pool_name, target_field=self.demos_field, sampler=sampler, ) )
if self.card.instructions is not None: if not self.instruction_item is None: picker = ItemPicker(int(self.instruction_item)) else: picker = RandomPicker() instruction = picker(self.card.instructions) else: instruction = None
if self.card.templates is not None: if self.template_item is None: picker = RandomPicker() else: picker = ItemPicker(self.template_item) template = picker(self.card.templates) else: template = None
render = RenderTemplatedICL( instruction=instruction, template=template, demos_field=self.demos_field, system_prompt=self.system_prompt, )
steps.append(render)
postprocessors = render.get_postprocessors()
steps.append( ToUnitxtGroup( group="unitxt", metrics=self.card.task.metrics, postprocessors=postprocessors, ) )
self.recipe = SequentialRecipe(steps)
def process(self) -> MultiStream: return self.recipe()123456789101112131415from typing import Union
from datasets import DatasetDict
from .artifact import fetch_artifactfrom .operator import StreamSource
def load_dataset(source: Union[StreamSource, str]) -> DatasetDict: assert isinstance( source, (StreamSource, str) ), "source must be a StreamSource or a string" if isinstance(source, str): source, _ = fetch_artifact(source) return source().to_dataset()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132from abc import ABCfrom typing import Any, Dict, List, Optional
from .dataclass import InternalFieldfrom .formats import Format, ICLFormatfrom .instructions import Instructionfrom .operator import Operator, SequentialOperator, StreamInstanceOperatorfrom .random_utils import get_randomfrom .templates import Template
class Renderer(ABC): pass # @abstractmethod # def get_postprocessors(self) -> List[str]: # pass
class RenderTemplate(Renderer, StreamInstanceOperator): template: Template random_reference: bool = False skip_rendered_instance: bool = True
def process( self, instance: Dict[str, Any], stream_name: Optional[str] = None ) -> Dict[str, Any]: if self.skip_rendered_instance: if ( "inputs" not in instance and "outputs" not in instance and "source" in instance and "target" in instance and "references" in instance ): return instance
inputs = instance["inputs"] outputs = instance["outputs"]
source = self.template.process_inputs(inputs) targets = self.template.process_outputs(outputs)
if self.template.is_multi_reference: assert isinstance(targets, list), f"{targets} must be a list" references = targets if self.random_reference: target = get_random().choice(references) else: if len(references) == 0: raise ValueError("No references found") target = references[0] else: references = [targets] target = targets
instance.update( { "source": source, "target": target, "references": references, } )
return instance
class RenderDemonstrations(RenderTemplate): demos_field: str
def process( self, instance: Dict[str, Any], stream_name: Optional[str] = None ) -> Dict[str, Any]: demos = instance.get(self.demos_field, [])
processed_demos = [] for demo_instance in demos: demo_instance = super().process(demo_instance) processed_demos.append(demo_instance)
instance[self.demos_field] = processed_demos
return instance
class RenderInstruction(Renderer, StreamInstanceOperator): instruction: Instruction
def process( self, instance: Dict[str, Any], stream_name: Optional[str] = None ) -> Dict[str, Any]: if self.instruction is not None: instance["instruction"] = self.instruction() else: instance["instruction"] = "" return instance
class RenderFormat(Renderer, StreamInstanceOperator): format: Format demos_field: str = None
def process( self, instance: Dict[str, Any], stream_name: Optional[str] = None ) -> Dict[str, Any]: demos_instances = instance.pop(self.demos_field, None) if demos_instances is not None: instance["source"] = self.format.format( instance, demos_instances=demos_instances ) else: instance["source"] = self.format.format(instance) return instance
class StandardRenderer(Renderer, SequentialOperator): template: Template instruction: Instruction = None demos_field: str = None format: ICLFormat = None
steps: List[Operator] = InternalField(default_factory=list)
def prepare(self): self.steps = [ RenderTemplate(template=self.template), RenderDemonstrations(template=self.template, demos_field=self.demos_field), RenderInstruction(instruction=self.instruction), RenderFormat(format=self.format, demos_field=self.demos_field), ]
def get_postprocessors(self): return self.template.get_postprocessors()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130from abc import ABC, abstractmethodfrom copy import deepcopyfrom typing import ( Any, Dict, List,)
from .operators import FieldOperator
"""TableSerializer converts a given table into a flat sequence with special symbols.Input table format must be:{"header": ["col1", "col2"], "rows": [["row11", "row12"], ["row21", "row22"], ["row31", "row32"]]}Output format varies depending on the chosen serializer. Abstract class at the top defines structure of a typical table serializer that any concrete implementation should follow."""
class TableSerializer(ABC, FieldOperator): # main method to serialize a table @abstractmethod def serialize_table(self, table_content: Dict) -> str: pass
# method to process table header @abstractmethod def process_header(self, header: List): pass
# method to process a table row @abstractmethod def process_row(self, row: List, row_index: int): pass
# Concrete classes implementing table serializers follow.."""Indexed Row Major Table Serializer.Commonly used row major serialization format.Format: col : col1 | col2 | col 3 row 1 : val1 | val2 | val3 | val4 row 2 : val1 | ..."""
class IndexedRowMajorTableSerializer(TableSerializer): def process_value(self, table: Any) -> Any: table_input = deepcopy(table) return self.serialize_table(table_content=table_input)
# main method that processes a table # table_content must be in the presribed input format def serialize_table(self, table_content: Dict) -> str: # Extract headers and rows from the dictionary header = table_content.get("header", []) rows = table_content.get("rows", [])
assert header and rows, "Incorrect input table format"
# Process table header first serialized_tbl_str = self.process_header(header) + " "
# Process rows sequentially starting from row 1 for i, row in enumerate(rows, start=1): serialized_tbl_str += self.process_row(row, row_index=i) + " "
# return serialized table as a string return serialized_tbl_str.strip()
# serialize header into a string containing the list of column names separated by '|' symbol def process_header(self, header: List): return "col : " + " | ".join(header)
# serialize a table row into a string containing the list of cell values separated by '|' def process_row(self, row: List, row_index: int): serialized_row_str = "" row_cell_values = [ str(value) if isinstance(value, (int, float)) else value for value in row ]
serialized_row_str += " | ".join(row_cell_values)
return f"row {row_index} : {serialized_row_str}"
"""Markdown Table Serializer.Markdown table format is used in GitHub code primarily.Format:|col1|col2|col3||---|---|---||A|4|1||I|2|1|..."""
class MarkdownTableSerializer(TableSerializer): def process_value(self, table: Any) -> Any: table_input = deepcopy(table) return self.serialize_table(table_content=table_input)
# main method that serializes a table. # table_content must be in the presribed input format. def serialize_table(self, table_content: Dict) -> str: # Extract headers and rows from the dictionary header = table_content.get("header", []) rows = table_content.get("rows", [])
assert header and rows, "Incorrect input table format"
# Process table header first serialized_tbl_str = self.process_header(header)
# Process rows sequentially starting from row 1 for i, row in enumerate(rows, start=1): serialized_tbl_str += self.process_row(row, row_index=i)
# return serialized table as a string return serialized_tbl_str.strip()
# serialize header into a string containing the list of column names def process_header(self, header: List): header_str = "|{}|\n".format("|".join(header)) header_str += "|{}|\n".format("|".join(["---"] * len(header))) return header_str
# serialize a table row into a string containing the list of cell values def process_row(self, row: List, row_index: int): row_str = "" row_str += "|{}|\n".format("|".join(str(cell) for cell in row)) return row_str_version.pyDeleted-1
common.pyDeleted-104
load.pyDeleted-15
renderers.pyDeleted-132
serializers.pyDeleted-130