Upload splitters.py with huggingface_hub
Browse files1234567891071 unmodified lines8283848586877 unmodified lines95969798991006 unmodified lines1071081091101111121131141151161171181191201211221231241251261271282 unmodified lines13113213313413513613713 unmodified lines1511521531541551561571581591601611621631641651661671681691 unmodified line171172173174175176177178179180import itertoolsfrom abc import abstractmethodfrom typing import Dict, Listfrom .artifact import Artifactfrom .operator import InstanceOperatorWithMultiStreamAccess, MultiStreamOperatorfrom .random_utils import get_randomfrom .split_utils import (parse_random_mix_string,parse_slices_string,71 unmodified linesclass Sampler(Artifact):sample_size: int = Nonedef prepare(self):super().prepare()7 unmodified linessize = int(size)self.sample_size = size@abstractmethoddef sample(self, instances_pool: List[Dict[str, object]]6 unmodified linesself, instances_pool: List[Dict[str, object]]) -> List[Dict[str, object]]:instances_pool = list(instances_pool)return get_random().sample(instances_pool, self.sample_size)class DiverseLabelsSampler(Sampler):choices: str = "choices"def prepare(self):super().prepare()self.labels = Nonedef examplar_repr(self, examplar):if "inputs" not in examplar:raise ValueError(f"'inputs' field is missing from '{examplar}'.")inputs = examplar["inputs"]if self.choices not in inputs:raise ValueError(f"{self.choices} field is missing from '{inputs}'.")choices = inputs[self.choices]if not isinstance(choices, list):raise ValueError(2 unmodified linesif "outputs" not in examplar:raise ValueError(f"'outputs' field is missing from '{examplar}'.")examplar_outputs = next(iter(examplar["outputs"].values()))if not isinstance(examplar_outputs, list):raise ValueError(f"Unexpected examplar_outputs value '{examplar_outputs}'. Expected a list."13 unmodified linesdef sample(self, instances_pool: List[Dict[str, object]]) -> List[Dict[str, object]]:if self.labels is None:self.labels = self.divide_by_repr(instances_pool)all_labels = list(self.labels.keys())get_random().shuffle(all_labels)from collections import Countertotal_allocated = 0allocations = Counter()while total_allocated < self.sample_size:for label in all_labels:if total_allocated < self.sample_size:if len(self.labels[label]) - allocations[label] > 0:allocations[label] += 1total_allocated += 1else:1 unmodified lineresult = []for label, allocation in allocations.items():sample = get_random().sample(self.labels[label], allocation)result.extend(sample)get_random().shuffle(result)return result123456789101171 unmodified lines838485868788897 unmodified lines9798991001011021031041051061076 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641652 unmodified lines16816917017117217317417517617717813 unmodified lines1921931941951961971981992002012022032042052062072082092102112122132141 unmodified line216217218219220221222223224225import itertoolsfrom abc import abstractmethodfrom random import Randomfrom typing import Dict, Listfrom .artifact import Artifactfrom .operator import InstanceOperatorWithMultiStreamAccess, MultiStreamOperatorfrom .random_utils import new_random_generatorfrom .split_utils import (parse_random_mix_string,parse_slices_string,71 unmodified linesclass Sampler(Artifact):sample_size: int = Nonerandom_generator: Random = new_random_generator(sub_seed="Sampler")def prepare(self):super().prepare()7 unmodified linessize = int(size)self.sample_size = sizedef init_new_random_generator(self):self.random_generator = new_random_generator(sub_seed="init_new_random_generator")@abstractmethoddef sample(self, instances_pool: List[Dict[str, object]]6 unmodified linesself, instances_pool: List[Dict[str, object]]) -> List[Dict[str, object]]:instances_pool = list(instances_pool)return self.random_generator.sample(instances_pool, self.sample_size)class DiverseLabelsSampler(Sampler):"""Selects a balanced sample of instances based on an output field.(used for selecting demonstrations in-context learning)The field must contain list of values e.g ['dog'], ['cat'], ['dog','cat','cow'].The balancing is done such that each value or combination of valuesappears as equals as possible in the samples.The `choices` param is required and determines which values should be considered.Example:If choices is ['dog,'cat'] , then the following combinations will be considered.['']['cat']['dog']['dog','cat']If the instance contains a value not in the 'choice' param, it is ignored. For example,if choices is ['dog,'cat'] and the instance field is ['dog','cat','cow'], then 'cow' is ignoredthen the instance is considered as ['dog','cat'].Args:sample_size - number of samples to extractchoices - name of input field that contains the list of values to balance onlabels - name of output field with labels that must be balanced"""choices: str = "choices"labels: str = "labels"def prepare(self):super().prepare()self.labels_cache = Nonedef examplar_repr(self, examplar):if "inputs" not in examplar:raise ValueError(f"'inputs' field is missing from '{examplar}'.")inputs = examplar["inputs"]if self.choices not in inputs:raise ValueError(f"'{self.choices}' field is missing from '{inputs}'.")choices = inputs[self.choices]if not isinstance(choices, list):raise ValueError(2 unmodified linesif "outputs" not in examplar:raise ValueError(f"'outputs' field is missing from '{examplar}'.")outputs = examplar["outputs"]if self.labels not in outputs:raise ValueError(f"'{self.labels}' field is missing from '{outputs}'.")examplar_outputs = examplar["outputs"][self.labels]if not isinstance(examplar_outputs, list):raise ValueError(f"Unexpected examplar_outputs value '{examplar_outputs}'. Expected a list."13 unmodified linesdef sample(self, instances_pool: List[Dict[str, object]]) -> List[Dict[str, object]]:if self.labels_cache is None:self.labels_cache = self.divide_by_repr(instances_pool)all_labels = list(self.labels_cache.keys())self.random_generator.shuffle(all_labels)from collections import Counterif self.sample_size > len(instances_pool):raise ValueError(f"Request sample size {self.sample_size} is greater than number of instances {len(instances_pool)}")total_allocated = 0allocations = Counter()while total_allocated < self.sample_size:for label in all_labels:if total_allocated < self.sample_size:if len(self.labels_cache[label]) - allocations[label] > 0:allocations[label] += 1total_allocated += 1else:1 unmodified lineresult = []for label, allocation in allocations.items():sample = self.random_generator.sample(self.labels_cache[label], allocation)result.extend(sample)self.random_generator.shuffle(result)return result
splitters.py+57-12