text
stringlengths
1
1.02k
class_index
int64
0
271
source
stringclasses
76 values
Args: features ([`Features`]): New features to cast the dataset to. The name of the fields in the features must match the current column names. The type of the data must also be convertible from one type to the other. For non-trivial conversion...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
cache_file_name (`str`, *optional*, defaults to `None`): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Nu...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Returns: [`Dataset`]: A copy of the dataset with casted features. Example:
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset, ClassLabel, Value >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.features {'label': ClassLabel(names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> new_features = ds.features.copy() ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
schema = features.arrow_schema format = self.format dataset = self.with_format("arrow") # capture the PyArrow version here to make the lambda serializable on Windows dataset = dataset.map( partial(table_cast, schema=schema), batched=True, batch_size=ba...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: column (`str`): Column name. feature (`FeatureType`): Target feature. new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset, ClassLabel >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.features {'label': ClassLabel(names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> ds = ds.cast_column('label', ClassLabel(n...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
return self.cast(features)
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@transmit_format @fingerprint_transform(inplace=False) def remove_columns(self, column_names: Union[str, List[str]], new_fingerprint: Optional[str] = None) -> "Dataset": """ Remove one or several column(s) in the dataset and the features associated to them. You can also remove a column ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds = ds.remove_columns('label') Dataset({ features: ['text'], num_rows: 1066 }) >>> ds = ds.remove_columns(column_names=ds.column_names) # ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
for column_name in column_names: del dataset._info.features[column_name] dataset._data = dataset._data.drop(column_names) dataset._data = update_metadata_with_features(dataset._data, dataset.features) dataset._fingerprint = new_fingerprint return dataset @fingerprint_tr...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: original_column_name (`str`): Name of the column to rename. new_column_name (`str`): New name for the column. new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds = ds.rename_column('label', 'label_new') Dataset({ features: ['text', 'label_new'], num_rows: 1066 }) ``` """ dataset = ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
raise ValueError("New column name is empty.")
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def rename(columns): return [new_column_name if col == original_column_name else col for col in columns] new_column_names = rename(self._data.column_names) if self._format_columns is not None: dataset._format_columns = rename(self._format_columns) dataset._info.features...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@fingerprint_transform(inplace=False) def rename_columns(self, column_mapping: Dict[str, str], new_fingerprint: Optional[str] = None) -> "Dataset": """ Rename several columns in the dataset, and move the features associated to the original columns under the new column names. Args: ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds = ds.rename_columns({'text': 'text_new', 'label': 'label_new'}) Dataset({ features: ['text_new', 'label_new'], num_rows: 1066 }) ``` ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
number_of_duplicates_in_new_columns = len(column_mapping.values()) - len(set(column_mapping.values())) if number_of_duplicates_in_new_columns != 0: raise ValueError( "New column names must all be different, but this column mapping " f"has {number_of_duplicates_in_new_...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
dataset._info.features = Features( { column_mapping[col] if col in column_mapping else col: feature for col, feature in (self._info.features or {}).items() } ) dataset._data = dataset._data.rename_columns(new_column_names) dataset._data = ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: column_names (`Union[str, List[str]]`): Name of the column(s) to keep. new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
missing_columns = set(column_names) - set(self._data.column_names) if missing_columns: raise ValueError( f"Column name {list(missing_columns)} not in the " "dataset. Current columns in the dataset: " f"{self._data.column_names}." ) ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.__len__ <bound method Dataset.__len__ of Dataset({ features: ['text', 'label'], num_rows: 1066 })> ``` """ return self.n...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
If a formatting is set with [`Dataset.set_format`] rows will be returned with the selected format. """ if self._indices is None: # Fast iteration # Benchmark: https://gist.github.com/mariosasko/0248288a2e3a7556873969717c1fe52b (fast_iter_batch) format_kwargs =...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
output_all_columns=self._output_all_columns, ) yield formatted_output else: for i in range(self.num_rows): yield self._getitem( i, )
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def iter(self, batch_size: int, drop_last_batch: bool = False): """Iterate through the batches of size `batch_size`. If a formatting is set with [`~datasets.Dataset.set_format`] rows will be returned with the selected format.
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: batch_size (:obj:`int`): size of each batch to yield. drop_last_batch (:obj:`bool`, default `False`): Whether a last batch smaller than the batch_size should be dropped """ if self._indices is None: # Fast iteration # Benchmark: https...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
) yield formatted_batch else: num_rows = self.num_rows if not drop_last_batch else self.num_rows // batch_size * batch_size for i in range(0, num_rows, batch_size): yield self._getitem( slice(i, i + batch_size), )
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def __repr__(self): return f"Dataset({{\n features: {list(self._info.features.keys())},\n num_rows: {self.num_rows}\n}})" @property def format(self): return { "type": self._format_type, "format_kwargs": self._format_kwargs, "columns": self.column_names ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: type (`str`, *optional*): Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__`` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in the ou...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
self.set_format(type, columns, output_all_columns, **format_kwargs) yield finally: self.set_format(old_format_type, old_format_columns, old_output_all_columns, **old_format_kwargs)
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@fingerprint_transform(inplace=True) def set_format( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ): """Set `__getitem__` return format (type and columns). The data formatting is applied on-th...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: type (`str`, *optional*): Either output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
It is possible to call [`~datasets.Dataset.map`] after calling `set_format`. Since `map` may add new columns, then the list of formatted columns gets updated. In this case, if you apply `map` on a dataset to add a new column, then this column will be formatted as: ``` new formatted colu...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, pad...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Check filter column if isinstance(columns, str): columns = [columns] if isinstance(columns, tuple): columns = list(columns) if columns is not None: missing_columns = set(columns) - set(self._data.column_names) if missing_columns: ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
self._format_type = type self._format_kwargs = format_kwargs self._format_columns = columns self._output_all_columns = output_all_columns logger.debug( "Set __getitem__(key) output type to %s for %s columns " " (when key is int or slice) and %s output other (un-fo...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, pad...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def set_transform( self, transform: Optional[Callable], columns: Optional[List] = None, output_all_columns: bool = False, ): """Set `__getitem__` return format using this transform. The transform is applied on-the-fly on batches when `__getitem__` is called. As [`~dat...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: transform (`Callable`, *optional*): User-defined formatting transform, replaces the format defined by [`~datasets.Dataset.set_format`]. A formatting function is a callable that takes a batch (as a `dict`) as input and returns a batch. This function is ap...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased') >>> def encode(batch): ... return tokenizer(batch['te...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
self.set_format("custom", columns=columns, output_all_columns=output_all_columns, transform=transform)
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def with_format( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ): """Set `__getitem__` return format (type and columns). The data formatting is applied on-the-fly. The format `type` (for ex...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: type (`str`, *optional*): Either output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, pad...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
'input_ids': tensor([ 101, 18027, 16310, 16001, 1103, 9321, 178, 11604, 7235, 6617, 1742, 2165, 2820, 1206, 6588, 22572, 12937, 1811, 2153, 1105, 1147, 12890, 19587, 6463, 1105, 15026, 1482, 119, 102, 0, 0, 0, 0, 0, 0, 0, ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def with_transform( self, transform: Optional[Callable], columns: Optional[List] = None, output_all_columns: bool = False, ): """Set `__getitem__` return format using this transform. The transform is applied on-the-fly on batches when `__getitem__` is called. As [`~d...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: transform (`Callable`, `optional`): User-defined formatting transform, replaces the format defined by [`~datasets.Dataset.set_format`]. A formatting function is a callable that takes a batch (as a `dict`) as input and returns a batch. This function is ap...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> def encode(example): ... return tokenizer(example["...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
dataset = copy.deepcopy(self) dataset.set_transform(transform=transform, columns=columns, output_all_columns=output_all_columns) return dataset
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def _getitem(self, key: Union[int, slice, str, ListLike[int]], **kwargs) -> Union[Dict, List]: """ Can be used to index columns (by string names) or rows (by integer, slice, or list-like of integer indices) """ if isinstance(key, bool): raise TypeError("dataset index must be ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
pa_subtable = query_table(self._data, key, indices=self._indices) formatted_output = format_table( pa_subtable, key, formatter=formatter, format_columns=format_columns, output_all_columns=output_all_columns ) return formatted_output
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@overload def __getitem__(self, key: Union[int, slice, Iterable[int]]) -> Dict: # noqa: F811 ... @overload def __getitem__(self, key: str) -> List: # noqa: F811 ... def __getitem__(self, key): # noqa: F811 """Can be used to index columns (by string names) or rows (by integer...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Returns: `int`: Number of removed files. Example:
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.cleanup_cache_files() 10 ``` """ current_cache_files = [os.path.abspath(cache_file["filename"]) for cache_file in self.cache_files] if not curre...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
logger.info(f"Removing {file_path}") os.remove(file_path) return len(files_to_remove)
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def _get_cache_file_path(self, fingerprint): if is_caching_enabled() and self.cache_files: cache_file_name = "cache-" + fingerprint + ".arrow" cache_directory = os.path.dirname(self.cache_files[0]["filename"]) else: cache_file_name = "cache-" + generate_random_fingerp...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@transmit_format def map( self, function: Optional[Callable] = None, with_indices: bool = False, with_rank: bool = False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, drop_last_batch: b...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Apply a function to all the examples in the table (individually or in batches) and update the table. If your function returns a column that already exists, then it overwrites it.
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
You can specify whether the function should be batched or not with the `batched` parameter: - If batched is `False`, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. `{"text": "Hello there !"}`. - If batched is `True` and `batch_size` is 1, th...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
- `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False` and `with_rank=False` - `function(example: Dict[str, Any], *extra_args) -> Dict[str, Any]` if `batched=False` and `with_indices=True` and/or `with_rank=True` (one extra arg for each) - `fu...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: `lambda x: x`. with_indices (`...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
as positional arguments. If `None`, a `dict` mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function`. batch_size (`int`, *optional*, defaults to `1000`): Number of examples per batc...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
columns with names in `remove_columns`, these columns will be kept. keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): I...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. features (`Optional[datasets.Features]`, defaults to `None`): Use a specific Features to store the cache file instead of the automatically generated one. ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
`rank=1` and `num_proc=4`, the resulting file would be `"processed_00001_of_00004.arrow"` for the default suffix. new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a ha...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> def add_prefix(example): ... example["text"] = "Review: " + example["text"] ... return example >>> ds = ds.map(add_prefix) >>> ds...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# process a batch of examples >>> ds = ds.map(lambda example: tokenizer(example["text"]), batched=True) # set number of processors >>> ds = ds.map(add_prefix, num_proc=4) ``` """ if keep_in_memory and cache_file_name is not None: raise ValueError("Please use e...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# If the array is empty we do nothing (but we make sure to handle an empty indices mapping and remove the requested columns anyway) if len(self) == 0: if self._indices is not None: # empty indices mapping self = Dataset( self.data.slice(0, 0), ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if input_columns is not None: missing_columns = set(input_columns) - set(self._data.column_names) if missing_columns: raise ValueError( f"Input column {list(missing_columns)} not in the dataset. Current columns in the dataset: {self._data.column_names}" ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if num_proc is not None and num_proc > len(self): num_proc = len(self) logger.warning( f"num_proc must be <= {len(self)}. Reducing num_proc to {num_proc} for dataset of size {len(self)}." ) dataset_kwargs = { "shard": self, "function":...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if new_fingerprint is None: # we create a unique hash from the function, # current dataset file and the mapping args transform = format_transform_for_fingerprint(Dataset._map_single) kwargs_for_fingerprint = format_kwargs_for_fingerprint(Dataset._map_single, (), dataset_k...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def load_processed_shard_from_cache(shard_kwargs): """Load a processed shard from cache if it exists, otherwise throw an error.""" shard = shard_kwargs["shard"] # Check if we've already cached this computation (indexed by a hash) if shard_kwargs["cache_file_name"] is not ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
shards_done = 0 if num_proc is None or num_proc == 1: transformed_dataset = None try: transformed_dataset = load_processed_shard_from_cache(dataset_kwargs) logger.info(f"Loading cached processed dataset at {dataset_kwargs['cache_file_name']}") ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
assert transformed_dataset is not None, "Failed to retrieve the result from map" # update fingerprint if the dataset changed if transformed_dataset._fingerprint != self._fingerprint: transformed_dataset._fingerprint = new_fingerprint return transformed_dataset ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def format_cache_file_name( cache_file_name: Optional[str], rank: Union[int, Literal["*"]], # noqa: F722 ) -> Optional[str]: if not cache_file_name: return cache_file_name sep = cache_file_name.rindex(".") b...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def format_new_fingerprint(new_fingerprint: str, rank: int) -> str: new_fingerprint = new_fingerprint + suffix_template.format(rank=rank, num_proc=num_proc) validate_fingerprint(new_fingerprint) return new_fingerprint
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
prev_env = deepcopy(os.environ) # check if parallelism if off # from https://github.com/huggingface/tokenizers/blob/bb668bc439dc34389b71dbb8ce0c597f15707b53/tokenizers/src/utils/parallelism.rs#L22 if prev_env.get("TOKENIZERS_PARALLELISM", "false").lower() not in ( "",...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
"cache_file_name": format_cache_file_name(cache_file_name, rank), "rank": rank, "offset": sum(len(s) for s in shards[:rank]), "new_fingerprint": format_new_fingerprint(new_fingerprint, rank), } for rank in range(num_shards) ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
transformed_shards = [None] * num_shards for rank in range(num_shards): try: transformed_shards[rank] = load_processed_shard_from_cache(kwargs_per_job[rank]) kwargs_per_job[rank] = None except NonExistentDatasetError: ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# We try to create a pool with as many workers as dataset not yet cached. if kwargs_per_job: if len(kwargs_per_job) < num_shards: logger.info( f"Reprocessing {len(kwargs_per_job)}/{num_shards} shards because some of them were missing from the cache...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
logger.debug(f"Finished processing shard number {rank} of {num_shards}.") transformed_shards[rank] = content else: pbar.update(content) # Avoids PermissionError on Windows (the error: https://github.com/huggingfa...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# update fingerprint if the dataset changed if any( transformed_shard._fingerprint != shard._fingerprint for transformed_shard, shard in zip(transformed_shards, shards) ): result._fingerprint = new_fingerprint else: resu...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@staticmethod def _map_single( shard: "Dataset", function: Optional[Callable] = None, with_indices: bool = False, with_rank: bool = False, input_columns: Optional[List[str]] = None, batched: bool = False, batch_size: Optional[int] = 1000, drop_last_bat...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: shard (`datasets.Dataset`): Dataset to map the transform on. function (`Callable`): with one of the following signature: - `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False` and `with_rank=False` - `function(exa...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: lambda x: x with_indices (`boo...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
batch_size (`int`, optional, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True` `batch_size <= 0` or `batch_size == None`: Provide the full dataset as a single batch to `function` drop_last_batch (`bool`, default: `False`): Whether a last batch smaller...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
cache_file_name (`str`, optional, defaults to `None`): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. writer_batch_size (`int`, default `1000`): Number of rows per write operation for t...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
new_fingerprint (`str`, optional, defaults to `None`): the new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments rank: (`int`, optional, defaults to `None`): If specified, this is the p...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# If we do batch computation but no batch size is provided, default to the full dataset if batched and (batch_size is None or batch_size <= 0): batch_size = shard.num_rows # We set this variable to True after processing the first example/batch in # `apply_function_on_filtered_inputs...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def validate_function_output(processed_inputs, indices): """Validate output of the map function.""" allowed_processed_inputs_types = (Mapping, pa.Table, pd.DataFrame) if config.POLARS_AVAILABLE and "polars" in sys.modules: import polars as pl
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
allowed_processed_inputs_types += (pl.DataFrame,) if processed_inputs is not None and not isinstance(processed_inputs, allowed_processed_inputs_types): raise TypeError( f"Provided `function` which is applied to all elements of table returns a variable of type {type(proces...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
allowed_batch_return_types += (tf.Tensor,) if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch allowed_batch_return_types += (torch.Tensor,) if config.JAX_AVAILABLE and "jax" in sys.modules: import jax.numpy as j...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def apply_function_on_filtered_inputs(pa_inputs, indices, check_same_num_examples=False, offset=0): """Utility to apply the function on a selection of columns.""" nonlocal update_data inputs = format_table( pa_inputs, 0 if not batched else range(pa_inp...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if isinstance(processed_inputs, LazyDict): processed_inputs = { k: v for k, v in processed_inputs.data.items() if k not in processed_inputs.keys_to_format } returned_lazy_dict = True else: returned_lazy_dict = False ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
updatable_types += (pl.DataFrame,) update_data = isinstance(processed_inputs, updatable_types) validate_function_output(processed_inputs, indices) if not update_data: return None # Nothing to update, let's move on if shard._format_type or input_co...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# `function` can modify input in-place causing column to be already removed. if column in inputs_to_merge: inputs_to_merge.pop(column) if returned_lazy_dict and column in processed_inputs: processed_inputs.pop(column) if...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
return {**inputs_to_merge, **processed_inputs} else: return processed_inputs
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def init_buffer_and_writer(): # Prepare output buffer and batched writer in memory or on file if we update the table writer_features = features if writer_features is None: writer_features = shard.features update_features = True else: ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
cache_dir = os.path.dirname(cache_file_name) os.makedirs(cache_dir, exist_ok=True) tmp_file = tempfile.NamedTemporaryFile("wb", dir=cache_dir, delete=False) writer = ArrowWriter( features=writer_features, path=tmp_file.name, ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py