jamesLeeeeeee/datasets-github-issues huggingface dataset:
HF Datasets data access is extremely slow even when in memory
Author: NightMachinery | Pull request: no | State: open

### 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
TypeError when loading from GCP bucket
Author: bilelomrani1 | Pull request: no | State: closed

### 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
How do i get "amazon_us_reviews
Author: IqraBaluch | Pull request: no | State: closed

### 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
Expanduser in save_to_disk()
Author: Unknown3141592 | Pull request: yes | State: closed

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)`).
Dataset.get_nearest_examples does not return all feature values for the k most similar datapoints - side effect of Dataset.set_format
Author: aschoenauer-sebag | Pull request: no | State: closed

### 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
Add `fsspec` support for `to_json`, `to_csv`, and `to_parquet`
Author: alvarobartt | Pull request: yes | State: open

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 deprecation of errors in TextConfig
Author: albertvillanova | Pull request: yes | State: closed

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
Fix deprecation of use_auth_token in DownloadConfig
Author: albertvillanova | Pull request: yes | State: closed

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'
```
Deprecate `download_custom`
Author: mariosasko | Pull request: yes | State: closed

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).
FilesIterable skips all the files after a hidden file
Author: dkrivosic | Pull request: no | State: closed

### 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
AssertionError: daemonic processes are not allowed to have children
Author: codingl2k1 | Pull request: no | State: open

### 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
Loading local data files initiates web requests
Author: lytning98 | Pull request: no | State: closed

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?
fsspec dependency is set too low
Author: iXce | Pull request: no | State: closed

### 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
Support `fsspec` in `Dataset.to_<format>` methods
Author: mariosasko | Pull request: no | State: open

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).
Fix `fsspec` download
Author: mariosasko | Pull request: yes | State: open

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
Changing pixel values of images in the Winoground dataset
Author: ZitengWangNYU | Pull request: no | State: open

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?
Deprecate `Dataset.export`
Author: mariosasko | Pull request: yes | State: closed

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.
Iterating over DataLoader based on HF datasets is stuck forever
Author: arindamsarkar93 | Pull request: no | State: closed

### 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