kardwalker/my_dataset huggingface dataset:
GitHub issue #6107: Fix deprecation of use_auth_token in file_utils
State: closed | Created: 2023-07-31T16:32:01Z

Fix issues with the deprecation of `use_auth_token`  introduced by:
- #5996

in functions:
- `get_authentication_headers_for_url`
- `request_etag`
- `get_from_cache`

Currently, `TypeError` is raised: https://github.com/huggingface/datasets-server/actions/runs/5711650666/job/15484685570?pr=1588
```
FAILED tests/job_runners/config/test_parquet_and_info.py::test__is_too_big_external_files[None-None-False] - TypeError: get_authentication_headers_for_url() got an unexpected keyword argument 'use_auth_token'

FAILED tests/job_runners/config/test_parquet_and_info.py::test_fill_builder_info[None-False] - libcommon.exceptions.FileSystemError: Could not read the parquet files: get_authentication_headers_for_url() got an unexpected keyword argument 'use_auth_token'
```

Related to:
- #6094
GitHub issue #6106: load local json_file as dataset
State: closed | Created: 2023-07-31T12:53:49Z

### Describe the bug

I tried to load local json file as dataset but failed to parsing json file because some columns are 'float' type.

### Steps to reproduce the bug

1. load json file with certain columns are 'float' type. For example `data = load_data("json", data_files=JSON_PATH)`
2. Then, the error will be triggered like `ArrowInvalid: Could not convert '-0.2253' with type str: tried to convert to double

### Expected behavior

Should allow some columns are 'float' type, at least it should convert those columns to str type.
I tried to avoid the error by naively convert the float item to str:
```python
# if col type is not str, we need to convert it to str
mapping = {}
for col in keys:
    if isinstance(dataset[0][col], str):
        mapping[col] = [row.get(col) for row in dataset]
    else:
        mapping[col] = [str(row.get(col)) for row in dataset]
```

### Environment info

- `datasets` version: 2.14.2
- Platform: Linux-5.4.0-52-generic-x86_64-with-glibc2.31
- Python version: 3.9.16
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.0
- Pandas version: 2.0.1
GitHub issue #6104: HF Datasets data access is extremely slow even when in memory
State: open | Created: 2023-07-31T11:12:19Z

### Describe the bug

Doing a simple `some_dataset[:10]` can take more than a minute.

Profiling it:
<img width="1280" alt="image" src="https://github.com/huggingface/datasets/assets/36224762/e641fb95-ff02-4072-9016-5416a65f75ab">

`some_dataset` is completely in memory with no disk cache.

This is proving fatal to my usage of HF Datasets. Is there a way I can forgo the arrow format and store the dataset as PyTorch tensors so that `_tensorize` is not needed? And is `_consolidate` supposed to take this long?

It's faster to produce the dataset from scratch than to access it from HF Datasets!

### Steps to reproduce the bug

I have uploaded the dataset that causes this problem [here](https://huggingface.co/datasets/NightMachinery/hf_datasets_bug1).

```python
#!/usr/bin/env python3
import sys
import time
import torch
from datasets import load_dataset


def main(dataset_name):
    # Start the timer
    start_time = time.time()

    # Load the dataset from Hugging Face Hub
    dataset = load_dataset(dataset_name)

    # Set the dataset format as torch
    dataset.set_format(type="torch")

    # Perform an identity map
    dataset = dataset.map(lambda example: example, batched=True, batch_size=20)

    # End the timer
    end_time = time.time()

    # Print the time taken
    print(f"Time taken: {end_time - start_time:.2f} seconds")


if __name__ == "__main__":
    dataset_name = "NightMachinery/hf_datasets_bug1"
    print(f"dataset_name: {dataset_name}")
    main(dataset_name)
```

### Expected behavior

_

### Environment info

- `datasets` version: 2.13.1
- Platform: Linux-5.15.0-76-generic-x86_64-with-glibc2.35
- Python version: 3.10.12
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3
GitHub issue #6100: TypeError when loading from GCP bucket
State: closed | Created: 2023-07-30T23:03:00Z

### Describe the bug

Loading a dataset from a GCP bucket raises a type error. This bug was introduced recently (either in 2.14 or 2.14.1), and appeared during a migration from 2.13.1.

### Steps to reproduce the bug

Load any file from a GCP bucket:

```python
import datasets

datasets.load_dataset("json", data_files=["gs://..."])
```

The following exception is raised:

```python
Traceback (most recent call last):
...
packages/datasets/data_files.py", line 335, in resolve_pattern
    protocol_prefix = fs.protocol + "://" if fs.protocol != "file" else ""
TypeError: can only concatenate tuple (not "str") to tuple
```

With a `GoogleFileSystem`, the attribute `fs.protocol` is a tuple `('gs', 'gcs')` and hence cannot be concatenated with a string.


### Expected behavior

The file should be loaded without exception.

### Environment info

- `datasets` version: 2.14.1
- Platform: macOS-13.2.1-x86_64-i386-64bit
- Python version: 3.10.12
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3
GitHub issue #6099: How do i get "amazon_us_reviews
State: closed | Created: 2023-07-30T11:02:17Z

### Feature request

I have been trying to load 'amazon_us_dataset" but unable to do so. 

`amazon_us_reviews = load_dataset('amazon_us_reviews')`
`print(amazon_us_reviews)`


> [ValueError: Config name is missing.

Please pick one among the available configs: ['Wireless_v1_00', 'Watches_v1_00', 'Video_Games_v1_00', 'Video_DVD_v1_00', 'Video_v1_00', 'Toys_v1_00', 'Tools_v1_00', 'Sports_v1_00', 'Software_v1_00', 'Shoes_v1_00', 'Pet_Products_v1_00', 'Personal_Care_Appliances_v1_00', 'PC_v1_00', 'Outdoors_v1_00', 'Office_Products_v1_00', 'Musical_Instruments_v1_00', 'Music_v1_00', 'Mobile_Electronics_v1_00', 'Mobile_Apps_v1_00', 'Major_Appliances_v1_00', 'Luggage_v1_00', 'Lawn_and_Garden_v1_00', 'Kitchen_v1_00', 'Jewelry_v1_00', 'Home_Improvement_v1_00', 'Home_Entertainment_v1_00', 'Home_v1_00', 'Health_Personal_Care_v1_00', 'Grocery_v1_00', 'Gift_Card_v1_00', 'Furniture_v1_00', 'Electronics_v1_00', 'Digital_Video_Games_v1_00', 'Digital_Video_Download_v1_00', 'Digital_Software_v1_00', 'Digital_Music_Purchase_v1_00', 'Digital_Ebook_Purchase_v1_00', 'Camera_v1_00', 'Books_v1_00', 'Beauty_v1_00', 'Baby_v1_00', 'Automotive_v1_00', 'Apparel_v1_00', 'Digital_Ebook_Purchase_v1_01', 'Books_v1_01', 'Books_v1_02']
Example of usage:
	`load_dataset('amazon_us_reviews', 'Wireless_v1_00')`]

__________________________________________________________________________
`amazon_us_reviews = load_dataset('amazon_us_reviews', 'Watches_v1_00')
print(amazon_us_reviews)`

**ERROR**
`Generating` train split: 0%
0/960872 [00:00<?, ? examples/s]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/datasets/builder.py in _prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id)
   1692                         )
-> 1693                     example = self.info.features.encode_example(record) if self.info.features is not None else record
   1694                     writer.write(example, key)

11 frames
KeyError: 'marketplace'

The above exception was the direct cause of the following exception:

DatasetGenerationError                    Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/datasets/builder.py in _prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id)
   1710             if isinstance(e, SchemaInferenceError) and e.__context__ is not None:
   1711                 e = e.__context__
-> 1712             raise DatasetGenerationError("An error occurred while generating the dataset") from e
   1713 
   1714         yield job_id, True, (total_num_examples, total_num_bytes, writer._features, num_shards, shard_lengths)

DatasetGenerationError: An error occurred while generating the dataset

### Motivation

The dataset I'm using
https://huggingface.co/datasets/amazon_us_reviews

### Your contribution

What is the best way to load this data
GitHub issue #6098: Expanduser in save_to_disk()
State: closed | Created: 2023-07-29T20:50:45Z

Fixes #5651. The same problem occurs when loading from disk so I fixed it there too.

I am not sure why the case distinction between local and remote filesystems is even necessary for `DatasetDict` when saving to disk. Imo this could be removed (leaving only `fs.makedirs(dataset_dict_path, exist_ok=True)`).
GitHub issue #6097: Dataset.get_nearest_examples does not return all feature values for the k most similar datapoints - side effect of Dataset.set_format
State: closed | Created: 2023-07-28T20:31:59Z

### Describe the bug

Hi team!

I observe that there seems to be a side effect of `Dataset.set_format`: after setting a format and creating a FAISS index, the method `get_nearest_examples` from the `Dataset` class, fails to retrieve anything else but the embeddings themselves - not super useful. This is not the case if not using the `set_format` method: you can also retrieve any other feature value, such as an index/id/etc.

Are you able to reproduce what I observe?

### Steps to reproduce the bug

```python

from datasets import Dataset
import numpy as np

foo = {'vectors': np.random.random((100,1024)), 'ids': [str(u) for u in range(100)]}
foo = Dataset.from_dict(foo)
foo.set_format('numpy', ['vectors'])
foo.add_faiss_index('vectors')
new_vector = np.random.random(1024)
scores, res = foo.get_nearest_examples('vectors', new_vector, k=3)
```
This will return, for the resulting most similar vectors to `new_vector` - in particular it will not return the `ids` feature:
```
{'vectors': array([[random values ...]])}
```

### Expected behavior

The expected behavior happens when the `set_format` method is not called:
```python

from datasets import Dataset
import numpy as np

foo = {'vectors': np.random.random((100,1024)), 'ids': [str(u) for u in range(100)]}
foo = Dataset.from_dict(foo)
# foo.set_format('numpy', ['vectors'])
foo.add_faiss_index('vectors')
new_vector = np.random.random(1024)
scores, res = foo.get_nearest_examples('vectors', new_vector, k=3)
```
This *will*  return the `ids` of the similar vectors - with unfortunately a list of lists in lieu of the array I think for caching reasons - read it elsewhere
```
{'vectors': [[random values on multiple lines...]], 'ids': ['x', 'y', 'z']}
```

### Environment info

- `datasets` version: 2.12.0
- Platform: Linux-5.4.0-155-generic-x86_64-with-glibc2.31
- Python version: 3.10.6
- Huggingface_hub version: 0.15.1
- PyArrow version: 11.0.0
- Pandas version: 1.5.3
GitHub issue #6096: Add `fsspec` support for `to_json`, `to_csv`, and `to_parquet`
State: closed | Created: 2023-07-28T16:36:59Z

Hi to whoever is reading this! 🤗 (Most likely @mariosasko)

## What's in this PR?

This PR replaces the `open` from Python with `fsspec.open` and adds the argument `storage_options` for the methods `to_json`, `to_csv`, and `to_parquet`, to allow users to export any 🤗`Dataset` into a file in a file-system as requested at #6086.

## What's missing in this PR?

As per `to_json`, `to_csv`, and `to_parquet` docstrings for the recently included `storage_options` arg, I've scoped it to 2.15.0, so we should check that before merging in case we want to scope that for 2.14.2 instead.

Additionally, should we also add `fsspec` support for the `from_csv`, `from_json`, and `from_parquet` methods? If you want me to do so @mariosasko just let me know and I'll create another PR to support that too!

Fix #6086.
GitHub issue #6095: Fix deprecation of errors in TextConfig
State: closed | Created: 2023-07-28T14:08:37Z

This PR fixes an issue with the deprecation of `errors` in `TextConfig` introduced by:
- #5974

```python
In [1]: ds = load_dataset("text", data_files="test.txt", errors="strict")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-701c27131a5d> in <module>
----> 1 ds = load_dataset("text", data_files="test.txt", errors="strict")

~/huggingface/datasets/src/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, verification_mode, ignore_verifications, keep_in_memory, save_infos, revision, token, use_auth_token, task, streaming, num_proc, storage_options, **config_kwargs)
   2107 
   2108     # Create a dataset builder
-> 2109     builder_instance = load_dataset_builder(
   2110         path=path,
   2111         name=name,

~/huggingface/datasets/src/datasets/load.py in load_dataset_builder(path, name, data_dir, data_files, cache_dir, features, download_config, download_mode, revision, token, use_auth_token, storage_options, **config_kwargs)
   1830     builder_cls = get_dataset_builder_class(dataset_module, dataset_name=dataset_name)
   1831     # Instantiate the dataset builder
-> 1832     builder_instance: DatasetBuilder = builder_cls(
   1833         cache_dir=cache_dir,
   1834         dataset_name=dataset_name,

~/huggingface/datasets/src/datasets/builder.py in __init__(self, cache_dir, dataset_name, config_name, hash, base_path, info, features, token, use_auth_token, repo_id, data_files, data_dir, storage_options, writer_batch_size, name, **config_kwargs)
    371         if data_dir is not None:
    372             config_kwargs["data_dir"] = data_dir
--> 373         self.config, self.config_id = self._create_builder_config(
    374             config_name=config_name,
    375             custom_features=features,

~/huggingface/datasets/src/datasets/builder.py in _create_builder_config(self, config_name, custom_features, **config_kwargs)
    550             if "version" not in config_kwargs and hasattr(self, "VERSION") and self.VERSION:
    551                 config_kwargs["version"] = self.VERSION
--> 552             builder_config = self.BUILDER_CONFIG_CLASS(**config_kwargs)
    553 
    554         # otherwise use the config_kwargs to overwrite the attributes

TypeError: __init__() got an unexpected keyword argument 'errors'
```

Similar to:
- #6094
GitHub issue #6094: Fix deprecation of use_auth_token in DownloadConfig
State: closed | Created: 2023-07-28T11:52:21Z

This PR fixes an issue with the deprecation of `use_auth_token` in `DownloadConfig` introduced by:
- #5996

```python
In [1]: from datasets import DownloadConfig

In [2]: DownloadConfig(use_auth_token=False)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-41927b449e72> in <module>
----> 1 DownloadConfig(use_auth_token=False)

TypeError: __init__() got an unexpected keyword argument 'use_auth_token'
```

```python
In [1]: from datasets import get_dataset_config_names
In [2]: get_dataset_config_names("squad", use_auth_token=False)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-4671992ead50> in <module>
----> 1 get_dataset_config_names("squad", use_auth_token=False)

~/huggingface/datasets/src/datasets/inspect.py in get_dataset_config_names(path, revision, download_config, download_mode, dynamic_modules_path, data_files, **download_kwargs)
    349     ```
    350     """
--> 351     dataset_module = dataset_module_factory(
    352         path,
    353         revision=revision,

~/huggingface/datasets/src/datasets/load.py in dataset_module_factory(path, revision, download_config, download_mode, dynamic_modules_path, data_dir, data_files, **download_kwargs)
   1374     """
   1375     if download_config is None:
-> 1376         download_config = DownloadConfig(**download_kwargs)
   1377     download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS)
   1378     download_config.extract_compressed_file = True

TypeError: __init__() got an unexpected keyword argument 'use_auth_token'
```
GitHub issue #6093: Deprecate `download_custom`
State: closed | Created: 2023-07-28T10:49:06Z

Deprecate `DownloadManager.download_custom`. Users should use `fsspec` URLs (cacheable) or make direct requests with `fsspec`/`requests` (not cacheable) instead.

We should deprecate this method as it's not compatible with streaming, and implementing the streaming version of it is hard/impossible. There have been requests to implement the streaming version of this method on the forum, but the reason for this seems to be a tip in the docs that "promotes" this method (this PR removes it).
GitHub issue #6090: FilesIterable skips all the files after a hidden file
State: closed | Created: 2023-07-28T07:25:57Z

### Describe the bug

When initializing `FilesIterable` with a list of file paths using `FilesIterable.from_paths`, it will discard all the files after a hidden file.
The problem is in [this line](https://github.com/huggingface/datasets/blob/88896a7b28610ace95e444b94f9a4bc332cc1ee3/src/datasets/download/download_manager.py#L233C26-L233C26) where `return` should be replaced by `continue`. 

### Steps to reproduce the bug

https://colab.research.google.com/drive/1SQlxs4y_LSo1Q89KnFoYDSyyKEISun_J#scrollTo=93K4_blkW-8-

### Expected behavior

The script should print all the files except the hidden one.

### Environment info

- `datasets` version: 2.14.1
- Platform: Linux-5.15.109+-x86_64-with-glibc2.35
- Python version: 3.10.6
- Huggingface_hub version: 0.16.4
- PyArrow version: 9.0.0
- Pandas version: 1.5.3
GitHub issue #6089: AssertionError: daemonic processes are not allowed to have children
State: open | Created: 2023-07-28T06:04:00Z

### Describe the bug

When I load_dataset with num_proc > 0 in a deamon process, I got an error:

```python
  File "/Users/codingl2k1/Work/datasets/src/datasets/download/download_manager.py", line 564, in download_and_extract
    return self.extract(self.download(url_or_urls))
    ^^^^^^^^^^^^^^^^^
  File "/Users/codingl2k1/Work/datasets/src/datasets/download/download_manager.py", line 427, in download
    downloaded_path_or_paths = map_nested(
    ^^^^^^^^^^^^^^^^^
  File "/Users/codingl2k1/Work/datasets/src/datasets/utils/py_utils.py", line 468, in map_nested
    mapped = parallel_map(function, iterable, num_proc, types, disable_tqdm, desc, _single_map_nested)
    ^^^^^^^^^^^^^^^^^
  File "/Users/codingl2k1/Work/datasets/src/datasets/utils/experimental.py", line 40, in _inner_fn
    return fn(*args, **kwargs)
    ^^^^^^^^^^^^^^^^^
  File "/Users/codingl2k1/Work/datasets/src/datasets/parallel/parallel.py", line 34, in parallel_map
    return _map_with_multiprocessing_pool(
    ^^^^^^^^^^^^^^^^^
  File "/Users/codingl2k1/Work/datasets/src/datasets/parallel/parallel.py", line 64, in _map_with_multiprocessing_pool
    with Pool(num_proc, initargs=initargs, initializer=initializer) as pool:
      ^^^^^^^^^^^^^^^^^
  File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/context.py", line 119, in Pool
    return Pool(processes, initializer, initargs, maxtasksperchild,
    ^^^^^^^^^^^^^^^^^
  File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/pool.py", line 215, in __init__
    self._repopulate_pool()
    ^^^^^^^^^^^^^^^^^
  File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/pool.py", line 306, in _repopulate_pool
    return self._repopulate_pool_static(self._ctx, self.Process,
    ^^^^^^^^^^^^^^^^^
  File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/pool.py", line 329, in _repopulate_pool_static
    w.start()
  File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/process.py", line 118, in start
    assert not _current_process._config.get('daemon'),     ^^^^^^^^^^^^^^^^^
AssertionError: daemonic processes are not allowed to have children
```

The download is io-intensive computing, may be datasets can replece the multi processing pool by a multi threading pool if in a deamon process.

### Steps to reproduce the bug

1. start a deamon process
2. run load_dataset with num_proc > 0

### Expected behavior

No error.

### Environment info

Python 3.11.4
datasets latest master
GitHub issue #6088: Loading local data files initiates web requests
State: closed | Created: 2023-07-28T04:06:26Z

As documented in the [official docs](https://huggingface.co/docs/datasets/v2.14.0/en/package_reference/loading_methods#datasets.load_dataset.example-2), I tried to load datasets from local files by
```python
# Load a JSON file
from datasets import load_dataset
ds = load_dataset('json', data_files='path/to/local/my_dataset.json')
```
But this failed on a web request because I'm executing the script on a machine without Internet access. Stacktrace shows
```
in PackagedDatasetModuleFactory.__init__(self, name, data_dir, data_files, download_config, download_mode)
    940 self.download_config = download_config
    941 self.download_mode = download_mode
--> 942 increase_load_count(name, resource_type="dataset")
```
I've read from the source code that this can be fixed by setting environment variable to run in offline mode. I'm just wondering that is this an expected behaviour that even loading a LOCAL JSON file requires Internet access by default? And what's the point of requesting to `increase_load_count` on some server when loading just LOCAL data files?
GitHub issue #6087: fsspec dependency is set too low
State: closed | Created: 2023-07-27T20:08:22Z

### Describe the bug

fsspec.callbacks.TqdmCallback (used in https://github.com/huggingface/datasets/blob/73bed12ecda17d1573fd3bf73ed5db24d3622f86/src/datasets/utils/file_utils.py#L338) was first released in fsspec [2022.3.0](https://github.com/fsspec/filesystem_spec/releases/tag/2022.3.0, commit where it was added: https://github.com/fsspec/filesystem_spec/commit/9577c8a482eb0a69092913b81580942a68d66a76#diff-906155c7e926a9ff58b9f23369bb513b09b445f5b0f41fa2a84015d0b471c68cR180), however the dependency is set to 2021.11.1 https://github.com/huggingface/datasets/blob/main/setup.py#L129



### Steps to reproduce the bug

1. Install fsspec==2021.11.1
2. Install latest datasets==2.14.1
3. Import datasets, import fails due to lack of `fsspec.callbacks.TqdmCallback`

### Expected behavior

No import issue

### Environment info

N/A
GitHub issue #6086: Support `fsspec` in `Dataset.to_<format>` methods
State: closed | Created: 2023-07-27T19:08:37Z

Supporting this should be fairly easy.

Requested on the forum [here](https://discuss.huggingface.co/t/how-can-i-convert-a-loaded-dataset-in-to-a-parquet-file-and-save-it-to-the-s3/48353).
GitHub issue #6085: Fix `fsspec` download
State: open | Created: 2023-07-27T18:54:47Z

Testing `ds = load_dataset("audiofolder", data_files="s3://datasets.huggingface.co/SpeechCommands/v0.01/v0.01_test.tar.gz", storage_options={"anon": True})` and trying to fix the issues raised by `fsspec` ...

TODO: fix
```
    self.session = aiobotocore.session.AioSession(**self.kwargs)
TypeError: __init__() got an unexpected keyword argument 'hf'
```
by "preparing `storage_options`" for the `fsspec` head/get
GitHub issue #6084: Changing pixel values of images in the Winoground dataset
State: open | Created: 2023-07-27T17:55:35Z

Hi, as I followed the instructions, with lasted "datasets" version:
"
from datasets import load_dataset
examples = load_dataset('facebook/winoground', use_auth_token=<YOUR USER ACCESS TOKEN>)
"
I got slightly different datasets in colab and in my hpc environment. Specifically, the pixel values of images are slightly different. 
I thought it was due to the package version difference, but today's morning I found out that my winoground dataset in colab became the same with the one in my hpc environment. The dataset in colab can produce the correct result but now it is gone as well. 

Can you help me with this? What causes the datasets to have the wrong pixel values?
GitHub issue #6081: Deprecate `Dataset.export`
State: closed | Created: 2023-07-27T14:22:18Z

Deprecate `Dataset.export` that generates a TFRecord file from a dataset as this method is undocumented, and the usage seems low. Users should use [TFRecordWriter](https://www.tensorflow.org/api_docs/python/tf/io/TFRecordWriter#write) or the official [TFRecord](https://www.tensorflow.org/tutorials/load_data/tfrecord) tutorial (on which this method is based) to write TFRecord files instead.
GitHub issue #6079: Iterating over DataLoader based on HF datasets is stuck forever
State: closed | Created: 2023-07-26T14:52:37Z

### Describe the bug

I am using Amazon Sagemaker notebook (Amazon Linux 2) with python 3.10 based Conda environment.
I have a dataset in parquet format locally. When I try to iterate over it, the loader is stuck forever. Note that the same code is working for python 3.6 based conda environment seamlessly. What should be my next steps here?

### Steps to reproduce the bug

```
train_dataset = load_dataset(
    "parquet", data_files = {'train': tr_data_path + '*.parquet'}, 
    split = 'train', 
    collate_fn = streaming_data_collate_fn,
    streaming = True
).with_format('torch')

train_dataloader = DataLoader(train_dataset, batch_size = 2, num_workers = 0)

t = time.time()
iter_ = 0
for batch in train_dataloader:
    iter_ += 1
    
    if iter_ == 1000:
        break
        
print (time.time() - t) 
```

### Expected behavior

The snippet should work normally and load the next batch of data.

### Environment info

datasets: '2.14.0'
pyarrow: '12.0.0'
torch: '2.0.0'
Python: 3.10.10 | packaged by conda-forge | (main, Mar 24 2023, 20:08:06) [GCC 11.3.0]

!uname -r
5.10.178-162.673.amzn2.x86_64
GitHub issue #6078: resume_download with streaming=True
State: closed | Created: 2023-07-26T14:08:22Z

### Describe the bug

I used:
```
dataset = load_dataset(
    "oscar-corpus/OSCAR-2201",
    token=True,
    language="fr",
    streaming=True,
    split="train"
)
```
Unfortunately, the server had a problem during the training process. I saved the step my training stopped at.
But how can I resume download from step 1_000_´000 without re-streaming all the first 1 million docs of the dataset?

`download_config=DownloadConfig(resume_download=True)` seems to not work with streaming=True.

### Steps to reproduce the bug

```
from datasets import load_dataset, DownloadConfig
dataset = load_dataset(
    "oscar-corpus/OSCAR-2201",
    token=True,
    language="fr",
    streaming=True,  # optional
    split="train",
    download_config=DownloadConfig(resume_download=True)
)
# interupt the run and try to relaunch it => this restart from scratch
```

### Expected behavior

I would expect a parameter to start streaming from a given index in the dataset.

### Environment info

- `datasets` version: 2.14.0
- Platform: Linux-5.19.0-45-generic-x86_64-with-glibc2.29
- Python version: 3.8.10
- Huggingface_hub version: 0.15.1
- PyArrow version: 12.0.1
- Pandas version: 2.0.0
GitHub issue #6076: No gzip encoding from github
State: closed | Created: 2023-07-26T12:46:07Z

Don't accept gzip encoding from github, otherwise some files are not streamable + seekable.

fix https://huggingface.co/datasets/code_x_glue_cc_code_to_code_trans/discussions/2#64c0e0c1a04a514ba6303e84

and making sure https://github.com/huggingface/datasets/issues/2918 works as well
GitHub issue #6074: Misc doc improvements
State: closed | Created: 2023-07-26T12:20:54Z

Removes the warning about requiring to write a dataset loading script to define multiple configurations, as the README YAML can be used instead (for simple cases). Also, deletes the section about using the `BatchSampler` in `torch<=1.12.1` to speed up loading, as `torch 1.12.1` is over a year old (and `torch 2.0` has been out for a while).
GitHub issue #6071: storage_options provided to load_dataset not fully piping through since datasets 2.14.0
State: closed | Created: 2023-07-26T09:37:20Z

### Describe the bug

Since the latest release of `datasets` (`2.14.0`), custom filesystem `storage_options` passed to `load_dataset()` do not seem to propagate through all the way - leading to problems if loading data files that need those options to be set.

I think this is because of the new `_prepare_path_and_storage_options()` (https://github.com/huggingface/datasets/pull/6028), which returns the right `storage_options` to use given a path and a `DownloadConfig` - but which might not be taking into account the extra `storage_options` explicitly provided e.g. through `load_dataset()`

### Steps to reproduce the bug

```python
import fsspec

import pandas as pd
import datasets

# Generate mock parquet file
data_files = "demo.parquet"
pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}).to_parquet(data_files)

_storage_options = {"x": 1, "y": 2}
fs = fsspec.filesystem("file", **_storage_options)

dataset = datasets.load_dataset(
    "parquet",
    data_files=data_files,
    storage_options=fs.storage_options
)
```

Looking at the `storage_options` resolved here:

https://github.com/huggingface/datasets/blob/b0177910b32712f28d147879395e511207e39958/src/datasets/data_files.py#L331

 they end up being `{}`, instead of propagating through the `storage_options` that were provided to `load_dataset` (`fs.storage_options`). As these then get used for the filesystem operation a few lines below

https://github.com/huggingface/datasets/blob/b0177910b32712f28d147879395e511207e39958/src/datasets/data_files.py#L339

the call will fail if the user-provided `storage_options` were needed.

---

A temporary workaround that seemed to work locally to bypass the problem was to bundle a duplicate of the `storage_options` into the `download_config`, so that they make their way all the way to `_prepare_path_and_storage_options()` and get extracted correctly:

```python
dataset = datasets.load_dataset(
        "parquet",
        data_files=data_files,
        storage_options=fs.storage_options,
        download_config=datasets.DownloadConfig(storage_options={fs.protocol: fs.storage_options}),
    )
```

### Expected behavior

`storage_options` provided to `load_dataset` take effect in all backend filesystem operations.

### Environment info

datasets==2.14.0
GitHub issue #6069: KeyError: dataset has no key "image"
State: closed | Created: 2023-07-25T17:45:50Z

### Describe the bug

I've loaded a local image dataset with:
`ds = laod_dataset("imagefolder", data_dir=path-to-data)`

And defined a transform to process the data, following the Datasets docs.

However, I get a keyError error, indicating there's no "image" key in my dataset. When I printed out the example_batch sent to the transformation function, it shows only the labels are being sent to the function.
For some reason, the images are not in the example batches.

### Steps to reproduce the bug

I'm using the latest stable version of datasets 

### Expected behavior

I expect the example_batches to contain both images and labels

### Environment info

I'm using the latest stable version of datasets
GitHub issue #6065: Add column type guessing from map return function
State: closed | Created: 2023-07-25T00:34:17Z

As discussed [here](https://github.com/huggingface/datasets/issues/5965), there are some cases where datasets is unable to automatically promote columns during mapping. The fix is to explicitly provide a `features` definition so pyarrow can configure itself with the right column types from the outset.

This PR provides an alternative approach, which is functionally equivalent to specifying features but a bit cleaner within a larger mapping pipeline. It allows clients to typehint the return variable coming from the mapper function - if we find one of these type annotations specified, and no explicit features have been passed in, we'll try to convert it into a Features map. If the map function runs and casting is unable to succeed, it will raise a DatasetTransformationNotAllowedError that indicates the typehint may be to blame. It works for batched and non-batched mapping functions.

Currently supported column types:
- builtins primitives: string, int, float, bool
- dictionaries, lists (nested and one-deep)
- Optional types and None-Unions (synonymous with optional types)

It's used like:

```python
class DatasetTyped(TypedDict):
  texts: list[str]

def dataset_typed_map(batch) -> DatasetTyped:
  return {"texts": [text.split() for text in batch["raw_text"]]}

dataset = {"raw_text": ["", "This is a test", "This is another test"]}

with Dataset.from_dict(dataset) as dset:
  new_dataset = dset.map(
    dataset_typed_map,
    batched=True,
    batch_size=1,
    num_proc=1,
)
```

Open questions:
- Should logging indicate we have automatically guessed these types? Or proceed quietly until we hit an error (as is the current implementation).
GitHub issue #6060: Dataset.map() execute twice when in PyTorch DDP mode
State: closed | Created: 2023-07-22T05:06:43Z

### Describe the bug

I use `torchrun --standalone --nproc_per_node=2 train.py` to start training. And write the code following the [docs](https://huggingface.co/docs/datasets/process#distributed-usage). The trick about using `torch.distributed.barrier()` to only execute map at the main process doesn't always work. When I am training model, it will map twice. When I am running a test for dataset and dataloader (just print the batches), it can work. Their code about loading dataset are same.

And on another server with 30 CPU cores, I use 2 GPUs and it can't work neither. 

I have tried to use `rank` and `local_rank` to check, they all didn't make sense.

### Steps to reproduce the bug

use `torchrun --standalone --nproc_per_node=2 train.py` or `torchrun --standalone train.py` to run

This is my code:

```python
            if args.distributed and world_size > 1:
                if args.local_rank > 0:
                    print(f"Rank {args.rank}: Gpu {args.gpu} waiting for main process to perform the mapping", force=True)
                    torch.distributed.barrier()
                print("Mapping dataset")
                dataset = dataset.map(lambda x: cut_reorder_keys(x, num_stations_list=args.num_stations_list, is_pad=True, is_train=True), num_proc=8, desc="cut_reorder_keys")
                dataset = dataset.map(lambda x: random_shift(x, shift_range=(-160, 0), feature_scale=16), num_proc=8, desc="random_shift")
                dataset_test = dataset_test.map(lambda x: cut_reorder_keys(x, num_stations_list=args.num_stations_list, is_pad=True, is_train=False), num_proc=8, desc="cut_reorder_keys")
                if args.local_rank == 0:
                    print("Mapping finished, loading results from main process")
                    torch.distributed.barrier()
```


### Expected behavior

Only the main process will execute `map`, while the sub process will load cache from disk.

### Environment info

server with 64 CPU cores (AMD Ryzen Threadripper PRO 5995WX 64-Cores) and 2 RTX 4090

- `python==3.9.16`
- `datasets==2.13.1`
- `torch==2.0.1+cu117`
- `22.04.1-Ubuntu`

server with 30 CPU cores (Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz) and 2 RTX 4090

- `python==3.9.0`
- `datasets==2.13.1`
- `torch==2.0.1+cu117`
- `Ubuntu 20.04`
GitHub issue #6059: Provide ability to load label mappings from file
State: open | Created: 2023-07-22T02:04:19Z

### Feature request


My task is classification of a dataset containing a large label set that includes a hierarchy. Even ignoring the hierarchy I'm not able to find an example using `datasets` where the label names aren't hard-coded. This works find for classification of a handful of labels but ideally there would be a way of loading the name/id mappings required for `datasets.features.ClassLabel` from a file.

It is possible to pass a file to ClassLabel but I cannot see an easy way of using this with `GeneratorBasedBuilder` since `self._info` is called before the `dl_manager` is constructed so even if my dataset contains say `label_mappings.json` there's no way of loading it in order to construct the `datasets.DatasetInfo`

I can see other uses to accessing the `download_manager` from `self._info` - i.e. if the files contain a schema (i.e. `arrow` or `parquet` files) the `datasets.DatasetInfo` could be inferred.

The workaround that was suggested in the forum is to generate a `.py` file from the `label_mappings.json` and import it.

```
class TestDatasetBuilder(datasets.GeneratorBasedBuilder):
    VERSION = datasets.Version("1.0.0")

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "text": datasets.Value("string"),
                    "label": datasets.features.ClassLabel(names=["label_1", "label_2"]),
                }
            ),
            task_templates=[TextClassification(text_column="text", label_column="label")],
        )

    def _split_generators(self, dl_manager):
        train_path = dl_manager.download_and_extract(_TRAIN_DOWNLOAD_URL)
        test_path = dl_manager.download_and_extract(_TEST_DOWNLOAD_URL)
        return [
            datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": train_path}),
            datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": test_path}),
        ]

    def _generate_examples(self, filepath):
        """Generate AG News examples."""
        with open(filepath, encoding="utf-8") as csv_file:
            csv_reader = csv.DictReader(csv_file)
            for id_, row in enumerate(csv_reader):
                yield id_, row
```

### Motivation

Allow `datasets.DatasetInfo` to be generated based on the contents of the dataset. 

### Your contribution

I'm willing to work on a PR with guidence.
GitHub issue #6057: Why is the speed difference of gen example so big?
State: closed | Created: 2023-07-21T03:34:49Z

```python
def _generate_examples(self, metadata_path, images_dir, conditioning_images_dir):
        with open(metadata_path, 'r') as file:
            metadata = json.load(file)

        for idx, item in enumerate(metadata):
            image_path = item.get('image_path')
            text_content = item.get('text_content')
            image_data = open(image_path, "rb").read()
            yield idx, {
                "text": text_content,
                "image": {
                    "path": image_path,
                    "bytes": image_data,
                },
                "conditioning_image": {
                    "path": image_path,
                    "bytes": image_data,
                },
            }
```
Hello, 

I use the above function to deal with my local data set, but I am very surprised that the speed at which I generate example is very different. When I start a training task, **sometimes 1000examples/s, sometimes only 10examples/s.**

![image](https://github.com/huggingface/datasets/assets/46072190/cdc17661-8267-4fd8-b30c-b74d505efd9b)

I'm not saying that speed is changing all the time. I mean, the reading speed is different in different training, which will cause me to start training over and over again until the speed of this generation of examples is normal.
GitHub issue #6056: Implement proper checkpointing for dataset uploading with resume function that does not require remapping shards that have already been uploaded
State: open | Created: 2023-07-21T03:13:21Z

Context: issue #5990

In order to implement the checkpointing, I introduce a metadata folder that keeps one yaml file for each set that one is uploading. This yaml keeps track of what shards have already been uploaded, and which one the idx of the latest one was. Using this information I am then able to easily get the push_to_hub function to retrieve on demand past history of uploads and continue mapping and uploading from where it was left off.
GitHub issue #6055: Fix host URL in The Pile datasets 
State: open | Created: 2023-07-20T09:08:52Z

### Describe the bug

In  #3627 and  #5543, you tried to fix the host URL in The Pile datasets. But both URLs are not working now:

`HTTPError: 404 Client Error: Not Found for URL: https://the-eye.eu/public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst`
And
`ConnectTimeout: HTTPSConnectionPool(host='mystic.the-eye.eu', port=443): Max retries exceeded with url: /public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst (Caused by ConnectTimeoutError(, 'Connection to mystic.the-eye.eu timed out. (connect timeout=10.0)'))`

### Steps to reproduce the bug

```
from datasets import load_dataset

# This takes a few minutes to run, so go grab a tea or coffee while you wait :)
data_files = "https://mystic.the-eye.eu/public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst"
pubmed_dataset = load_dataset("json", data_files=data_files, split="train")
pubmed_dataset
```

Result:
`ConnectTimeout: HTTPSConnectionPool(host='mystic.the-eye.eu', port=443): Max retries exceeded with url: /public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst (Caused by ConnectTimeoutError(, 'Connection to mystic.the-eye.eu timed out. (connect timeout=10.0)'))`

And

```
from datasets import load_dataset

# This takes a few minutes to run, so go grab a tea or coffee while you wait :)
data_files = "https://the-eye.eu/public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst"
pubmed_dataset = load_dataset("json", data_files=data_files, split="train")
pubmed_dataset
```

Result:
`HTTPError: 404 Client Error: Not Found for URL: https://the-eye.eu/public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst`

### Expected behavior

Downloading as normal.

### Environment info

Environment info

    `datasets` version: 2.9.0
    Platform: Windows
    Python version: 3.9.13
GitHub issue #6054: Multi-processed `Dataset.map` slows down a lot when `import torch`
State: closed | Created: 2023-07-20T06:36:14Z

### Describe the bug

When using `Dataset.map` with `num_proc > 1`, the speed slows down much if I add `import torch` to the start of the script even though I don't use it.

I'm not sure if it's `torch` only or if any other package that is "large" will also cause the same result.
BTW, `import lightning` also slows it down.

Below are the progress bars of `Dataset.map`, the only difference between them is with or without `import torch`, but the speed varies by 6-7 times.

- without `import torch` ![image](https://github.com/huggingface/datasets/assets/47121592/0233055a-ced4-424a-9f0f-32a2afd802c2)
- with `import torch` ![image](https://github.com/huggingface/datasets/assets/47121592/463eafb7-b81e-4eb9-91ca-fd7fe20f3d59)


### Steps to reproduce the bug

Below is the code I used, but I don't think the dataset and the mapping function have much to do with the phenomenon.

```python3
from datasets import load_from_disk, disable_caching
from transformers import AutoTokenizer
# import torch
# import lightning

def rearrange_datapoints(
    batch,
    tokenizer,
    sequence_length,
):
    datapoints = []
    
    input_ids = []
    for x in batch['input_ids']:
        input_ids += x
        while len(input_ids) >= sequence_length:
            datapoint = input_ids[:sequence_length]
            datapoints.append(datapoint)
            input_ids[:sequence_length] = []

    if input_ids:
        paddings = [-1] * (sequence_length - len(input_ids))
        datapoint = paddings + input_ids if tokenizer.padding_side == 'left' else input_ids + paddings
        datapoints.append(datapoint)
    
    batch['input_ids'] = datapoints
    return batch


if __name__ == '__main__':
    disable_caching()

    tokenizer = AutoTokenizer.from_pretrained('...', use_fast=False)
    dataset = load_from_disk('...')
    
    dataset = dataset.map(
        rearrange_datapoints,
        fn_kwargs=dict(
            tokenizer=tokenizer,
            sequence_length=2048,
        ),
        batched=True,
        num_proc=8,
    )

```

### Expected behavior

The multi-processed `Dataset.map` function speed between with and without `import torch` should be the same.

### Environment info

- `datasets` version: 2.13.1
- Platform: Linux-3.10.0-1127.el7.x86_64-x86_64-with-glibc2.31
- Python version: 3.10.11
- Huggingface_hub version: 0.14.1
- PyArrow version: 12.0.0
- Pandas version: 2.0.1
GitHub issue #6053: Change package name from "datasets" to something less generic
State: closed | Created: 2023-07-19T19:53:28Z

### Feature request

I'm repeatedly finding myself in situations where I want to have a package called `datasets.py` or `evaluate.py` in my code and can't because those names are being taken up by Huggingface packages. While I can understand how (even from the user's perspective) it's aesthetically pleasing to have nice terse library names, ultimately a library hogging simple names like this is something I find short-sighted, impractical and at my most irritable, frankly rude.

My preference would be a pattern like what you get with all the other big libraries like numpy or pandas:

```
import huggingface as hf
# hf.transformers, hf.datasets, hf.evaluate
```

or things like

```
import huggingface.transformers as tf
# tf.load_model(), etc
```

If this isn't possible for some technical reason, at least just call the packages something like `hf_transformers` and so on.

I realize this is a very big change that's probably been discussed internally already, but I'm making this issue and sister issues on each huggingface project just to start the conversation and begin tracking community feeling on the matter, since I suspect I'm not the only one who feels like this.

Sorry if this has been requested already on this issue tracker, I couldn't find anything looking for terms like "package name".

Sister issues:
- [transformers](https://github.com/huggingface/transformers/issues/24934)
- **datasets**
- [evaluate](https://github.com/huggingface/evaluate/issues/476)

### Motivation

Not taking up package names the user is likely to want to use.

### Your contribution

No - more a matter of internal discussion among core library authors.
GitHub issue #6051: Skipping shard in the remote repo and resume upload
State: closed | Created: 2023-07-19T09:25:26Z

### Describe the bug

For some reason when I try to resume the upload of my dataset, it is very slow to reach the index of the shard from which to resume the uploading.

From my understanding, the problem is in this part of the code:

arrow_dataset.py
```python
for index, shard in logging.tqdm(
            enumerate(itertools.chain([first_shard], shards_iter)),
            desc="Pushing dataset shards to the dataset hub",
            total=num_shards,
            disable=not logging.is_progress_bar_enabled(),
        ):
            shard_path_in_repo = path_in_repo(index, shard)
            # Upload a shard only if it doesn't already exist in the repository
            if shard_path_in_repo not in data_files:
```

In particular, iterating the generator is slow during the call:
```python
self._select_contiguous(start, length, new_fingerprint=new_fingerprint)
```

I wonder if it is possible to avoid calling this function for shards that are already uploaded and just start from the correct shard index.

### Steps to reproduce the bug

1. Start the upload
```python
dataset = load_dataset("imagefolder", data_dir=DATA_DIR, split="train", drop_labels=True)    
dataset.push_to_hub("repo/name")
```
2. Stop and restart the upload after hundreds of shards

### Expected behavior

Skip the uploaded shards faster.

### Environment info

- `datasets` version: 2.5.1
- Platform: Linux-4.18.0-193.el8.x86_64-x86_64-with-glibc2.17
- Python version: 3.8.16
- PyArrow version: 12.0.1
- Pandas version: 2.0.2