Upload splitters.py with huggingface_hub
Browse files1234567789101171 unmodified lines838485868788897 unmodified lines9798991001011021031041051061076 unmodified lines1141151161101171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541181551561571581591601611251621631641652 unmodified lines16816917013417117217317417517617717813 unmodified lines1921931941541551561571951961971981992002012022032042052062072082092101662112122132141 unmodified line216217218174219220221177222223224225import itertoolsfrom abc import abstractmethodfrom random import Randomfrom typing import Dict, List
from .artifact import Artifactfrom .operator import InstanceOperatorWithMultiStreamAccess, MultiStreamOperatorfrom .random_utils import get_randomfrom .random_utils import new_random_generatorfrom .split_utils import ( parse_random_mix_string, parse_slices_string,71 unmodified lines
class Sampler(Artifact): sample_size: int = None random_generator: Random = new_random_generator(sub_seed="Sampler")
def prepare(self): super().prepare()7 unmodified lines size = int(size) self.sample_size = size
def init_new_random_generator(self): self.random_generator = new_random_generator( sub_seed="init_new_random_generator" )
@abstractmethod def sample( self, instances_pool: List[Dict[str, object]]6 unmodified lines self, instances_pool: List[Dict[str, object]] ) -> List[Dict[str, object]]: instances_pool = list(instances_pool) return get_random().sample(instances_pool, self.sample_size) 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 values appears 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 ignored then the instance is considered as ['dog','cat'].
Args: sample_size - number of samples to extract choices - name of input field that contains the list of values to balance on labels - name of output field with labels that must be balanced
"""
choices: str = "choices" labels: str = "labels"
def prepare(self): super().prepare() self.labels = None self.labels_cache = None
def 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}'.") raise ValueError(f"'{self.choices}' field is missing from '{inputs}'.") choices = inputs[self.choices] if not isinstance(choices, list): raise ValueError(2 unmodified lines
if "outputs" not in examplar: raise ValueError(f"'outputs' field is missing from '{examplar}'.") examplar_outputs = next(iter(examplar["outputs"].values())) 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 lines def 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) 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 Counter
if 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 = 0 allocations = 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: if len(self.labels_cache[label]) - allocations[label] > 0: allocations[label] += 1 total_allocated += 1 else:1 unmodified line
result = [] for label, allocation in allocations.items(): sample = get_random().sample(self.labels[label], allocation) sample = self.random_generator.sample(self.labels_cache[label], allocation) result.extend(sample)
get_random().shuffle(result) self.random_generator.shuffle(result) return result
splitters.py+57-12