html_url
stringlengths
48
51
title
stringlengths
5
280
comments
stringlengths
63
51.8k
body
stringlengths
0
36.2k
βŒ€
comment_length
int64
16
1.52k
text
stringlengths
163
54.1k
https://github.com/huggingface/datasets/issues/6058
laion-coco download error
This can also mean one of the files was not downloaded correctly. We log an erroneous file's name before raising the reader's error, so this is how you can find the problematic file. Then, you should delete it and call `load_dataset` again. (I checked all the uploaded files, and they seem to be valid Parquet files, so I don't think this is a bug on their side)
### Describe the bug The full trace: ``` /home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/load.py:1744: FutureWarning: 'ignore_verifications' was de precated in favor of 'verification_mode' in version 2.9.1 and will be removed in 3.0.0. You can remove this warning by passing 'verification_mode=no_checks' instead. warnings.warn( Downloading and preparing dataset parquet/laion--laion-coco to /home/bian/.cache/huggingface/datasets/laion___parquet/laion-- laion-coco-cb4205d7f1863066/0.0.0/bcacc8bdaa0614a5d73d0344c813275e590940c6ea8bc569da462847103a1afd... Downloading data: 100%|β–ˆ| 1.89G/1.89G [04:57<00:00, Downloading data files: 100%|β–ˆ| 1/1 [04:59<00:00, 2 Extracting data files: 100%|β–ˆ| 1/1 [00:00<00:00, 13 Generating train split: 0 examples [00:00, ? examples/s]<_io.BufferedReader name='/home/bian/.cache/huggingface/datasets/downlo ads/26d7a016d25bbd9443115cfa3092136e8eb2f1f5bcd4154 0cb9234572927f04c'> Traceback (most recent call last): File "/home/bian/data/ZOC/download_laion_coco.py", line 4, in <module> dataset = load_dataset("laion/laion-coco", ignore_verifications=True) File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/load.py", line 1791, in load_dataset builder_instance.download_and_prepare( File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/builder.py", line 891, in download_and_prepare self._download_and_prepare( File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/builder.py", line 986, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/builder.py", line 1748, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/builder.py", line 1842, in _prepare_split_single generator = self._generate_tables(**gen_kwargs) File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/packaged_modules/parquet/parquet.py", line 67, in _generate_tables parquet_file = pq.ParquetFile(f) File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/pyarrow/parquet/core.py", line 323, in __init__ self.reader.open( File "pyarrow/_parquet.pyx", line 1227, in pyarrow._parquet.ParquetReader.open File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status pyarrow.lib.ArrowInvalid: Parquet magic bytes not found in footer. Either the file is corrupted or this is not a parquet file . ``` I have carefully followed the instructions in #5264 but still get the same error. Other helpful information: ``` ds = load_dataset("parquet", data_files= ...: "https://huggingface.co/datasets/laion/l ...: aion-coco/resolve/d22869de3ccd39dfec1507 ...: f7ded32e4a518dad24/part-00000-2256f782-1 ...: 26f-4dc6-b9c6-e6757637749d-c000.snappy.p ...: arquet") Found cached dataset parquet (/home/bian/.cache/huggingface/datasets/parquet/default-a02eea00aeb08b0e/0.0.0/bb8ccf89d9ee38581ff5e51506d721a9b37f14df8090dc9b2d8fb4a40957833f) 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 4.55it/s] ``` ### Steps to reproduce the bug ``` from datasets import load_dataset dataset = load_dataset("laion/laion-coco", ignore_verifications=True/False) ``` ### Expected behavior Properly load Laion-coco dataset ### Environment info datasets==2.11.0 torch==1.12.1 python 3.10
67
laion-coco download error ### Describe the bug The full trace: ``` /home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/load.py:1744: FutureWarning: 'ignore_verifications' was de precated in favor of 'verification_mode' in version 2.9.1 and will be removed in 3.0.0. You can remove this warning by passing 'verification_mode=no_checks' instead. warnings.warn( Downloading and preparing dataset parquet/laion--laion-coco to /home/bian/.cache/huggingface/datasets/laion___parquet/laion-- laion-coco-cb4205d7f1863066/0.0.0/bcacc8bdaa0614a5d73d0344c813275e590940c6ea8bc569da462847103a1afd... Downloading data: 100%|β–ˆ| 1.89G/1.89G [04:57<00:00, Downloading data files: 100%|β–ˆ| 1/1 [04:59<00:00, 2 Extracting data files: 100%|β–ˆ| 1/1 [00:00<00:00, 13 Generating train split: 0 examples [00:00, ? examples/s]<_io.BufferedReader name='/home/bian/.cache/huggingface/datasets/downlo ads/26d7a016d25bbd9443115cfa3092136e8eb2f1f5bcd4154 0cb9234572927f04c'> Traceback (most recent call last): File "/home/bian/data/ZOC/download_laion_coco.py", line 4, in <module> dataset = load_dataset("laion/laion-coco", ignore_verifications=True) File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/load.py", line 1791, in load_dataset builder_instance.download_and_prepare( File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/builder.py", line 891, in download_and_prepare self._download_and_prepare( File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/builder.py", line 986, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/builder.py", line 1748, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/builder.py", line 1842, in _prepare_split_single generator = self._generate_tables(**gen_kwargs) File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/datasets/packaged_modules/parquet/parquet.py", line 67, in _generate_tables parquet_file = pq.ParquetFile(f) File "/home/bian/anaconda3/envs/sd/lib/python3.10/site-packages/pyarrow/parquet/core.py", line 323, in __init__ self.reader.open( File "pyarrow/_parquet.pyx", line 1227, in pyarrow._parquet.ParquetReader.open File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status pyarrow.lib.ArrowInvalid: Parquet magic bytes not found in footer. Either the file is corrupted or this is not a parquet file . ``` I have carefully followed the instructions in #5264 but still get the same error. Other helpful information: ``` ds = load_dataset("parquet", data_files= ...: "https://huggingface.co/datasets/laion/l ...: aion-coco/resolve/d22869de3ccd39dfec1507 ...: f7ded32e4a518dad24/part-00000-2256f782-1 ...: 26f-4dc6-b9c6-e6757637749d-c000.snappy.p ...: arquet") Found cached dataset parquet (/home/bian/.cache/huggingface/datasets/parquet/default-a02eea00aeb08b0e/0.0.0/bb8ccf89d9ee38581ff5e51506d721a9b37f14df8090dc9b2d8fb4a40957833f) 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 4.55it/s] ``` ### Steps to reproduce the bug ``` from datasets import load_dataset dataset = load_dataset("laion/laion-coco", ignore_verifications=True/False) ``` ### Expected behavior Properly load Laion-coco dataset ### Environment info datasets==2.11.0 torch==1.12.1 python 3.10 This can also mean one of the files was not downloaded correctly. We log an erroneous file's name before raising the reader's error, so this is how you can find the problematic file. Then, you should delete it and call `load_dataset` again. (I checked all the uploaded files, and they seem to be valid Parquet files, so I don't think this is a bug on their side)
https://github.com/huggingface/datasets/issues/6057
Why is the speed difference of gen example so big?
Hi! It's hard to explain this behavior without more information. Can you profile the slower version with the following code ```python import cProfile, pstats from datasets import load_dataset with cProfile.Profile() as profiler: ds = load_dataset(...) stats = pstats.Stats(profiler).sort_stats("cumtime") stats.print_stats() ``` and share the output?
```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.
44
Why is the speed difference of gen example so big? ```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. Hi! It's hard to explain this behavior without more information. Can you profile the slower version with the following code ```python import cProfile, pstats from datasets import load_dataset with cProfile.Profile() as profiler: ds = load_dataset(...) stats = pstats.Stats(profiler).sort_stats("cumtime") stats.print_stats() ``` and share the output?
https://github.com/huggingface/datasets/issues/6051
Skipping shard in the remote repo and resume upload
Hi! `_select_contiguous` fetches a (zero-copy) slice of the dataset's Arrow table to build a shard, so I don't think this part is the problem. To me, the issue seems to be the step where we embed external image files' bytes (a lot of file reads). You can use `.map` with multiprocessing to perform this step before `push_to_hub` in a faster manner and cache it to disk: ```python from datasets.table import embed_table_storage # load_dataset(...) format = dataset.format dataset = dataset.with_format("arrow") dataset = dataset.map(embed_table_storage, batched=True) dataset = dataset.with_format(**format) # push_to_hub(...) ``` (In Datasets 3.0, these external bytes will be written to an Arrow file when generating a dataset to avoid this "embed" step)
### 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
111
Skipping shard in the remote repo and resume upload ### 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 Hi! `_select_contiguous` fetches a (zero-copy) slice of the dataset's Arrow table to build a shard, so I don't think this part is the problem. To me, the issue seems to be the step where we embed external image files' bytes (a lot of file reads). You can use `.map` with multiprocessing to perform this step before `push_to_hub` in a faster manner and cache it to disk: ```python from datasets.table import embed_table_storage # load_dataset(...) format = dataset.format dataset = dataset.with_format("arrow") dataset = dataset.map(embed_table_storage, batched=True) dataset = dataset.with_format(**format) # push_to_hub(...) ``` (In Datasets 3.0, these external bytes will be written to an Arrow file when generating a dataset to avoid this "embed" step)
https://github.com/huggingface/datasets/issues/6051
Skipping shard in the remote repo and resume upload
Hi, thanks, this solution saves some time. But can't we avoid embedding all external image files bytes with each push, skipping the images that have already been pushed into the repo? Edit: Ok I missed the part of cache it manually on the disk the first time, this solves the problem. Thank you
### 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
53
Skipping shard in the remote repo and resume upload ### 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 Hi, thanks, this solution saves some time. But can't we avoid embedding all external image files bytes with each push, skipping the images that have already been pushed into the repo? Edit: Ok I missed the part of cache it manually on the disk the first time, this solves the problem. Thank you
https://github.com/huggingface/datasets/issues/6048
when i use datasets.load_dataset, i encounter the http connect error!
The `audiofolder` loader is not available in version `2.3.2`, hence the error. Please run the `pip install -U datasets` command to update the `datasets` installation to make `load_dataset("audiofolder", ...)` work.
### Describe the bug `common_voice_test = load_dataset("audiofolder", data_dir="./dataset/",cache_dir="./cache",split=datasets.Split.TEST)` when i run the code above, i got the error as below: -------------------------------------------- ConnectionError: Couldn't reach https://raw.githubusercontent.com/huggingface/datasets/2.3.2/datasets/audiofolder/audiofolder.py (ConnectionError(MaxRetryError("HTTPSConnectionPool(host='raw.githubusercontent.com', port=443): Max retries exceeded with url: /huggingface/datasets/2.3.2/datasets/audiofolder/audiofolder.py (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f299ed082e0>: Failed to establish a new connection: [Errno 101] Network is unreachable'))"))) -------------------------------------------------- My all data is on local machine, why does it need to connect the internet? how can i fix it, because my machine cannot connect the internet. ### Steps to reproduce the bug 1 ### Expected behavior no error when i use the load_dataset func ### Environment info python=3.8.15
30
when i use datasets.load_dataset, i encounter the http connect error! ### Describe the bug `common_voice_test = load_dataset("audiofolder", data_dir="./dataset/",cache_dir="./cache",split=datasets.Split.TEST)` when i run the code above, i got the error as below: -------------------------------------------- ConnectionError: Couldn't reach https://raw.githubusercontent.com/huggingface/datasets/2.3.2/datasets/audiofolder/audiofolder.py (ConnectionError(MaxRetryError("HTTPSConnectionPool(host='raw.githubusercontent.com', port=443): Max retries exceeded with url: /huggingface/datasets/2.3.2/datasets/audiofolder/audiofolder.py (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f299ed082e0>: Failed to establish a new connection: [Errno 101] Network is unreachable'))"))) -------------------------------------------------- My all data is on local machine, why does it need to connect the internet? how can i fix it, because my machine cannot connect the internet. ### Steps to reproduce the bug 1 ### Expected behavior no error when i use the load_dataset func ### Environment info python=3.8.15 The `audiofolder` loader is not available in version `2.3.2`, hence the error. Please run the `pip install -U datasets` command to update the `datasets` installation to make `load_dataset("audiofolder", ...)` work.
https://github.com/huggingface/datasets/issues/6043
Compression kwargs have no effect when saving datasets as csv
Hello @exs-avianello, I have reproduced the bug successfully and have understood the problem. But I am confused regarding this part of the statement, "`pandas.DataFrame.to_csv` is always called with a buf-like `path_or_buf`". Can you please elaborate on it? Thanks!
### Describe the bug Attempting to save a dataset as a compressed csv file, the compression kwargs provided to `.to_csv()` that get piped to panda's `pandas.DataFrame.to_csv` do not have any effect - resulting in the dataset not getting compressed. A warning is raised if explicitly providing a `compression` kwarg, but no warnings are raised if relying on the defaults. This can lead to datasets secretly not getting compressed for users expecting the behaviour to match panda's `.to_csv()`, where the compression format is automatically inferred from the destination path suffix. ### Steps to reproduce the bug ```python # dataset is not compressed (but at least a warning is emitted) import datasets dataset = datasets.load_dataset("rotten_tomatoes", split="train") dataset.to_csv("uncompressed.csv") print(os.path.getsize("uncompressed.csv")) # 1008607 dataset.to_csv("compressed.csv.gz", compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}) print(os.path.getsize("compressed.csv.gz")) # 1008607 ``` ```shell >>> RuntimeWarning: compression has no effect when passing a non-binary object as input. csv_str = batch.to_pandas().to_csv( ``` ```python # dataset is not compressed and no warnings are emitted dataset.to_csv("compressed.csv.gz") print(os.path.getsize("compressed.csv.gz")) # 1008607 # compare with dataset.to_pandas().to_csv("pandas.csv.gz") print(os.path.getsize("pandas.csv.gz")) # 418561 ``` --- I think that this is because behind the scenes `pandas.DataFrame.to_csv` is always called with a buf-like `path_or_buf`, but users that are providing a path-like to `datasets.Dataset.to_csv` are likely not to expect / know that - leading to a mismatch in their understanding of the expected behaviour of the `compression` kwarg. ### Expected behavior The dataset to be saved as a compressed csv file when providing a `compression` kwarg, or when relying on the default `compression='infer'` ### Environment info `datasets == 2.13.1`
38
Compression kwargs have no effect when saving datasets as csv ### Describe the bug Attempting to save a dataset as a compressed csv file, the compression kwargs provided to `.to_csv()` that get piped to panda's `pandas.DataFrame.to_csv` do not have any effect - resulting in the dataset not getting compressed. A warning is raised if explicitly providing a `compression` kwarg, but no warnings are raised if relying on the defaults. This can lead to datasets secretly not getting compressed for users expecting the behaviour to match panda's `.to_csv()`, where the compression format is automatically inferred from the destination path suffix. ### Steps to reproduce the bug ```python # dataset is not compressed (but at least a warning is emitted) import datasets dataset = datasets.load_dataset("rotten_tomatoes", split="train") dataset.to_csv("uncompressed.csv") print(os.path.getsize("uncompressed.csv")) # 1008607 dataset.to_csv("compressed.csv.gz", compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}) print(os.path.getsize("compressed.csv.gz")) # 1008607 ``` ```shell >>> RuntimeWarning: compression has no effect when passing a non-binary object as input. csv_str = batch.to_pandas().to_csv( ``` ```python # dataset is not compressed and no warnings are emitted dataset.to_csv("compressed.csv.gz") print(os.path.getsize("compressed.csv.gz")) # 1008607 # compare with dataset.to_pandas().to_csv("pandas.csv.gz") print(os.path.getsize("pandas.csv.gz")) # 418561 ``` --- I think that this is because behind the scenes `pandas.DataFrame.to_csv` is always called with a buf-like `path_or_buf`, but users that are providing a path-like to `datasets.Dataset.to_csv` are likely not to expect / know that - leading to a mismatch in their understanding of the expected behaviour of the `compression` kwarg. ### Expected behavior The dataset to be saved as a compressed csv file when providing a `compression` kwarg, or when relying on the default `compression='infer'` ### Environment info `datasets == 2.13.1` Hello @exs-avianello, I have reproduced the bug successfully and have understood the problem. But I am confused regarding this part of the statement, "`pandas.DataFrame.to_csv` is always called with a buf-like `path_or_buf`". Can you please elaborate on it? Thanks!
https://github.com/huggingface/datasets/issues/6043
Compression kwargs have no effect when saving datasets as csv
Hi @aryanxk02 ! Sure, what I actually meant is that when passing a path-like `path_or_buf` here https://github.com/huggingface/datasets/blob/14f6edd9222e577dccb962ed5338b79b73502fa5/src/datasets/arrow_dataset.py#L4708-L4714 it gets converted to a file object behind the scenes here https://github.com/huggingface/datasets/blob/14f6edd9222e577dccb962ed5338b79b73502fa5/src/datasets/io/csv.py#L92-L94 and the eventual pandas `.to_csv()` calls that write to it always get `path_or_buf=None`, making pandas ignore the `compression` kwarg in the `to_csv_kwargs` https://github.com/huggingface/datasets/blob/14f6edd9222e577dccb962ed5338b79b73502fa5/src/datasets/io/csv.py#L107-L109
### Describe the bug Attempting to save a dataset as a compressed csv file, the compression kwargs provided to `.to_csv()` that get piped to panda's `pandas.DataFrame.to_csv` do not have any effect - resulting in the dataset not getting compressed. A warning is raised if explicitly providing a `compression` kwarg, but no warnings are raised if relying on the defaults. This can lead to datasets secretly not getting compressed for users expecting the behaviour to match panda's `.to_csv()`, where the compression format is automatically inferred from the destination path suffix. ### Steps to reproduce the bug ```python # dataset is not compressed (but at least a warning is emitted) import datasets dataset = datasets.load_dataset("rotten_tomatoes", split="train") dataset.to_csv("uncompressed.csv") print(os.path.getsize("uncompressed.csv")) # 1008607 dataset.to_csv("compressed.csv.gz", compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}) print(os.path.getsize("compressed.csv.gz")) # 1008607 ``` ```shell >>> RuntimeWarning: compression has no effect when passing a non-binary object as input. csv_str = batch.to_pandas().to_csv( ``` ```python # dataset is not compressed and no warnings are emitted dataset.to_csv("compressed.csv.gz") print(os.path.getsize("compressed.csv.gz")) # 1008607 # compare with dataset.to_pandas().to_csv("pandas.csv.gz") print(os.path.getsize("pandas.csv.gz")) # 418561 ``` --- I think that this is because behind the scenes `pandas.DataFrame.to_csv` is always called with a buf-like `path_or_buf`, but users that are providing a path-like to `datasets.Dataset.to_csv` are likely not to expect / know that - leading to a mismatch in their understanding of the expected behaviour of the `compression` kwarg. ### Expected behavior The dataset to be saved as a compressed csv file when providing a `compression` kwarg, or when relying on the default `compression='infer'` ### Environment info `datasets == 2.13.1`
52
Compression kwargs have no effect when saving datasets as csv ### Describe the bug Attempting to save a dataset as a compressed csv file, the compression kwargs provided to `.to_csv()` that get piped to panda's `pandas.DataFrame.to_csv` do not have any effect - resulting in the dataset not getting compressed. A warning is raised if explicitly providing a `compression` kwarg, but no warnings are raised if relying on the defaults. This can lead to datasets secretly not getting compressed for users expecting the behaviour to match panda's `.to_csv()`, where the compression format is automatically inferred from the destination path suffix. ### Steps to reproduce the bug ```python # dataset is not compressed (but at least a warning is emitted) import datasets dataset = datasets.load_dataset("rotten_tomatoes", split="train") dataset.to_csv("uncompressed.csv") print(os.path.getsize("uncompressed.csv")) # 1008607 dataset.to_csv("compressed.csv.gz", compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}) print(os.path.getsize("compressed.csv.gz")) # 1008607 ``` ```shell >>> RuntimeWarning: compression has no effect when passing a non-binary object as input. csv_str = batch.to_pandas().to_csv( ``` ```python # dataset is not compressed and no warnings are emitted dataset.to_csv("compressed.csv.gz") print(os.path.getsize("compressed.csv.gz")) # 1008607 # compare with dataset.to_pandas().to_csv("pandas.csv.gz") print(os.path.getsize("pandas.csv.gz")) # 418561 ``` --- I think that this is because behind the scenes `pandas.DataFrame.to_csv` is always called with a buf-like `path_or_buf`, but users that are providing a path-like to `datasets.Dataset.to_csv` are likely not to expect / know that - leading to a mismatch in their understanding of the expected behaviour of the `compression` kwarg. ### Expected behavior The dataset to be saved as a compressed csv file when providing a `compression` kwarg, or when relying on the default `compression='infer'` ### Environment info `datasets == 2.13.1` Hi @aryanxk02 ! Sure, what I actually meant is that when passing a path-like `path_or_buf` here https://github.com/huggingface/datasets/blob/14f6edd9222e577dccb962ed5338b79b73502fa5/src/datasets/arrow_dataset.py#L4708-L4714 it gets converted to a file object behind the scenes here https://github.com/huggingface/datasets/blob/14f6edd9222e577dccb962ed5338b79b73502fa5/src/datasets/io/csv.py#L92-L94 and the eventual pandas `.to_csv()` calls that write to it always get `path_or_buf=None`, making pandas ignore the `compression` kwarg in the `to_csv_kwargs` https://github.com/huggingface/datasets/blob/14f6edd9222e577dccb962ed5338b79b73502fa5/src/datasets/io/csv.py#L107-L109
https://github.com/huggingface/datasets/issues/6043
Compression kwargs have no effect when saving datasets as csv
@exs-avianello When `path_or_buf` is set to None, the `to_csv()` method will return the CSV data as a string instead of saving it to a file. Hence the compression doesn't take place. I think setting `path_or_buf=self.path_or_buf` should work. What you say?
### Describe the bug Attempting to save a dataset as a compressed csv file, the compression kwargs provided to `.to_csv()` that get piped to panda's `pandas.DataFrame.to_csv` do not have any effect - resulting in the dataset not getting compressed. A warning is raised if explicitly providing a `compression` kwarg, but no warnings are raised if relying on the defaults. This can lead to datasets secretly not getting compressed for users expecting the behaviour to match panda's `.to_csv()`, where the compression format is automatically inferred from the destination path suffix. ### Steps to reproduce the bug ```python # dataset is not compressed (but at least a warning is emitted) import datasets dataset = datasets.load_dataset("rotten_tomatoes", split="train") dataset.to_csv("uncompressed.csv") print(os.path.getsize("uncompressed.csv")) # 1008607 dataset.to_csv("compressed.csv.gz", compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}) print(os.path.getsize("compressed.csv.gz")) # 1008607 ``` ```shell >>> RuntimeWarning: compression has no effect when passing a non-binary object as input. csv_str = batch.to_pandas().to_csv( ``` ```python # dataset is not compressed and no warnings are emitted dataset.to_csv("compressed.csv.gz") print(os.path.getsize("compressed.csv.gz")) # 1008607 # compare with dataset.to_pandas().to_csv("pandas.csv.gz") print(os.path.getsize("pandas.csv.gz")) # 418561 ``` --- I think that this is because behind the scenes `pandas.DataFrame.to_csv` is always called with a buf-like `path_or_buf`, but users that are providing a path-like to `datasets.Dataset.to_csv` are likely not to expect / know that - leading to a mismatch in their understanding of the expected behaviour of the `compression` kwarg. ### Expected behavior The dataset to be saved as a compressed csv file when providing a `compression` kwarg, or when relying on the default `compression='infer'` ### Environment info `datasets == 2.13.1`
40
Compression kwargs have no effect when saving datasets as csv ### Describe the bug Attempting to save a dataset as a compressed csv file, the compression kwargs provided to `.to_csv()` that get piped to panda's `pandas.DataFrame.to_csv` do not have any effect - resulting in the dataset not getting compressed. A warning is raised if explicitly providing a `compression` kwarg, but no warnings are raised if relying on the defaults. This can lead to datasets secretly not getting compressed for users expecting the behaviour to match panda's `.to_csv()`, where the compression format is automatically inferred from the destination path suffix. ### Steps to reproduce the bug ```python # dataset is not compressed (but at least a warning is emitted) import datasets dataset = datasets.load_dataset("rotten_tomatoes", split="train") dataset.to_csv("uncompressed.csv") print(os.path.getsize("uncompressed.csv")) # 1008607 dataset.to_csv("compressed.csv.gz", compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}) print(os.path.getsize("compressed.csv.gz")) # 1008607 ``` ```shell >>> RuntimeWarning: compression has no effect when passing a non-binary object as input. csv_str = batch.to_pandas().to_csv( ``` ```python # dataset is not compressed and no warnings are emitted dataset.to_csv("compressed.csv.gz") print(os.path.getsize("compressed.csv.gz")) # 1008607 # compare with dataset.to_pandas().to_csv("pandas.csv.gz") print(os.path.getsize("pandas.csv.gz")) # 418561 ``` --- I think that this is because behind the scenes `pandas.DataFrame.to_csv` is always called with a buf-like `path_or_buf`, but users that are providing a path-like to `datasets.Dataset.to_csv` are likely not to expect / know that - leading to a mismatch in their understanding of the expected behaviour of the `compression` kwarg. ### Expected behavior The dataset to be saved as a compressed csv file when providing a `compression` kwarg, or when relying on the default `compression='infer'` ### Environment info `datasets == 2.13.1` @exs-avianello When `path_or_buf` is set to None, the `to_csv()` method will return the CSV data as a string instead of saving it to a file. Hence the compression doesn't take place. I think setting `path_or_buf=self.path_or_buf` should work. What you say?
https://github.com/huggingface/datasets/issues/6038
File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/builder.py", line 992, in _download_and_prepare if str(split_generator.split_info.name).lower() == "all": AttributeError: 'str' object has no attribute 'split_info'. Did you mean: 'splitlines'?
Instead of writing the loading script, you can use the built-in loader to [load JSON files](https://huggingface.co/docs/datasets/loading#json): ```python from datasets import load_dataset ds = load_dataset("json", data_files={"train": os.path.join(data_dir["train"]), "dev": os.path.join(data_dir["dev"])}) ```
Hi, I use the code below to load local file ``` def _split_generators(self, dl_manager): # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files. # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive # urls = _URLS[self.config.name] data_dir = dl_manager.download_and_extract(_URLs) print(data_dir) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir["train"]), "split": "train", }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir["dev"]), "split": "dev", }, ), ] ``` and error occured ``` Traceback (most recent call last): File "/home/zhizhou/data1/zhanghao/huggingface/FineTuning_Transformer/load_local_dataset.py", line 2, in <module> dataset = load_dataset("./QA_script.py",data_files='/home/zhizhou/.cache/huggingface/datasets/conversatiom_corps/part_file.json') File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/load.py", line 1809, in load_dataset builder_instance.download_and_prepare( File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/builder.py", line 1670, in _download_and_prepare super()._download_and_prepare( File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/builder.py", line 992, in _download_and_prepare if str(split_generator.split_info.name).lower() == "all": AttributeError: 'str' object has no attribute 'split_info'. Did you mean: 'splitlines'? ``` Could you help me?
29
File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/builder.py", line 992, in _download_and_prepare if str(split_generator.split_info.name).lower() == "all": AttributeError: 'str' object has no attribute 'split_info'. Did you mean: 'splitlines'? Hi, I use the code below to load local file ``` def _split_generators(self, dl_manager): # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files. # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive # urls = _URLS[self.config.name] data_dir = dl_manager.download_and_extract(_URLs) print(data_dir) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir["train"]), "split": "train", }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir["dev"]), "split": "dev", }, ), ] ``` and error occured ``` Traceback (most recent call last): File "/home/zhizhou/data1/zhanghao/huggingface/FineTuning_Transformer/load_local_dataset.py", line 2, in <module> dataset = load_dataset("./QA_script.py",data_files='/home/zhizhou/.cache/huggingface/datasets/conversatiom_corps/part_file.json') File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/load.py", line 1809, in load_dataset builder_instance.download_and_prepare( File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/builder.py", line 1670, in _download_and_prepare super()._download_and_prepare( File "/home/zhizhou/anaconda3/envs/pytorch/lib/python3.10/site-packages/datasets/builder.py", line 992, in _download_and_prepare if str(split_generator.split_info.name).lower() == "all": AttributeError: 'str' object has no attribute 'split_info'. Did you mean: 'splitlines'? ``` Could you help me? Instead of writing the loading script, you can use the built-in loader to [load JSON files](https://huggingface.co/docs/datasets/loading#json): ```python from datasets import load_dataset ds = load_dataset("json", data_files={"train": os.path.join(data_dir["train"]), "dev": os.path.join(data_dir["dev"])}) ```
https://github.com/huggingface/datasets/issues/6037
Documentation links to examples are broken
These docs are outdated (version 1.2.1 is over two years old). Please refer to [this](https://huggingface.co/docs/datasets/dataset_script) version instead. Initially, we hosted datasets in this repo, but now you can find them [on the HF Hub](https://huggingface.co/datasets) (e.g. the [`ag_news`](https://huggingface.co/datasets/ag_news/blob/main/ag_news.py) script)
### Describe the bug The links at the bottom of [add_dataset](https://huggingface.co/docs/datasets/v1.2.1/add_dataset.html) to examples of specific datasets are all broken, for example - text classification: [ag_news](https://github.com/huggingface/datasets/blob/master/datasets/ag_news/ag_news.py) (original data are in csv files) ### Steps to reproduce the bug Click on links to examples from latest documentation ### Expected behavior Links should be up to date - it might be more stable to link to https://huggingface.co/datasets/ag_news/blob/main/ag_news.py ### Environment info dataset v1.2.1
38
Documentation links to examples are broken ### Describe the bug The links at the bottom of [add_dataset](https://huggingface.co/docs/datasets/v1.2.1/add_dataset.html) to examples of specific datasets are all broken, for example - text classification: [ag_news](https://github.com/huggingface/datasets/blob/master/datasets/ag_news/ag_news.py) (original data are in csv files) ### Steps to reproduce the bug Click on links to examples from latest documentation ### Expected behavior Links should be up to date - it might be more stable to link to https://huggingface.co/datasets/ag_news/blob/main/ag_news.py ### Environment info dataset v1.2.1 These docs are outdated (version 1.2.1 is over two years old). Please refer to [this](https://huggingface.co/docs/datasets/dataset_script) version instead. Initially, we hosted datasets in this repo, but now you can find them [on the HF Hub](https://huggingface.co/datasets) (e.g. the [`ag_news`](https://huggingface.co/datasets/ag_news/blob/main/ag_news.py) script)
https://github.com/huggingface/datasets/issues/6034
load_dataset hangs on WSL
Even if a dataset is cached, we still make requests to check whether the cache is up-to-date. [This](https://huggingface.co/docs/datasets/v2.13.1/en/loading#offline) section in the docs explains how to avoid them and directly load the cached version.
### Describe the bug load_dataset simply hangs. It happens once every ~5 times, and interestingly hangs for a multiple of 5 minutes (hangs for 5/10/15 minutes). Using the profiler in PyCharm shows that it spends the time at <method 'connect' of '_socket.socket' objects>. However, a local cache is available so I am not sure why socket is needed. ([profiler result](https://ibb.co/0Btbbp8)) It only happens on WSL for me. It works for native Windows and my MacBook. (cache quickly recognized and loaded within a second). ### Steps to reproduce the bug I am using Ubuntu 22.04.2 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64) Python 3.10.10 (main, Mar 21 2023, 18:45:11) [GCC 11.2.0] on linux >>> import datasets >>> datasets.load_dataset('ai2_arc', 'ARC-Challenge') # hangs for 5/10/15 minutes ### Expected behavior cache quickly recognized and loaded within a second ### Environment info Please let me know if I should provide more environment information.
33
load_dataset hangs on WSL ### Describe the bug load_dataset simply hangs. It happens once every ~5 times, and interestingly hangs for a multiple of 5 minutes (hangs for 5/10/15 minutes). Using the profiler in PyCharm shows that it spends the time at <method 'connect' of '_socket.socket' objects>. However, a local cache is available so I am not sure why socket is needed. ([profiler result](https://ibb.co/0Btbbp8)) It only happens on WSL for me. It works for native Windows and my MacBook. (cache quickly recognized and loaded within a second). ### Steps to reproduce the bug I am using Ubuntu 22.04.2 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64) Python 3.10.10 (main, Mar 21 2023, 18:45:11) [GCC 11.2.0] on linux >>> import datasets >>> datasets.load_dataset('ai2_arc', 'ARC-Challenge') # hangs for 5/10/15 minutes ### Expected behavior cache quickly recognized and loaded within a second ### Environment info Please let me know if I should provide more environment information. Even if a dataset is cached, we still make requests to check whether the cache is up-to-date. [This](https://huggingface.co/docs/datasets/v2.13.1/en/loading#offline) section in the docs explains how to avoid them and directly load the cached version.
https://github.com/huggingface/datasets/issues/6034
load_dataset hangs on WSL
Thanks - that works! However it doesn't resolve the original issue (but I am not sure if it is a WSL problem)
### Describe the bug load_dataset simply hangs. It happens once every ~5 times, and interestingly hangs for a multiple of 5 minutes (hangs for 5/10/15 minutes). Using the profiler in PyCharm shows that it spends the time at <method 'connect' of '_socket.socket' objects>. However, a local cache is available so I am not sure why socket is needed. ([profiler result](https://ibb.co/0Btbbp8)) It only happens on WSL for me. It works for native Windows and my MacBook. (cache quickly recognized and loaded within a second). ### Steps to reproduce the bug I am using Ubuntu 22.04.2 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64) Python 3.10.10 (main, Mar 21 2023, 18:45:11) [GCC 11.2.0] on linux >>> import datasets >>> datasets.load_dataset('ai2_arc', 'ARC-Challenge') # hangs for 5/10/15 minutes ### Expected behavior cache quickly recognized and loaded within a second ### Environment info Please let me know if I should provide more environment information.
22
load_dataset hangs on WSL ### Describe the bug load_dataset simply hangs. It happens once every ~5 times, and interestingly hangs for a multiple of 5 minutes (hangs for 5/10/15 minutes). Using the profiler in PyCharm shows that it spends the time at <method 'connect' of '_socket.socket' objects>. However, a local cache is available so I am not sure why socket is needed. ([profiler result](https://ibb.co/0Btbbp8)) It only happens on WSL for me. It works for native Windows and my MacBook. (cache quickly recognized and loaded within a second). ### Steps to reproduce the bug I am using Ubuntu 22.04.2 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64) Python 3.10.10 (main, Mar 21 2023, 18:45:11) [GCC 11.2.0] on linux >>> import datasets >>> datasets.load_dataset('ai2_arc', 'ARC-Challenge') # hangs for 5/10/15 minutes ### Expected behavior cache quickly recognized and loaded within a second ### Environment info Please let me know if I should provide more environment information. Thanks - that works! However it doesn't resolve the original issue (but I am not sure if it is a WSL problem)
https://github.com/huggingface/datasets/issues/6034
load_dataset hangs on WSL
We use `requests` to make HTTP requests (and `aiohttp` in the streaming mode), so I don't think we can provide much help regarding the socket issue (it probably has something to do with WSL).
### Describe the bug load_dataset simply hangs. It happens once every ~5 times, and interestingly hangs for a multiple of 5 minutes (hangs for 5/10/15 minutes). Using the profiler in PyCharm shows that it spends the time at <method 'connect' of '_socket.socket' objects>. However, a local cache is available so I am not sure why socket is needed. ([profiler result](https://ibb.co/0Btbbp8)) It only happens on WSL for me. It works for native Windows and my MacBook. (cache quickly recognized and loaded within a second). ### Steps to reproduce the bug I am using Ubuntu 22.04.2 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64) Python 3.10.10 (main, Mar 21 2023, 18:45:11) [GCC 11.2.0] on linux >>> import datasets >>> datasets.load_dataset('ai2_arc', 'ARC-Challenge') # hangs for 5/10/15 minutes ### Expected behavior cache quickly recognized and loaded within a second ### Environment info Please let me know if I should provide more environment information.
34
load_dataset hangs on WSL ### Describe the bug load_dataset simply hangs. It happens once every ~5 times, and interestingly hangs for a multiple of 5 minutes (hangs for 5/10/15 minutes). Using the profiler in PyCharm shows that it spends the time at <method 'connect' of '_socket.socket' objects>. However, a local cache is available so I am not sure why socket is needed. ([profiler result](https://ibb.co/0Btbbp8)) It only happens on WSL for me. It works for native Windows and my MacBook. (cache quickly recognized and loaded within a second). ### Steps to reproduce the bug I am using Ubuntu 22.04.2 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64) Python 3.10.10 (main, Mar 21 2023, 18:45:11) [GCC 11.2.0] on linux >>> import datasets >>> datasets.load_dataset('ai2_arc', 'ARC-Challenge') # hangs for 5/10/15 minutes ### Expected behavior cache quickly recognized and loaded within a second ### Environment info Please let me know if I should provide more environment information. We use `requests` to make HTTP requests (and `aiohttp` in the streaming mode), so I don't think we can provide much help regarding the socket issue (it probably has something to do with WSL).
https://github.com/huggingface/datasets/issues/6032
DownloadConfig.proxies not work when load_dataset_builder calling HfApi.dataset_info
`HfApi` comes from the `huggingface_hub` package. You can use [this](https://huggingface.co/docs/huggingface_hub/v0.16.3/en/package_reference/utilities#huggingface_hub.configure_http_backend) utility to change the `huggingface_hub`'s `Session` proxies (see the example). We plan to implement https://github.com/huggingface/datasets/issues/5080 and make this behavior more consistent eventually.
### Describe the bug ```python download_config = DownloadConfig(proxies={'https': '<my proxy>'}) builder = load_dataset_builder(..., download_config=download_config) ``` But, when getting the dataset_info from HfApi, the http requests not using the proxies. ### Steps to reproduce the bug 1. Setup proxies in DownloadConfig. 2. Call `load_dataset_build` with download_config. 3. Inspect the call stack in HfApi.dataset_info. ![image](https://github.com/huggingface/datasets/assets/138426806/33e538a8-2e22-4e63-b634-343febe5324b) ### Expected behavior DownloadConfig.proxies works for getting dataset_info. ### Environment info https://github.com/huggingface/datasets/commit/406b2212263c0d33f267e35b917f410ff6b3bc00 Python 3.11.4
32
DownloadConfig.proxies not work when load_dataset_builder calling HfApi.dataset_info ### Describe the bug ```python download_config = DownloadConfig(proxies={'https': '<my proxy>'}) builder = load_dataset_builder(..., download_config=download_config) ``` But, when getting the dataset_info from HfApi, the http requests not using the proxies. ### Steps to reproduce the bug 1. Setup proxies in DownloadConfig. 2. Call `load_dataset_build` with download_config. 3. Inspect the call stack in HfApi.dataset_info. ![image](https://github.com/huggingface/datasets/assets/138426806/33e538a8-2e22-4e63-b634-343febe5324b) ### Expected behavior DownloadConfig.proxies works for getting dataset_info. ### Environment info https://github.com/huggingface/datasets/commit/406b2212263c0d33f267e35b917f410ff6b3bc00 Python 3.11.4 `HfApi` comes from the `huggingface_hub` package. You can use [this](https://huggingface.co/docs/huggingface_hub/v0.16.3/en/package_reference/utilities#huggingface_hub.configure_http_backend) utility to change the `huggingface_hub`'s `Session` proxies (see the example). We plan to implement https://github.com/huggingface/datasets/issues/5080 and make this behavior more consistent eventually.
https://github.com/huggingface/datasets/issues/6025
Using a dataset for a use other than it was intended for.
I've opened a PR with a fix. In the meantime, you can avoid the error by deleting `task_templates` with `dataset.info.task_templates = None` before the `interleave_datasets` call. `
### Describe the bug Hi, I want to use the rotten tomatoes dataset but for a task other than classification, but when I interleave the dataset, it throws ```'ValueError: Column label is not present in features.'```. It seems that the label_col must be there in the dataset for some reason? Here is the full stacktrace ``` File "/home/suryahari/Vornoi/tryage-handoff-other-datasets.py", line 276, in create_dataloaders dataset = interleave_datasets(dsfold, stopping_strategy="all_exhausted") File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/combine.py", line 134, in interleave_datasets return _interleave_iterable_datasets( File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/iterable_dataset.py", line 1833, in _interleave_iterable_datasets info = DatasetInfo.from_merge([d.info for d in datasets]) File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 275, in from_merge dataset_infos = [dset_info.copy() for dset_info in dataset_infos if dset_info is not None] File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 275, in <listcomp> dataset_infos = [dset_info.copy() for dset_info in dataset_infos if dset_info is not None] File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 378, in copy return self.__class__(**{k: copy.deepcopy(v) for k, v in self.__dict__.items()}) File "<string>", line 20, in __init__ File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 208, in __post_init__ self.task_templates = [ File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 209, in <listcomp> template.align_with_features(self.features) for template in (self.task_templates) File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/tasks/text_classification.py", line 20, in align_with_features raise ValueError(f"Column {self.label_column} is not present in features.") ValueError: Column label is not present in features. ``` ### Steps to reproduce the bug Delete the column `labels` from the `rotten_tomatoes` dataset. Try to interleave it with other datasets. ### Expected behavior Should let me use the dataset with just the `text` field ### Environment info latest datasets library? I don't think this was an issue in earlier versions.
27
Using a dataset for a use other than it was intended for. ### Describe the bug Hi, I want to use the rotten tomatoes dataset but for a task other than classification, but when I interleave the dataset, it throws ```'ValueError: Column label is not present in features.'```. It seems that the label_col must be there in the dataset for some reason? Here is the full stacktrace ``` File "/home/suryahari/Vornoi/tryage-handoff-other-datasets.py", line 276, in create_dataloaders dataset = interleave_datasets(dsfold, stopping_strategy="all_exhausted") File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/combine.py", line 134, in interleave_datasets return _interleave_iterable_datasets( File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/iterable_dataset.py", line 1833, in _interleave_iterable_datasets info = DatasetInfo.from_merge([d.info for d in datasets]) File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 275, in from_merge dataset_infos = [dset_info.copy() for dset_info in dataset_infos if dset_info is not None] File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 275, in <listcomp> dataset_infos = [dset_info.copy() for dset_info in dataset_infos if dset_info is not None] File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 378, in copy return self.__class__(**{k: copy.deepcopy(v) for k, v in self.__dict__.items()}) File "<string>", line 20, in __init__ File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 208, in __post_init__ self.task_templates = [ File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/info.py", line 209, in <listcomp> template.align_with_features(self.features) for template in (self.task_templates) File "/home/suryahari/miniconda3/envs/vornoi/lib/python3.10/site-packages/datasets/tasks/text_classification.py", line 20, in align_with_features raise ValueError(f"Column {self.label_column} is not present in features.") ValueError: Column label is not present in features. ``` ### Steps to reproduce the bug Delete the column `labels` from the `rotten_tomatoes` dataset. Try to interleave it with other datasets. ### Expected behavior Should let me use the dataset with just the `text` field ### Environment info latest datasets library? I don't think this was an issue in earlier versions. I've opened a PR with a fix. In the meantime, you can avoid the error by deleting `task_templates` with `dataset.info.task_templates = None` before the `interleave_datasets` call. `
https://github.com/huggingface/datasets/issues/6020
Inconsistent "The features can't be aligned" error when combining map, multiprocessing, and variable length outputs
This scenario currently requires explicitly passing the target features (to avoid the error): ```python import datasets ... features = dataset.features features["output"] = = [{"test": datasets.Value("int64")}] test2 = dataset.map(lambda row, idx: test_func(row, idx), with_indices=True, num_proc=32, features=features) ```
### Describe the bug I'm using a dataset with map and multiprocessing to run a function that returned a variable length list of outputs. This output list may be empty. Normally this is handled fine, but there is an edge case that crops up when using multiprocessing. In some cases, an empty list result ends up in a dataset shard consisting of a single item. This results in a `The features can't be aligned` error that is difficult to debug because it depends on the number of processes/shards used. I've reproduced a minimal example below. My current workaround is to fill empty results with a dummy value that I filter after, but this was a weird error that took a while to track down. ### Steps to reproduce the bug ```python import datasets dataset = datasets.Dataset.from_list([{'idx':i} for i in range(60)]) def test_func(row, idx): if idx==58: return {'output': []} else: return {'output' : [{'test':1}, {'test':2}]} # this works fine test1 = dataset.map(lambda row, idx: test_func(row, idx), with_indices=True, num_proc=4) # this fails test2 = dataset.map(lambda row, idx: test_func(row, idx), with_indices=True, num_proc=32) >ValueError: The features can't be aligned because the key output of features {'idx': Value(dtype='int64', id=None), 'output': Sequence(feature=Value(dtype='null', id=None), length=-1, id=None)} has unexpected type - Sequence(feature=Value(dtype='null', id=None), length=-1, id=None) (expected either [{'test': Value(dtype='int64', id=None)}] or Value("null"). ``` The error occurs during the check ```python _check_if_features_can_be_aligned([dset.features for dset in dsets]) ``` When the multiprocessing splitting lines up just right with the empty return value, one of the `dset` in `dsets` will have a single item with an empty list value, causing the error. ### Expected behavior Expected behavior is the result would be the same regardless of the `num_proc` value used. ### Environment info Datasets version 2.11.0 Python 3.9.16
36
Inconsistent "The features can't be aligned" error when combining map, multiprocessing, and variable length outputs ### Describe the bug I'm using a dataset with map and multiprocessing to run a function that returned a variable length list of outputs. This output list may be empty. Normally this is handled fine, but there is an edge case that crops up when using multiprocessing. In some cases, an empty list result ends up in a dataset shard consisting of a single item. This results in a `The features can't be aligned` error that is difficult to debug because it depends on the number of processes/shards used. I've reproduced a minimal example below. My current workaround is to fill empty results with a dummy value that I filter after, but this was a weird error that took a while to track down. ### Steps to reproduce the bug ```python import datasets dataset = datasets.Dataset.from_list([{'idx':i} for i in range(60)]) def test_func(row, idx): if idx==58: return {'output': []} else: return {'output' : [{'test':1}, {'test':2}]} # this works fine test1 = dataset.map(lambda row, idx: test_func(row, idx), with_indices=True, num_proc=4) # this fails test2 = dataset.map(lambda row, idx: test_func(row, idx), with_indices=True, num_proc=32) >ValueError: The features can't be aligned because the key output of features {'idx': Value(dtype='int64', id=None), 'output': Sequence(feature=Value(dtype='null', id=None), length=-1, id=None)} has unexpected type - Sequence(feature=Value(dtype='null', id=None), length=-1, id=None) (expected either [{'test': Value(dtype='int64', id=None)}] or Value("null"). ``` The error occurs during the check ```python _check_if_features_can_be_aligned([dset.features for dset in dsets]) ``` When the multiprocessing splitting lines up just right with the empty return value, one of the `dset` in `dsets` will have a single item with an empty list value, causing the error. ### Expected behavior Expected behavior is the result would be the same regardless of the `num_proc` value used. ### Environment info Datasets version 2.11.0 Python 3.9.16 This scenario currently requires explicitly passing the target features (to avoid the error): ```python import datasets ... features = dataset.features features["output"] = = [{"test": datasets.Value("int64")}] test2 = dataset.map(lambda row, idx: test_func(row, idx), with_indices=True, num_proc=32, features=features) ```
https://github.com/huggingface/datasets/issues/6014
Request to Share/Update Dataset Viewer Code
Hi ! The huggingface/dataset-viewer code was not maintained anymore because we switched to a new dataset viewer that is deployed available for each dataset the Hugging Face website. What are you using this old repository for ?
Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response.
37
Request to Share/Update Dataset Viewer Code Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response. Hi ! The huggingface/dataset-viewer code was not maintained anymore because we switched to a new dataset viewer that is deployed available for each dataset the Hugging Face website. What are you using this old repository for ?
https://github.com/huggingface/datasets/issues/6014
Request to Share/Update Dataset Viewer Code
I think these parts are outdated: * https://github.com/huggingface/datasets-viewer/blob/8efad8eae313a891f713469983bf4c744786f26e/run.py#L126-L131 * https://github.com/huggingface/datasets-viewer/blob/8efad8eae313a891f713469983bf4c744786f26e/run.py#L145-L150 To make the viewer work, the first one should be replaced with the following: ```python dataset_module = datasets.load.dataset_module_factory(path) builder_cls = datasets.load.import_main_class(dataset_module.module_path) confs = builder_cls.BUILDER_CONFIGS ``` And the second one: ```python dataset_module = datasets.load.dataset_module_factory(path) builder_cls = datasets.load.import_main_class(dataset_module.module_path) if conf: builder_instance = builder_cls(name=conf, cache_dir=path if path_to_datasets is not None else None) else: builder_instance = builder_cls(cache_dir=path if path_to_datasets is not None else None) ``` But as @lhoestq suggested, it's better to use the `datasets-server` API nowadays to [fetch the rows](https://huggingface.co/docs/datasets-server/rows).
Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response.
87
Request to Share/Update Dataset Viewer Code Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response. I think these parts are outdated: * https://github.com/huggingface/datasets-viewer/blob/8efad8eae313a891f713469983bf4c744786f26e/run.py#L126-L131 * https://github.com/huggingface/datasets-viewer/blob/8efad8eae313a891f713469983bf4c744786f26e/run.py#L145-L150 To make the viewer work, the first one should be replaced with the following: ```python dataset_module = datasets.load.dataset_module_factory(path) builder_cls = datasets.load.import_main_class(dataset_module.module_path) confs = builder_cls.BUILDER_CONFIGS ``` And the second one: ```python dataset_module = datasets.load.dataset_module_factory(path) builder_cls = datasets.load.import_main_class(dataset_module.module_path) if conf: builder_instance = builder_cls(name=conf, cache_dir=path if path_to_datasets is not None else None) else: builder_instance = builder_cls(cache_dir=path if path_to_datasets is not None else None) ``` But as @lhoestq suggested, it's better to use the `datasets-server` API nowadays to [fetch the rows](https://huggingface.co/docs/datasets-server/rows).
https://github.com/huggingface/datasets/issues/6014
Request to Share/Update Dataset Viewer Code
> The dataset viewer on the Hugging Face website is incredibly useful @mariosasko i think @lilyorlilypad wants to run the new dataset-viewer, not the old one
Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response.
26
Request to Share/Update Dataset Viewer Code Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response. > The dataset viewer on the Hugging Face website is incredibly useful @mariosasko i think @lilyorlilypad wants to run the new dataset-viewer, not the old one
https://github.com/huggingface/datasets/issues/6014
Request to Share/Update Dataset Viewer Code
> wants to run the new dataset-viewer, not the old one Thanks for the clarification for me. I do want to run the new dataset-viewer.
Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response.
25
Request to Share/Update Dataset Viewer Code Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response. > wants to run the new dataset-viewer, not the old one Thanks for the clarification for me. I do want to run the new dataset-viewer.
https://github.com/huggingface/datasets/issues/6014
Request to Share/Update Dataset Viewer Code
It should be possible to run it locally using the HF datasets-server API (docs [here](https://huggingface.co/docs/datasets-server)) but the front end part is not open source (yet ?) The back-end is open source though if you're interested: https://github.com/huggingface/datasets-server It automatically converts datasets on HF to Parquet, which is the format we use to power the viewer.
Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response.
54
Request to Share/Update Dataset Viewer Code Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response. It should be possible to run it locally using the HF datasets-server API (docs [here](https://huggingface.co/docs/datasets-server)) but the front end part is not open source (yet ?) The back-end is open source though if you're interested: https://github.com/huggingface/datasets-server It automatically converts datasets on HF to Parquet, which is the format we use to power the viewer.
https://github.com/huggingface/datasets/issues/6014
Request to Share/Update Dataset Viewer Code
the new frontend would probably be hard to open source, as is, as it's quite intertwined with the Hub's code. However, at some point it would be amazing to have a community-driven open source implementation of a frontend to datasets-server!
Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response.
40
Request to Share/Update Dataset Viewer Code Overview: The repository (huggingface/datasets-viewer) was recently archived and when I tried to run the code, there was the error message "AttributeError: module 'datasets.load' has no attribute 'prepare_module'". I could not resolve the issue myself due to lack of documentation of that attribute. Request: I kindly request the sharing of the code responsible for the dataset preview functionality or help with resolving the error. The dataset viewer on the Hugging Face website is incredibly useful since it is compatible with different types of inputs. It allows users to find datasets that meet their needs more efficiently. If needed, I am willing to contribute to the project by testing, documenting, and providing feedback on the dataset viewer code. Thank you for considering this request, and I look forward to your response. the new frontend would probably be hard to open source, as is, as it's quite intertwined with the Hub's code. However, at some point it would be amazing to have a community-driven open source implementation of a frontend to datasets-server!
https://github.com/huggingface/datasets/issues/6013
[FR] `map` should reuse unchanged columns from the previous dataset to avoid disk usage
You can use the `remove_columns` parameter in `map` to avoid duplicating the columns (and save disk space) and then concatenate the original dataset with the map result: ```python from datasets import concatenate_datasets # dummy example ds_new = ds.map(lambda x: {"new_col": x["col"] + 2}, remove_columns=ds.column_names) ds_combined = concatenate_datasets([ds, ds_new], axis=1) ``` Doing this automatically is hard to implement efficiently unless we know ahead of time which existing columns will be modified by a `map` transform. We have this info when `input_columns` are specified, so I think this is the only case we can optimize.
### Feature request Currently adding a new column with `map` will cause all the data in the dataset to be duplicated and stored/cached on the disk again. It should reuse unchanged columns. ### Motivation This allows having datasets with different columns but sharing some basic columns. Currently, these datasets would become too expensive to store and one would need some kind of on-the-fly join; which also doesn't seem implemented. ### Your contribution _
93
[FR] `map` should reuse unchanged columns from the previous dataset to avoid disk usage ### Feature request Currently adding a new column with `map` will cause all the data in the dataset to be duplicated and stored/cached on the disk again. It should reuse unchanged columns. ### Motivation This allows having datasets with different columns but sharing some basic columns. Currently, these datasets would become too expensive to store and one would need some kind of on-the-fly join; which also doesn't seem implemented. ### Your contribution _ You can use the `remove_columns` parameter in `map` to avoid duplicating the columns (and save disk space) and then concatenate the original dataset with the map result: ```python from datasets import concatenate_datasets # dummy example ds_new = ds.map(lambda x: {"new_col": x["col"] + 2}, remove_columns=ds.column_names) ds_combined = concatenate_datasets([ds, ds_new], axis=1) ``` Doing this automatically is hard to implement efficiently unless we know ahead of time which existing columns will be modified by a `map` transform. We have this info when `input_columns` are specified, so I think this is the only case we can optimize.
https://github.com/huggingface/datasets/issues/6012
[FR] Transform Chaining, Lazy Mapping
You can use `with_transform` to get a new dataset object. Support for lazy `map` has already been discussed [here](https://github.com/huggingface/datasets/issues/3385) a little bit. Personally, I'm not a fan, as this would make `map` even more complex.
### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _
35
[FR] Transform Chaining, Lazy Mapping ### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _ You can use `with_transform` to get a new dataset object. Support for lazy `map` has already been discussed [here](https://github.com/huggingface/datasets/issues/3385) a little bit. Personally, I'm not a fan, as this would make `map` even more complex.
https://github.com/huggingface/datasets/issues/6012
[FR] Transform Chaining, Lazy Mapping
> You can use `with_transform` to get a new dataset object. > > Support for lazy `map` has already been discussed [here](https://github.com/huggingface/datasets/issues/3385) a little bit. Personally, I'm not a fan, as this would make `map` even more complex. I read about IterableDataset, and it seems to have lazy mapping. But I can't figure out how to convert an IterableDataset into a normal one when needed. `with_transform` still does not chain AFAIU.
### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _
71
[FR] Transform Chaining, Lazy Mapping ### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _ > You can use `with_transform` to get a new dataset object. > > Support for lazy `map` has already been discussed [here](https://github.com/huggingface/datasets/issues/3385) a little bit. Personally, I'm not a fan, as this would make `map` even more complex. I read about IterableDataset, and it seems to have lazy mapping. But I can't figure out how to convert an IterableDataset into a normal one when needed. `with_transform` still does not chain AFAIU.
https://github.com/huggingface/datasets/issues/6012
[FR] Transform Chaining, Lazy Mapping
> I read about IterableDataset, and it seems to have lazy mapping. But I can't figure out how to convert an IterableDataset into a normal one when needed. You must cache an `IterableDataset` to disk to load it as a `Dataset`. One way to do this is with `Dataset.from_generator`: ```python from functools import partial from datasets import Dataset def gen_from_iterable_dataset(iterable_ds) yield from iterable_ds ds = Dataset.from_generator(partial(gen_from_iterable_dataset, iterable_ds), features=iterable_ds.features}) ``` > with_transform still does not chain AFAIU. Yes, not supported yet - the solution is to combine the transforms into a single one.
### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _
92
[FR] Transform Chaining, Lazy Mapping ### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _ > I read about IterableDataset, and it seems to have lazy mapping. But I can't figure out how to convert an IterableDataset into a normal one when needed. You must cache an `IterableDataset` to disk to load it as a `Dataset`. One way to do this is with `Dataset.from_generator`: ```python from functools import partial from datasets import Dataset def gen_from_iterable_dataset(iterable_ds) yield from iterable_ds ds = Dataset.from_generator(partial(gen_from_iterable_dataset, iterable_ds), features=iterable_ds.features}) ``` > with_transform still does not chain AFAIU. Yes, not supported yet - the solution is to combine the transforms into a single one.
https://github.com/huggingface/datasets/issues/6012
[FR] Transform Chaining, Lazy Mapping
I wonder if it would be beneficial to have a dedicated method to do that ? Maybe a `.save_to_disk()` so that the user can reload the resulting dataset later ?
### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _
30
[FR] Transform Chaining, Lazy Mapping ### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _ I wonder if it would be beneficial to have a dedicated method to do that ? Maybe a `.save_to_disk()` so that the user can reload the resulting dataset later ?
https://github.com/huggingface/datasets/issues/6012
[FR] Transform Chaining, Lazy Mapping
> ```python > from functools import partial > from datasets import Dataset > > def gen_from_iterable_dataset(iterable_ds) > yield from iterable_ds > > ds = Dataset.from_generator(partial(gen_from_iterable_dataset, iterable_ds), features=iterable_ds.features}) > ``` @mariosasko With these complex mapping functions, what hash will be used to cache this dataset?
### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _
44
[FR] Transform Chaining, Lazy Mapping ### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _ > ```python > from functools import partial > from datasets import Dataset > > def gen_from_iterable_dataset(iterable_ds) > yield from iterable_ds > > ds = Dataset.from_generator(partial(gen_from_iterable_dataset, iterable_ds), features=iterable_ds.features}) > ``` @mariosasko With these complex mapping functions, what hash will be used to cache this dataset?
https://github.com/huggingface/datasets/issues/6012
[FR] Transform Chaining, Lazy Mapping
The params passed to `Dataset.from_generator` will be used to compute the hash (`partial` encapsulates the `iterable_ds` value, so changing it will also change the hash)
### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _
25
[FR] Transform Chaining, Lazy Mapping ### Feature request Currently using a `map` call processes and duplicates the whole dataset, which takes both time and disk space. The solution is to allow lazy mapping, which is essentially a saved chain of transforms that are applied on the fly whenever a slice of the dataset is requested. The API should look like `map`, as `set_transform` changes the current dataset while `map` returns another dataset. ### Motivation Lazy processing allows lower disk usage and faster experimentation. ### Your contribution _ The params passed to `Dataset.from_generator` will be used to compute the hash (`partial` encapsulates the `iterable_ds` value, so changing it will also change the hash)
https://github.com/huggingface/datasets/issues/6011
Documentation: wiki_dpr Dataset has no metric_type for Faiss Index
Hi! You can do `ds.get_index("embeddings").faiss_index.metric_type` to get the metric type and then match the result with the FAISS metric [enum](https://github.com/facebookresearch/faiss/blob/43d86e30736ede853c384b24667fc3ab897d6ba9/faiss/MetricType.h#L22-L36) (should be L2).
### Describe the bug After loading `wiki_dpr` using: ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # prints nothing because the value is None ``` the index does not have a defined `metric_type`. This is an issue because I do not know how the `scores` are being computed for `get_nearest_examples()`. ### Steps to reproduce the bug System: Python 3.9.16, Transformers 4.30.2, WSL After loading `wiki_dpr` using: ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # prints nothing because the value is None ``` the index does not have a defined `metric_type`. This is an issue because I do not know how the `scores` are being computed for `get_nearest_examples()`. ```py from transformers import DPRQuestionEncoder, DPRContextEncoder, DPRQuestionEncoderTokenizer, DPRContextEncoderTokenizer tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-multiset-base") encoder = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-multiset-base") def encode_question(query, tokenizer=tokenizer, encoder=encoder): inputs = tokenizer(query, return_tensors='pt') question_embedding = encoder(**inputs)[0].detach().numpy() return question_embedding def get_knn(query, k=5, tokenizer=tokenizer, encoder=encoder, verbose=False): enc_question = encode_question(query, tokenizer, encoder) topk_results = ds.get_nearest_examples(index_name='embeddings', query=enc_question, k=k) a = torch.tensor(enc_question[0]).reshape(768) b = torch.tensor(topk_results.examples['embeddings'][0]) print(a.shape, b.shape) print(torch.dot(a, b)) print((a-b).pow(2).sum()) return topk_results ``` The [FAISS documentation](https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances) suggests the metric is usually L2 distance (without the square root) or the inner product. I compute both for the sample query: ```py query = """ it catapulted into popular culture along with a line of action figures and other toys by Bandai.[2] By 2001, the media franchise had generated over $6 billion in toy sales. Despite initial criticism that its action violence targeted child audiences, the franchise has been commercially successful.""" get_knn(query,k=5) ``` Here, I get dot product of 80.6020 and L2 distance of 77.6616 and ```py NearestExamplesResults(scores=array([76.20431 , 75.312416, 74.945404, 74.866394, 74.68506 ], dtype=float32), examples={'id': ['3081096', '2004811', '8908258', '9594124', '286575'], 'text': ['actors, resulting in the "Power Rangers" franchise which has continued since then into sequel TV series (with "Power Rangers Beast Morphers" set to premiere in 2019), comic books, video games, and three feature films, with a further cinematic universe planned. Following from the success of "Power Rangers", Saban acquired the rights to more of Toei\'s library, creating "VR Troopers" and "Big Bad Beetleborgs" from several Metal Hero Series shows and "Masked Rider" from Kamen Rider Series footage. DIC Entertainment joined this boom by acquiring the rights to "Gridman the Hyper Agent" and turning it into "Superhuman Samurai Syber-Squad". In 2002,', ``` Doing `k=1` indicates the higher the outputted number, the better the match, so the metric should not be L2 distance. However, my manually computed inner product (80.6) has a discrepancy with the reported (76.2). Perhaps, this has to do with me using the `compressed` embeddings? ### Expected behavior ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # METRIC_INNER_PRODUCT ``` ### Environment info - `datasets` version: 2.12.0 - Platform: Linux-4.18.0-477.13.1.el8_8.x86_64-x86_64-with-glibc2.28 - Python version: 3.9.16 - Huggingface_hub version: 0.14.1 - PyArrow version: 12.0.0 - Pandas version: 2.0.1
23
Documentation: wiki_dpr Dataset has no metric_type for Faiss Index ### Describe the bug After loading `wiki_dpr` using: ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # prints nothing because the value is None ``` the index does not have a defined `metric_type`. This is an issue because I do not know how the `scores` are being computed for `get_nearest_examples()`. ### Steps to reproduce the bug System: Python 3.9.16, Transformers 4.30.2, WSL After loading `wiki_dpr` using: ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # prints nothing because the value is None ``` the index does not have a defined `metric_type`. This is an issue because I do not know how the `scores` are being computed for `get_nearest_examples()`. ```py from transformers import DPRQuestionEncoder, DPRContextEncoder, DPRQuestionEncoderTokenizer, DPRContextEncoderTokenizer tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-multiset-base") encoder = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-multiset-base") def encode_question(query, tokenizer=tokenizer, encoder=encoder): inputs = tokenizer(query, return_tensors='pt') question_embedding = encoder(**inputs)[0].detach().numpy() return question_embedding def get_knn(query, k=5, tokenizer=tokenizer, encoder=encoder, verbose=False): enc_question = encode_question(query, tokenizer, encoder) topk_results = ds.get_nearest_examples(index_name='embeddings', query=enc_question, k=k) a = torch.tensor(enc_question[0]).reshape(768) b = torch.tensor(topk_results.examples['embeddings'][0]) print(a.shape, b.shape) print(torch.dot(a, b)) print((a-b).pow(2).sum()) return topk_results ``` The [FAISS documentation](https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances) suggests the metric is usually L2 distance (without the square root) or the inner product. I compute both for the sample query: ```py query = """ it catapulted into popular culture along with a line of action figures and other toys by Bandai.[2] By 2001, the media franchise had generated over $6 billion in toy sales. Despite initial criticism that its action violence targeted child audiences, the franchise has been commercially successful.""" get_knn(query,k=5) ``` Here, I get dot product of 80.6020 and L2 distance of 77.6616 and ```py NearestExamplesResults(scores=array([76.20431 , 75.312416, 74.945404, 74.866394, 74.68506 ], dtype=float32), examples={'id': ['3081096', '2004811', '8908258', '9594124', '286575'], 'text': ['actors, resulting in the "Power Rangers" franchise which has continued since then into sequel TV series (with "Power Rangers Beast Morphers" set to premiere in 2019), comic books, video games, and three feature films, with a further cinematic universe planned. Following from the success of "Power Rangers", Saban acquired the rights to more of Toei\'s library, creating "VR Troopers" and "Big Bad Beetleborgs" from several Metal Hero Series shows and "Masked Rider" from Kamen Rider Series footage. DIC Entertainment joined this boom by acquiring the rights to "Gridman the Hyper Agent" and turning it into "Superhuman Samurai Syber-Squad". In 2002,', ``` Doing `k=1` indicates the higher the outputted number, the better the match, so the metric should not be L2 distance. However, my manually computed inner product (80.6) has a discrepancy with the reported (76.2). Perhaps, this has to do with me using the `compressed` embeddings? ### Expected behavior ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # METRIC_INNER_PRODUCT ``` ### Environment info - `datasets` version: 2.12.0 - Platform: Linux-4.18.0-477.13.1.el8_8.x86_64-x86_64-with-glibc2.28 - Python version: 3.9.16 - Huggingface_hub version: 0.14.1 - PyArrow version: 12.0.0 - Pandas version: 2.0.1 Hi! You can do `ds.get_index("embeddings").faiss_index.metric_type` to get the metric type and then match the result with the FAISS metric [enum](https://github.com/facebookresearch/faiss/blob/43d86e30736ede853c384b24667fc3ab897d6ba9/faiss/MetricType.h#L22-L36) (should be L2).
https://github.com/huggingface/datasets/issues/6011
Documentation: wiki_dpr Dataset has no metric_type for Faiss Index
Ah! Thank you for pointing this out. FYI: the enum indicates it's using the inner product. Using `torch.inner` or `torch.dot` still produces a discrepancy compared to the built-in score. I think this is because of the compression/quantization that occurs with the FAISS index.
### Describe the bug After loading `wiki_dpr` using: ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # prints nothing because the value is None ``` the index does not have a defined `metric_type`. This is an issue because I do not know how the `scores` are being computed for `get_nearest_examples()`. ### Steps to reproduce the bug System: Python 3.9.16, Transformers 4.30.2, WSL After loading `wiki_dpr` using: ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # prints nothing because the value is None ``` the index does not have a defined `metric_type`. This is an issue because I do not know how the `scores` are being computed for `get_nearest_examples()`. ```py from transformers import DPRQuestionEncoder, DPRContextEncoder, DPRQuestionEncoderTokenizer, DPRContextEncoderTokenizer tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-multiset-base") encoder = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-multiset-base") def encode_question(query, tokenizer=tokenizer, encoder=encoder): inputs = tokenizer(query, return_tensors='pt') question_embedding = encoder(**inputs)[0].detach().numpy() return question_embedding def get_knn(query, k=5, tokenizer=tokenizer, encoder=encoder, verbose=False): enc_question = encode_question(query, tokenizer, encoder) topk_results = ds.get_nearest_examples(index_name='embeddings', query=enc_question, k=k) a = torch.tensor(enc_question[0]).reshape(768) b = torch.tensor(topk_results.examples['embeddings'][0]) print(a.shape, b.shape) print(torch.dot(a, b)) print((a-b).pow(2).sum()) return topk_results ``` The [FAISS documentation](https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances) suggests the metric is usually L2 distance (without the square root) or the inner product. I compute both for the sample query: ```py query = """ it catapulted into popular culture along with a line of action figures and other toys by Bandai.[2] By 2001, the media franchise had generated over $6 billion in toy sales. Despite initial criticism that its action violence targeted child audiences, the franchise has been commercially successful.""" get_knn(query,k=5) ``` Here, I get dot product of 80.6020 and L2 distance of 77.6616 and ```py NearestExamplesResults(scores=array([76.20431 , 75.312416, 74.945404, 74.866394, 74.68506 ], dtype=float32), examples={'id': ['3081096', '2004811', '8908258', '9594124', '286575'], 'text': ['actors, resulting in the "Power Rangers" franchise which has continued since then into sequel TV series (with "Power Rangers Beast Morphers" set to premiere in 2019), comic books, video games, and three feature films, with a further cinematic universe planned. Following from the success of "Power Rangers", Saban acquired the rights to more of Toei\'s library, creating "VR Troopers" and "Big Bad Beetleborgs" from several Metal Hero Series shows and "Masked Rider" from Kamen Rider Series footage. DIC Entertainment joined this boom by acquiring the rights to "Gridman the Hyper Agent" and turning it into "Superhuman Samurai Syber-Squad". In 2002,', ``` Doing `k=1` indicates the higher the outputted number, the better the match, so the metric should not be L2 distance. However, my manually computed inner product (80.6) has a discrepancy with the reported (76.2). Perhaps, this has to do with me using the `compressed` embeddings? ### Expected behavior ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # METRIC_INNER_PRODUCT ``` ### Environment info - `datasets` version: 2.12.0 - Platform: Linux-4.18.0-477.13.1.el8_8.x86_64-x86_64-with-glibc2.28 - Python version: 3.9.16 - Huggingface_hub version: 0.14.1 - PyArrow version: 12.0.0 - Pandas version: 2.0.1
43
Documentation: wiki_dpr Dataset has no metric_type for Faiss Index ### Describe the bug After loading `wiki_dpr` using: ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # prints nothing because the value is None ``` the index does not have a defined `metric_type`. This is an issue because I do not know how the `scores` are being computed for `get_nearest_examples()`. ### Steps to reproduce the bug System: Python 3.9.16, Transformers 4.30.2, WSL After loading `wiki_dpr` using: ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # prints nothing because the value is None ``` the index does not have a defined `metric_type`. This is an issue because I do not know how the `scores` are being computed for `get_nearest_examples()`. ```py from transformers import DPRQuestionEncoder, DPRContextEncoder, DPRQuestionEncoderTokenizer, DPRContextEncoderTokenizer tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-multiset-base") encoder = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-multiset-base") def encode_question(query, tokenizer=tokenizer, encoder=encoder): inputs = tokenizer(query, return_tensors='pt') question_embedding = encoder(**inputs)[0].detach().numpy() return question_embedding def get_knn(query, k=5, tokenizer=tokenizer, encoder=encoder, verbose=False): enc_question = encode_question(query, tokenizer, encoder) topk_results = ds.get_nearest_examples(index_name='embeddings', query=enc_question, k=k) a = torch.tensor(enc_question[0]).reshape(768) b = torch.tensor(topk_results.examples['embeddings'][0]) print(a.shape, b.shape) print(torch.dot(a, b)) print((a-b).pow(2).sum()) return topk_results ``` The [FAISS documentation](https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances) suggests the metric is usually L2 distance (without the square root) or the inner product. I compute both for the sample query: ```py query = """ it catapulted into popular culture along with a line of action figures and other toys by Bandai.[2] By 2001, the media franchise had generated over $6 billion in toy sales. Despite initial criticism that its action violence targeted child audiences, the franchise has been commercially successful.""" get_knn(query,k=5) ``` Here, I get dot product of 80.6020 and L2 distance of 77.6616 and ```py NearestExamplesResults(scores=array([76.20431 , 75.312416, 74.945404, 74.866394, 74.68506 ], dtype=float32), examples={'id': ['3081096', '2004811', '8908258', '9594124', '286575'], 'text': ['actors, resulting in the "Power Rangers" franchise which has continued since then into sequel TV series (with "Power Rangers Beast Morphers" set to premiere in 2019), comic books, video games, and three feature films, with a further cinematic universe planned. Following from the success of "Power Rangers", Saban acquired the rights to more of Toei\'s library, creating "VR Troopers" and "Big Bad Beetleborgs" from several Metal Hero Series shows and "Masked Rider" from Kamen Rider Series footage. DIC Entertainment joined this boom by acquiring the rights to "Gridman the Hyper Agent" and turning it into "Superhuman Samurai Syber-Squad". In 2002,', ``` Doing `k=1` indicates the higher the outputted number, the better the match, so the metric should not be L2 distance. However, my manually computed inner product (80.6) has a discrepancy with the reported (76.2). Perhaps, this has to do with me using the `compressed` embeddings? ### Expected behavior ```py ds = load_dataset(path='wiki_dpr', name='psgs_w100.multiset.compressed', split='train') print(ds.get_index("embeddings").metric_type) # METRIC_INNER_PRODUCT ``` ### Environment info - `datasets` version: 2.12.0 - Platform: Linux-4.18.0-477.13.1.el8_8.x86_64-x86_64-with-glibc2.28 - Python version: 3.9.16 - Huggingface_hub version: 0.14.1 - PyArrow version: 12.0.0 - Pandas version: 2.0.1 Ah! Thank you for pointing this out. FYI: the enum indicates it's using the inner product. Using `torch.inner` or `torch.dot` still produces a discrepancy compared to the built-in score. I think this is because of the compression/quantization that occurs with the FAISS index.
https://github.com/huggingface/datasets/issues/6010
Improve `Dataset`'s string representation
Yes, feel free to work on this. You can check the PyArrow Table `__repr__` and Polars DataFrame `__repr__`/`_repr_html_` implementations for some pointers/ideas.
Currently, `Dataset.__repr__` outputs a dataset's column names and the number of rows. We could improve it by printing its features and the first few rows. We should also implement `_repr_html_` to have a rich HTML representation in notebooks/Streamlit.
22
Improve `Dataset`'s string representation Currently, `Dataset.__repr__` outputs a dataset's column names and the number of rows. We could improve it by printing its features and the first few rows. We should also implement `_repr_html_` to have a rich HTML representation in notebooks/Streamlit. Yes, feel free to work on this. You can check the PyArrow Table `__repr__` and Polars DataFrame `__repr__`/`_repr_html_` implementations for some pointers/ideas.
https://github.com/huggingface/datasets/issues/6008
Dataset.from_generator consistently freezes at ~1000 rows
By default, we write data to disk (so it can be memory-mapped) every 1000 rows/samples. You can control this with the `writer_batch_size` parameter. Also, when working with fixed-size arrays, the `ArrayXD` feature types yield better performance (e.g., in your case, `features=datasets.Features({"i": datasets.Array3D(shape=(512,512,3), dtype="float32")})` should be faster). Our support for multi-dim arrays could be better, and we plan to improve it as part of https://github.com/huggingface/datasets/issues/5272.
### Describe the bug Whenever I try to create a dataset which contains images using `Dataset.from_generator`, it freezes around 996 rows. I suppose it has something to do with memory consumption, but there's more memory available. I Somehow it worked a few times but mostly this makes the datasets library much more cumbersome to work with because generators are the easiest way to turn an existing dataset into a Hugging Face dataset. I've let it run in the frozen state for way longer than it can possibly take to load the actual dataset. Let me know if you have ideas how to resolve it! ### Steps to reproduce the bug ```python from datasets import Dataset import numpy as np def gen(): for row in range(10000): yield {"i": np.random.rand(512, 512, 3)} Dataset.from_generator(gen) # -> 90% of the time gets stuck around 1000 rows ``` ### Expected behavior Should continue and go through all the examples yielded by the generator, or at least throw an error or somehow communicate what's going on. ### Environment info - `datasets` version: 2.8.0 - Platform: Linux-5.15.0-52-generic-x86_64-with-glibc2.29 - Python version: 3.8.10 - PyArrow version: 12.0.1 - Pandas version: 1.5.1
64
Dataset.from_generator consistently freezes at ~1000 rows ### Describe the bug Whenever I try to create a dataset which contains images using `Dataset.from_generator`, it freezes around 996 rows. I suppose it has something to do with memory consumption, but there's more memory available. I Somehow it worked a few times but mostly this makes the datasets library much more cumbersome to work with because generators are the easiest way to turn an existing dataset into a Hugging Face dataset. I've let it run in the frozen state for way longer than it can possibly take to load the actual dataset. Let me know if you have ideas how to resolve it! ### Steps to reproduce the bug ```python from datasets import Dataset import numpy as np def gen(): for row in range(10000): yield {"i": np.random.rand(512, 512, 3)} Dataset.from_generator(gen) # -> 90% of the time gets stuck around 1000 rows ``` ### Expected behavior Should continue and go through all the examples yielded by the generator, or at least throw an error or somehow communicate what's going on. ### Environment info - `datasets` version: 2.8.0 - Platform: Linux-5.15.0-52-generic-x86_64-with-glibc2.29 - Python version: 3.8.10 - PyArrow version: 12.0.1 - Pandas version: 1.5.1 By default, we write data to disk (so it can be memory-mapped) every 1000 rows/samples. You can control this with the `writer_batch_size` parameter. Also, when working with fixed-size arrays, the `ArrayXD` feature types yield better performance (e.g., in your case, `features=datasets.Features({"i": datasets.Array3D(shape=(512,512,3), dtype="float32")})` should be faster). Our support for multi-dim arrays could be better, and we plan to improve it as part of https://github.com/huggingface/datasets/issues/5272.
https://github.com/huggingface/datasets/issues/6008
Dataset.from_generator consistently freezes at ~1000 rows
> By default, we write data to disk (so it can be memory-mapped) every 1000 rows/samples. You can control this with the `writer_batch_size` parameter. Also, when working with fixed-size arrays, the `ArrayXD` feature types yield better performance (e.g., in your case, `features=datasets.Features({"i": datasets.Array3D(shape=(512,512,3), dtype="float32")})` should be faster). > > Our support for multi-dim arrays could be better, and we plan to improve it as part of #5272. Thanks for the explanation! The Image array was just for demonstration, I use PIL Images in practice. Does that make a difference? What's the best approach for a dataset with PIL Images as rows?
### Describe the bug Whenever I try to create a dataset which contains images using `Dataset.from_generator`, it freezes around 996 rows. I suppose it has something to do with memory consumption, but there's more memory available. I Somehow it worked a few times but mostly this makes the datasets library much more cumbersome to work with because generators are the easiest way to turn an existing dataset into a Hugging Face dataset. I've let it run in the frozen state for way longer than it can possibly take to load the actual dataset. Let me know if you have ideas how to resolve it! ### Steps to reproduce the bug ```python from datasets import Dataset import numpy as np def gen(): for row in range(10000): yield {"i": np.random.rand(512, 512, 3)} Dataset.from_generator(gen) # -> 90% of the time gets stuck around 1000 rows ``` ### Expected behavior Should continue and go through all the examples yielded by the generator, or at least throw an error or somehow communicate what's going on. ### Environment info - `datasets` version: 2.8.0 - Platform: Linux-5.15.0-52-generic-x86_64-with-glibc2.29 - Python version: 3.8.10 - PyArrow version: 12.0.1 - Pandas version: 1.5.1
101
Dataset.from_generator consistently freezes at ~1000 rows ### Describe the bug Whenever I try to create a dataset which contains images using `Dataset.from_generator`, it freezes around 996 rows. I suppose it has something to do with memory consumption, but there's more memory available. I Somehow it worked a few times but mostly this makes the datasets library much more cumbersome to work with because generators are the easiest way to turn an existing dataset into a Hugging Face dataset. I've let it run in the frozen state for way longer than it can possibly take to load the actual dataset. Let me know if you have ideas how to resolve it! ### Steps to reproduce the bug ```python from datasets import Dataset import numpy as np def gen(): for row in range(10000): yield {"i": np.random.rand(512, 512, 3)} Dataset.from_generator(gen) # -> 90% of the time gets stuck around 1000 rows ``` ### Expected behavior Should continue and go through all the examples yielded by the generator, or at least throw an error or somehow communicate what's going on. ### Environment info - `datasets` version: 2.8.0 - Platform: Linux-5.15.0-52-generic-x86_64-with-glibc2.29 - Python version: 3.8.10 - PyArrow version: 12.0.1 - Pandas version: 1.5.1 > By default, we write data to disk (so it can be memory-mapped) every 1000 rows/samples. You can control this with the `writer_batch_size` parameter. Also, when working with fixed-size arrays, the `ArrayXD` feature types yield better performance (e.g., in your case, `features=datasets.Features({"i": datasets.Array3D(shape=(512,512,3), dtype="float32")})` should be faster). > > Our support for multi-dim arrays could be better, and we plan to improve it as part of #5272. Thanks for the explanation! The Image array was just for demonstration, I use PIL Images in practice. Does that make a difference? What's the best approach for a dataset with PIL Images as rows?
https://github.com/huggingface/datasets/issues/6007
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset
This error means that one of the int32 (`Value("int32")`) columns in the dataset has a value that is out of the valid (int32) range. I'll open a PR to print the name of a problematic column to make debugging such errors easier.
### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5
42
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset ### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5 This error means that one of the int32 (`Value("int32")`) columns in the dataset has a value that is out of the valid (int32) range. I'll open a PR to print the name of a problematic column to make debugging such errors easier.
https://github.com/huggingface/datasets/issues/6007
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset
I am afraid int32 is not the reason for this error. I have submitted a commit to use int64 for all ints in the dataset: https://huggingface.co/datasets/liwu/MNBVC/commit/857ac00d9eab96a6708ad6a82bd9001686042a9e and I have updated my env to the latest datasets release: Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.13.1 - Platform: macOS-13.2.1-arm64-arm-64bit - Python version: 3.11.2 - Huggingface_hub version: 0.13.4 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 But the error still exist ``` Downloading and preparing dataset mnbvc/news_peoples_daily to /Users/silver/.cache/huggingface/datasets/liwu___mnbvc/news_peoples_daily/0.0.1/ee380f6309fe9b8b0d1fb14d77118f132444f22c8c4b28bf5c1645312688e051... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 12/12 [00:00<00:00, 9070.40it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 12/12 [00:00<00:00, 2697.16it/s] --------------------------------------------------------------------------- OverflowError Traceback (most recent call last) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1647, in GeneratorBasedBuilder._prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id) 1646 example = self.info.features.encode_example(record) if self.info.features is not None else record -> 1647 writer.write(example, key) 1648 num_examples_progress_update += 1 File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:490, in ArrowWriter.write(self, example, key, writer_batch_size) 488 self.hkey_record = [] --> 490 self.write_examples_on_file() File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:448, in ArrowWriter.write_examples_on_file(self) 444 batch_examples[col] = [ 445 row[0][col].to_pylist()[0] if isinstance(row[0][col], (pa.Array, pa.ChunkedArray)) else row[0][col] 446 for row in self.current_examples 447 ] --> 448 self.write_batch(batch_examples=batch_examples) 449 self.current_examples = [] File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:553, in ArrowWriter.write_batch(self, batch_examples, writer_batch_size) 552 typed_sequence = OptimizedTypedSequence(col_values, type=col_type, try_type=col_try_type, col=col) --> 553 arrays.append(pa.array(typed_sequence)) 554 inferred_features[col] = typed_sequence.get_inferred_type() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:236, in pyarrow.lib.array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:110, in pyarrow.lib._handle_arrow_array_protocol() File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:189, in TypedSequence.__arrow_array__(self, type) 188 trying_cast_to_python_objects = True --> 189 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 190 # use smaller integer precisions if possible File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:320, in pyarrow.lib.array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:39, in pyarrow.lib._sequence_to_array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/error.pxi:144, in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1656, in GeneratorBasedBuilder._prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id) 1655 num_shards = shard_id + 1 -> 1656 num_examples, num_bytes = writer.finalize() 1657 writer.close() File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:584, in ArrowWriter.finalize(self, close_stream) 583 self.hkey_record = [] --> 584 self.write_examples_on_file() 585 # If schema is known, infer features even if no examples were written File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:448, in ArrowWriter.write_examples_on_file(self) 444 batch_examples[col] = [ 445 row[0][col].to_pylist()[0] if isinstance(row[0][col], (pa.Array, pa.ChunkedArray)) else row[0][col] 446 for row in self.current_examples 447 ] --> 448 self.write_batch(batch_examples=batch_examples) 449 self.current_examples = [] File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:553, in ArrowWriter.write_batch(self, batch_examples, writer_batch_size) 552 typed_sequence = OptimizedTypedSequence(col_values, type=col_type, try_type=col_try_type, col=col) --> 553 arrays.append(pa.array(typed_sequence)) 554 inferred_features[col] = typed_sequence.get_inferred_type() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:236, in pyarrow.lib.array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:110, in pyarrow.lib._handle_arrow_array_protocol() File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:189, in TypedSequence.__arrow_array__(self, type) 188 trying_cast_to_python_objects = True --> 189 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 190 # use smaller integer precisions if possible File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:320, in pyarrow.lib.array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:39, in pyarrow.lib._sequence_to_array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/error.pxi:144, in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long The above exception was the direct cause of the following exception: DatasetGenerationError Traceback (most recent call last) Cell In[2], line 1 ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') File ~/git/venv/lib/python3.11/site-packages/datasets/load.py:1809, 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, use_auth_token, task, streaming, num_proc, storage_options, **config_kwargs) 1806 try_from_hf_gcs = path not in _PACKAGED_DATASETS_MODULES 1808 # Download and prepare data -> 1809 builder_instance.download_and_prepare( 1810 download_config=download_config, 1811 download_mode=download_mode, 1812 verification_mode=verification_mode, 1813 try_from_hf_gcs=try_from_hf_gcs, 1814 num_proc=num_proc, 1815 storage_options=storage_options, 1816 ) 1818 # Build dataset for splits 1819 keep_in_memory = ( 1820 keep_in_memory if keep_in_memory is not None else is_small_dataset(builder_instance.info.dataset_size) 1821 ) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:909, in DatasetBuilder.download_and_prepare(self, output_dir, download_config, download_mode, verification_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, file_format, max_shard_size, num_proc, storage_options, **download_and_prepare_kwargs) 907 if num_proc is not None: 908 prepare_split_kwargs["num_proc"] = num_proc --> 909 self._download_and_prepare( 910 dl_manager=dl_manager, 911 verification_mode=verification_mode, 912 **prepare_split_kwargs, 913 **download_and_prepare_kwargs, 914 ) 915 # Sync info 916 self.info.dataset_size = sum(split.num_bytes for split in self.info.splits.values()) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1670, in GeneratorBasedBuilder._download_and_prepare(self, dl_manager, verification_mode, **prepare_splits_kwargs) 1669 def _download_and_prepare(self, dl_manager, verification_mode, **prepare_splits_kwargs): -> 1670 super()._download_and_prepare( 1671 dl_manager, 1672 verification_mode, 1673 check_duplicate_keys=verification_mode == VerificationMode.BASIC_CHECKS 1674 or verification_mode == VerificationMode.ALL_CHECKS, 1675 **prepare_splits_kwargs, 1676 ) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1004, in DatasetBuilder._download_and_prepare(self, dl_manager, verification_mode, **prepare_split_kwargs) 1000 split_dict.add(split_generator.split_info) 1002 try: 1003 # Prepare split will record examples associated to the split -> 1004 self._prepare_split(split_generator, **prepare_split_kwargs) 1005 except OSError as e: 1006 raise OSError( 1007 "Cannot find data file. " 1008 + (self.manual_download_instructions or "") 1009 + "\nOriginal error:\n" 1010 + str(e) 1011 ) from None File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1508, in GeneratorBasedBuilder._prepare_split(self, split_generator, check_duplicate_keys, file_format, num_proc, max_shard_size) 1506 job_id = 0 1507 with pbar: -> 1508 for job_id, done, content in self._prepare_split_single( 1509 gen_kwargs=gen_kwargs, job_id=job_id, **_prepare_split_args 1510 ): 1511 if done: 1512 result = content File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1665, in GeneratorBasedBuilder._prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id) 1663 if isinstance(e, SchemaInferenceError) and e.__context__ is not None: 1664 e = e.__context__ -> 1665 raise DatasetGenerationError("An error occurred while generating the dataset") from e 1667 yield job_id, True, (total_num_examples, total_num_bytes, writer._features, num_shards, shard_lengths) DatasetGenerationError: An error occurred while generating the dataset ``` Besides, it works fine when I am using streamed dataset.
### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5
763
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset ### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5 I am afraid int32 is not the reason for this error. I have submitted a commit to use int64 for all ints in the dataset: https://huggingface.co/datasets/liwu/MNBVC/commit/857ac00d9eab96a6708ad6a82bd9001686042a9e and I have updated my env to the latest datasets release: Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.13.1 - Platform: macOS-13.2.1-arm64-arm-64bit - Python version: 3.11.2 - Huggingface_hub version: 0.13.4 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 But the error still exist ``` Downloading and preparing dataset mnbvc/news_peoples_daily to /Users/silver/.cache/huggingface/datasets/liwu___mnbvc/news_peoples_daily/0.0.1/ee380f6309fe9b8b0d1fb14d77118f132444f22c8c4b28bf5c1645312688e051... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 12/12 [00:00<00:00, 9070.40it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 12/12 [00:00<00:00, 2697.16it/s] --------------------------------------------------------------------------- OverflowError Traceback (most recent call last) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1647, in GeneratorBasedBuilder._prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id) 1646 example = self.info.features.encode_example(record) if self.info.features is not None else record -> 1647 writer.write(example, key) 1648 num_examples_progress_update += 1 File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:490, in ArrowWriter.write(self, example, key, writer_batch_size) 488 self.hkey_record = [] --> 490 self.write_examples_on_file() File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:448, in ArrowWriter.write_examples_on_file(self) 444 batch_examples[col] = [ 445 row[0][col].to_pylist()[0] if isinstance(row[0][col], (pa.Array, pa.ChunkedArray)) else row[0][col] 446 for row in self.current_examples 447 ] --> 448 self.write_batch(batch_examples=batch_examples) 449 self.current_examples = [] File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:553, in ArrowWriter.write_batch(self, batch_examples, writer_batch_size) 552 typed_sequence = OptimizedTypedSequence(col_values, type=col_type, try_type=col_try_type, col=col) --> 553 arrays.append(pa.array(typed_sequence)) 554 inferred_features[col] = typed_sequence.get_inferred_type() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:236, in pyarrow.lib.array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:110, in pyarrow.lib._handle_arrow_array_protocol() File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:189, in TypedSequence.__arrow_array__(self, type) 188 trying_cast_to_python_objects = True --> 189 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 190 # use smaller integer precisions if possible File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:320, in pyarrow.lib.array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:39, in pyarrow.lib._sequence_to_array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/error.pxi:144, in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1656, in GeneratorBasedBuilder._prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id) 1655 num_shards = shard_id + 1 -> 1656 num_examples, num_bytes = writer.finalize() 1657 writer.close() File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:584, in ArrowWriter.finalize(self, close_stream) 583 self.hkey_record = [] --> 584 self.write_examples_on_file() 585 # If schema is known, infer features even if no examples were written File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:448, in ArrowWriter.write_examples_on_file(self) 444 batch_examples[col] = [ 445 row[0][col].to_pylist()[0] if isinstance(row[0][col], (pa.Array, pa.ChunkedArray)) else row[0][col] 446 for row in self.current_examples 447 ] --> 448 self.write_batch(batch_examples=batch_examples) 449 self.current_examples = [] File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:553, in ArrowWriter.write_batch(self, batch_examples, writer_batch_size) 552 typed_sequence = OptimizedTypedSequence(col_values, type=col_type, try_type=col_try_type, col=col) --> 553 arrays.append(pa.array(typed_sequence)) 554 inferred_features[col] = typed_sequence.get_inferred_type() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:236, in pyarrow.lib.array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:110, in pyarrow.lib._handle_arrow_array_protocol() File ~/git/venv/lib/python3.11/site-packages/datasets/arrow_writer.py:189, in TypedSequence.__arrow_array__(self, type) 188 trying_cast_to_python_objects = True --> 189 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 190 # use smaller integer precisions if possible File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:320, in pyarrow.lib.array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/array.pxi:39, in pyarrow.lib._sequence_to_array() File ~/git/venv/lib/python3.11/site-packages/pyarrow/error.pxi:144, in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long The above exception was the direct cause of the following exception: DatasetGenerationError Traceback (most recent call last) Cell In[2], line 1 ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') File ~/git/venv/lib/python3.11/site-packages/datasets/load.py:1809, 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, use_auth_token, task, streaming, num_proc, storage_options, **config_kwargs) 1806 try_from_hf_gcs = path not in _PACKAGED_DATASETS_MODULES 1808 # Download and prepare data -> 1809 builder_instance.download_and_prepare( 1810 download_config=download_config, 1811 download_mode=download_mode, 1812 verification_mode=verification_mode, 1813 try_from_hf_gcs=try_from_hf_gcs, 1814 num_proc=num_proc, 1815 storage_options=storage_options, 1816 ) 1818 # Build dataset for splits 1819 keep_in_memory = ( 1820 keep_in_memory if keep_in_memory is not None else is_small_dataset(builder_instance.info.dataset_size) 1821 ) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:909, in DatasetBuilder.download_and_prepare(self, output_dir, download_config, download_mode, verification_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, file_format, max_shard_size, num_proc, storage_options, **download_and_prepare_kwargs) 907 if num_proc is not None: 908 prepare_split_kwargs["num_proc"] = num_proc --> 909 self._download_and_prepare( 910 dl_manager=dl_manager, 911 verification_mode=verification_mode, 912 **prepare_split_kwargs, 913 **download_and_prepare_kwargs, 914 ) 915 # Sync info 916 self.info.dataset_size = sum(split.num_bytes for split in self.info.splits.values()) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1670, in GeneratorBasedBuilder._download_and_prepare(self, dl_manager, verification_mode, **prepare_splits_kwargs) 1669 def _download_and_prepare(self, dl_manager, verification_mode, **prepare_splits_kwargs): -> 1670 super()._download_and_prepare( 1671 dl_manager, 1672 verification_mode, 1673 check_duplicate_keys=verification_mode == VerificationMode.BASIC_CHECKS 1674 or verification_mode == VerificationMode.ALL_CHECKS, 1675 **prepare_splits_kwargs, 1676 ) File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1004, in DatasetBuilder._download_and_prepare(self, dl_manager, verification_mode, **prepare_split_kwargs) 1000 split_dict.add(split_generator.split_info) 1002 try: 1003 # Prepare split will record examples associated to the split -> 1004 self._prepare_split(split_generator, **prepare_split_kwargs) 1005 except OSError as e: 1006 raise OSError( 1007 "Cannot find data file. " 1008 + (self.manual_download_instructions or "") 1009 + "\nOriginal error:\n" 1010 + str(e) 1011 ) from None File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1508, in GeneratorBasedBuilder._prepare_split(self, split_generator, check_duplicate_keys, file_format, num_proc, max_shard_size) 1506 job_id = 0 1507 with pbar: -> 1508 for job_id, done, content in self._prepare_split_single( 1509 gen_kwargs=gen_kwargs, job_id=job_id, **_prepare_split_args 1510 ): 1511 if done: 1512 result = content File ~/git/venv/lib/python3.11/site-packages/datasets/builder.py:1665, in GeneratorBasedBuilder._prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id) 1663 if isinstance(e, SchemaInferenceError) and e.__context__ is not None: 1664 e = e.__context__ -> 1665 raise DatasetGenerationError("An error occurred while generating the dataset") from e 1667 yield job_id, True, (total_num_examples, total_num_bytes, writer._features, num_shards, shard_lengths) DatasetGenerationError: An error occurred while generating the dataset ``` Besides, it works fine when I am using streamed dataset.
https://github.com/huggingface/datasets/issues/6007
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset
`simhash` is the problematic column - it has values such as `18329103420363166823` that are out of the int64 range. You can fix this by setting the feature type to `Value("string")` (it's advised to use this type for hash values in general) > Besides, it works fine when I am using streamed dataset. Streaming yields Python dictionaries from the script without converting them to the Arrow representation, as this conversion step is not that cheap performance-wise.
### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5
75
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset ### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5 `simhash` is the problematic column - it has values such as `18329103420363166823` that are out of the int64 range. You can fix this by setting the feature type to `Value("string")` (it's advised to use this type for hash values in general) > Besides, it works fine when I am using streamed dataset. Streaming yields Python dictionaries from the script without converting them to the Arrow representation, as this conversion step is not that cheap performance-wise.
https://github.com/huggingface/datasets/issues/6007
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset
i am using uint64 for simhash uint64 ranges up to about 3.69E19. 18329103420363166823 is less than this value. moreover, our simhash algorithm use 64 bits. it should fit in uint64.
### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5
30
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset ### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5 i am using uint64 for simhash uint64 ranges up to about 3.69E19. 18329103420363166823 is less than this value. moreover, our simhash algorithm use 64 bits. it should fit in uint64.
https://github.com/huggingface/datasets/issues/6007
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset
You are right. I overlooked the feature type. This is a reproducer: ```python import pyarrow as pa from datasets.arrow_writer import TypedSequence pa.array(TypedSequence([18329103420363166823], type=Value("uint64"))) ``` `pa.array([18329103420363166823])` also fails with the same error, so it seems PyArrow does not always infer the correct type as NumPy does (`uint64` in this case). I'll report this issue in the Arrow repo. `pa.array([18329103420363166823], pa.uint64)` works, so maybe we can implement a temporary fix (supporting complex input such as `[{"image": pil_image, "num": uint64_value}]` would be hard though). In the meantime, you should be able to bypass this error by returning the `simhash` values as NumPy scalars in the script: ```python def _generate_examples(self, ...): ... yield {..., "simhash": np.uint64(simhash), ...} ```
### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5
114
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset ### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5 You are right. I overlooked the feature type. This is a reproducer: ```python import pyarrow as pa from datasets.arrow_writer import TypedSequence pa.array(TypedSequence([18329103420363166823], type=Value("uint64"))) ``` `pa.array([18329103420363166823])` also fails with the same error, so it seems PyArrow does not always infer the correct type as NumPy does (`uint64` in this case). I'll report this issue in the Arrow repo. `pa.array([18329103420363166823], pa.uint64)` works, so maybe we can implement a temporary fix (supporting complex input such as `[{"image": pil_image, "num": uint64_value}]` would be hard though). In the meantime, you should be able to bypass this error by returning the `simhash` values as NumPy scalars in the script: ```python def _generate_examples(self, ...): ... yield {..., "simhash": np.uint64(simhash), ...} ```
https://github.com/huggingface/datasets/issues/6007
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset
Thank you for checking this issue in detail. However, it seems that using `np.uint64(simhash)` does not work. The same issue still exists. https://huggingface.co/datasets/liwu/MNBVC/commit/1e44f1e400b7e61052647d44c99cdae3bae9c830 Anyway, we decide to use string type for these simhash values. Hope pyarrow can fix their bug soon.
### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5
41
Get an error "OverflowError: Python int too large to convert to C long" when loading a large dataset ### Describe the bug When load a large dataset with the following code ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ``` We encountered the error: "OverflowError: Python int too large to convert to C long" The error look something like: ``` OverflowError: Python int too large to convert to C long During handling of the above exception, another exception occurred: OverflowError Traceback (most recent call last) <ipython-input-7-0ed8700e662d> in <module> ----> 1 dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', cache_dir='/sfs/MNBVC/.cache/') /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, **config_kwargs) 1749 ignore_verifications=ignore_verifications, 1750 try_from_hf_gcs=try_from_hf_gcs, -> 1751 use_auth_token=use_auth_token, 1752 ) 1753 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, base_path, use_auth_token, **download_and_prepare_kwargs) 703 if not downloaded_from_gcs: 704 self._download_and_prepare( --> 705 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 706 ) 707 # Sync info /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos) 1225 1226 def _download_and_prepare(self, dl_manager, verify_infos): -> 1227 super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos) 1228 1229 def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 791 try: 792 # Prepare split will record examples associated to the split --> 793 self._prepare_split(split_generator, **prepare_split_kwargs) 794 except OSError as e: 795 raise OSError( /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/builder.py in _prepare_split(self, split_generator, check_duplicate_keys) 1219 writer.write(example, key) 1220 finally: -> 1221 num_examples, num_bytes = writer.finalize() 1222 1223 split_generator.split_info.num_examples = num_examples /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in finalize(self, close_stream) 536 # Re-intializing to empty list for next batch 537 self.hkey_record = [] --> 538 self.write_examples_on_file() 539 if self.pa_writer is None: 540 if self.schema: /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_examples_on_file(self) 407 # Since current_examples contains (example, key) tuples 408 batch_examples[col] = [row[0][col] for row in self.current_examples] --> 409 self.write_batch(batch_examples=batch_examples) 410 self.current_examples = [] 411 /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 506 col_try_type = try_features[col] if try_features is not None and col in try_features else None 507 typed_sequence = OptimizedTypedSequence(batch_examples[col], type=col_type, try_type=col_try_type, col=col) --> 508 arrays.append(pa.array(typed_sequence)) 509 inferred_features[col] = typed_sequence.get_inferred_type() 510 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._handle_arrow_array_protocol() /sfs/MNBVC/venv/lib64/python3.6/site-packages/datasets/arrow_writer.py in __arrow_array__(self, type) 180 else: 181 trying_cast_to_python_objects = True --> 182 out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) 183 # use smaller integer precisions if possible 184 if self.trying_int_optimization: /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib.array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/array.pxi in pyarrow.lib._sequence_to_array() /sfs/MNBVC/venv/lib64/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.pyarrow_internal_check_status() OverflowError: Python int too large to convert to C long ``` However, that dataset can be loaded in a streaming manner: ```python from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train', streaming=True) for i in dataset: pass # it work well ``` Another issue is reported in our dataset hub: https://huggingface.co/datasets/liwu/MNBVC/discussions/2 ### Steps to reproduce the bug from datasets import load_dataset dataset = load_dataset("liwu/MNBVC", 'news_peoples_daily', split='train') ### Expected behavior the dataset can be safely loaded ### Environment info - `datasets` version: 2.4.0 - Platform: Linux-3.10.0-1160.an7.x86_64-x86_64-with-centos-7.9 - Python version: 3.6.8 - PyArrow version: 6.0.1 - Pandas version: 1.1.5 Thank you for checking this issue in detail. However, it seems that using `np.uint64(simhash)` does not work. The same issue still exists. https://huggingface.co/datasets/liwu/MNBVC/commit/1e44f1e400b7e61052647d44c99cdae3bae9c830 Anyway, we decide to use string type for these simhash values. Hope pyarrow can fix their bug soon.
https://github.com/huggingface/datasets/issues/5997
extend the map function so it can wrap around long text that does not fit in the context window
I just noticed the [docs](https://github.com/huggingface/datasets/blob/main/src/datasets/arrow_dataset.py#L2881C11-L2881C200) say: >If batched is `True` and `batch_size` is `n > 1`, then the function takes a batch of `n` examples as input and can return a batch with `n` examples, or with an arbitrary number of examples. so maybe this is a bug then.
### Feature request I understand `dataset` provides a [`map`](https://github.com/huggingface/datasets/blob/main/src/datasets/arrow_dataset.py#L2849) function. This function in turn takes in a callable that is used to tokenize the text on which a model is trained. Frequently this text will not fit within a models's context window. In this case it would be useful to wrap around the text into multiple rows with each row fitting the model's context window. I tried to do it using this code as example which in turn I have borrowed from [here](https://stackoverflow.com/a/76343993/147530): ``` data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True) ``` but running the code gives me this error: ``` File "/llm/fine-tune.py", line 117, in <module> data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 580, in wrapper out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 545, in wrapper out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 3087, in map for rank, done, content in Dataset._map_single(**dataset_kwargs): File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 3480, in _map_single writer.write_batch(batch) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_writer.py", line 556, in write_batch pa_table = pa.Table.from_arrays(arrays, schema=schema) File "pyarrow/table.pxi", line 3798, in pyarrow.lib.Table.from_arrays File "pyarrow/table.pxi", line 2962, in pyarrow.lib.Table.validate File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status pyarrow.lib.ArrowInvalid: Column 1 named input_ids expected length 394 but got length 447 ``` The lambda function I have provided is correctly chopping up long text so it wraps around (and because of this 394 samples become 447 after wrap around) but the dataset `map` function does not like it. ### Motivation please see above ### Your contribution I'm afraid I don't have much knowledge to help
49
extend the map function so it can wrap around long text that does not fit in the context window ### Feature request I understand `dataset` provides a [`map`](https://github.com/huggingface/datasets/blob/main/src/datasets/arrow_dataset.py#L2849) function. This function in turn takes in a callable that is used to tokenize the text on which a model is trained. Frequently this text will not fit within a models's context window. In this case it would be useful to wrap around the text into multiple rows with each row fitting the model's context window. I tried to do it using this code as example which in turn I have borrowed from [here](https://stackoverflow.com/a/76343993/147530): ``` data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True) ``` but running the code gives me this error: ``` File "/llm/fine-tune.py", line 117, in <module> data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 580, in wrapper out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 545, in wrapper out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 3087, in map for rank, done, content in Dataset._map_single(**dataset_kwargs): File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 3480, in _map_single writer.write_batch(batch) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_writer.py", line 556, in write_batch pa_table = pa.Table.from_arrays(arrays, schema=schema) File "pyarrow/table.pxi", line 3798, in pyarrow.lib.Table.from_arrays File "pyarrow/table.pxi", line 2962, in pyarrow.lib.Table.validate File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status pyarrow.lib.ArrowInvalid: Column 1 named input_ids expected length 394 but got length 447 ``` The lambda function I have provided is correctly chopping up long text so it wraps around (and because of this 394 samples become 447 after wrap around) but the dataset `map` function does not like it. ### Motivation please see above ### Your contribution I'm afraid I don't have much knowledge to help I just noticed the [docs](https://github.com/huggingface/datasets/blob/main/src/datasets/arrow_dataset.py#L2881C11-L2881C200) say: >If batched is `True` and `batch_size` is `n > 1`, then the function takes a batch of `n` examples as input and can return a batch with `n` examples, or with an arbitrary number of examples. so maybe this is a bug then.
https://github.com/huggingface/datasets/issues/5997
extend the map function so it can wrap around long text that does not fit in the context window
All the values in a batch must be of the same length. So one solution is dropping all the input columns: ```python data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True, remove_columns=data.column_names) ``` Another is padding/transforming the input columns to the tokenizer output's length (447).
### Feature request I understand `dataset` provides a [`map`](https://github.com/huggingface/datasets/blob/main/src/datasets/arrow_dataset.py#L2849) function. This function in turn takes in a callable that is used to tokenize the text on which a model is trained. Frequently this text will not fit within a models's context window. In this case it would be useful to wrap around the text into multiple rows with each row fitting the model's context window. I tried to do it using this code as example which in turn I have borrowed from [here](https://stackoverflow.com/a/76343993/147530): ``` data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True) ``` but running the code gives me this error: ``` File "/llm/fine-tune.py", line 117, in <module> data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 580, in wrapper out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 545, in wrapper out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 3087, in map for rank, done, content in Dataset._map_single(**dataset_kwargs): File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 3480, in _map_single writer.write_batch(batch) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_writer.py", line 556, in write_batch pa_table = pa.Table.from_arrays(arrays, schema=schema) File "pyarrow/table.pxi", line 3798, in pyarrow.lib.Table.from_arrays File "pyarrow/table.pxi", line 2962, in pyarrow.lib.Table.validate File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status pyarrow.lib.ArrowInvalid: Column 1 named input_ids expected length 394 but got length 447 ``` The lambda function I have provided is correctly chopping up long text so it wraps around (and because of this 394 samples become 447 after wrap around) but the dataset `map` function does not like it. ### Motivation please see above ### Your contribution I'm afraid I don't have much knowledge to help
46
extend the map function so it can wrap around long text that does not fit in the context window ### Feature request I understand `dataset` provides a [`map`](https://github.com/huggingface/datasets/blob/main/src/datasets/arrow_dataset.py#L2849) function. This function in turn takes in a callable that is used to tokenize the text on which a model is trained. Frequently this text will not fit within a models's context window. In this case it would be useful to wrap around the text into multiple rows with each row fitting the model's context window. I tried to do it using this code as example which in turn I have borrowed from [here](https://stackoverflow.com/a/76343993/147530): ``` data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True) ``` but running the code gives me this error: ``` File "/llm/fine-tune.py", line 117, in <module> data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 580, in wrapper out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 545, in wrapper out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 3087, in map for rank, done, content in Dataset._map_single(**dataset_kwargs): File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 3480, in _map_single writer.write_batch(batch) File "/llm/.env/lib/python3.9/site-packages/datasets/arrow_writer.py", line 556, in write_batch pa_table = pa.Table.from_arrays(arrays, schema=schema) File "pyarrow/table.pxi", line 3798, in pyarrow.lib.Table.from_arrays File "pyarrow/table.pxi", line 2962, in pyarrow.lib.Table.validate File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status pyarrow.lib.ArrowInvalid: Column 1 named input_ids expected length 394 but got length 447 ``` The lambda function I have provided is correctly chopping up long text so it wraps around (and because of this 394 samples become 447 after wrap around) but the dataset `map` function does not like it. ### Motivation please see above ### Your contribution I'm afraid I don't have much knowledge to help All the values in a batch must be of the same length. So one solution is dropping all the input columns: ```python data = data.map(lambda samples: tokenizer(samples["text"], max_length=tokenizer.model_max_length, truncation=True, stride=4, return_overflowing_tokens=True), batched=True, remove_columns=data.column_names) ``` Another is padding/transforming the input columns to the tokenizer output's length (447).
https://github.com/huggingface/datasets/issues/5993
ValueError: Table schema does not match schema used to create file
We'll do a new release of `datasets` soon to make the fix available :) In the meantime you can use `datasets` from source (main)
### Describe the bug Saving a dataset as parquet fails with a `ValueError: Table schema does not match schema used to create file` if the dataset was obtained out of a `.select_columns()` call with columns selected out of order. ### Steps to reproduce the bug ```python import datasets dataset = datasets.Dataset.from_dict( { "x1": [1, 2, 3], "x2": [10, 11, 12], } ) ds = dataset.select_columns(["x2", "x1"]) ds.to_parquet("demo.parquet") ``` ```shell >>> ValueError: Table schema does not match schema used to create file: table: x2: int64 x1: int64 -- schema metadata -- huggingface: '{"info": {"features": {"x2": {"dtype": "int64", "_type": "V' + 53 vs. file: x1: int64 x2: int64 -- schema metadata -- huggingface: '{"info": {"features": {"x1": {"dtype": "int64", "_type": "V' + 53 ``` --- I think this is because after the `.select_columns()` call with out of order columns, the output dataset features' schema ends up being out of sync with the schema of the arrow table backing it. ```python ds.features.arrow_schema >>> x1: int64 x2: int64 -- schema metadata -- huggingface: '{"info": {"features": {"x1": {"dtype": "int64", "_type": "V' + 53 ds.data.schema >>> x2: int64 x1: int64 -- schema metadata -- huggingface: '{"info": {"features": {"x2": {"dtype": "int64", "_type": "V' + 53 ``` So when we call `.to_parquet()`, the call behind the scenes to `datasets.io.parquet.ParquetDatasetWriter(...).write()` which initialises the backend `pyarrow.parquet.ParquetWriter` with `schema = self.dataset.features.arrow_schema` triggers `pyarrow` on write when [it checks](https://github.com/apache/arrow/blob/11b140a734a516e436adaddaeb35d23f30dcce44/python/pyarrow/parquet/core.py#L1086-L1090) that the `ParquetWriter` schema matches the schema of the table being written πŸ™Œ https://github.com/huggingface/datasets/blob/6ed837325cb539a5deb99129e5ad181d0269e050/src/datasets/io/parquet.py#L139-L141 ### Expected behavior The dataset gets successfully saved as parquet. *In the same way as it does if saving it as csv: ```python import datasets dataset = datasets.Dataset.from_dict( { "x1": [1, 2, 3], "x2": [10, 11, 12], } ) ds = dataset.select_columns(["x2", "x1"]) ds.to_csv("demo.csv") ``` ### Environment info `python==3.11` `datasets==2.13.1`
24
ValueError: Table schema does not match schema used to create file ### Describe the bug Saving a dataset as parquet fails with a `ValueError: Table schema does not match schema used to create file` if the dataset was obtained out of a `.select_columns()` call with columns selected out of order. ### Steps to reproduce the bug ```python import datasets dataset = datasets.Dataset.from_dict( { "x1": [1, 2, 3], "x2": [10, 11, 12], } ) ds = dataset.select_columns(["x2", "x1"]) ds.to_parquet("demo.parquet") ``` ```shell >>> ValueError: Table schema does not match schema used to create file: table: x2: int64 x1: int64 -- schema metadata -- huggingface: '{"info": {"features": {"x2": {"dtype": "int64", "_type": "V' + 53 vs. file: x1: int64 x2: int64 -- schema metadata -- huggingface: '{"info": {"features": {"x1": {"dtype": "int64", "_type": "V' + 53 ``` --- I think this is because after the `.select_columns()` call with out of order columns, the output dataset features' schema ends up being out of sync with the schema of the arrow table backing it. ```python ds.features.arrow_schema >>> x1: int64 x2: int64 -- schema metadata -- huggingface: '{"info": {"features": {"x1": {"dtype": "int64", "_type": "V' + 53 ds.data.schema >>> x2: int64 x1: int64 -- schema metadata -- huggingface: '{"info": {"features": {"x2": {"dtype": "int64", "_type": "V' + 53 ``` So when we call `.to_parquet()`, the call behind the scenes to `datasets.io.parquet.ParquetDatasetWriter(...).write()` which initialises the backend `pyarrow.parquet.ParquetWriter` with `schema = self.dataset.features.arrow_schema` triggers `pyarrow` on write when [it checks](https://github.com/apache/arrow/blob/11b140a734a516e436adaddaeb35d23f30dcce44/python/pyarrow/parquet/core.py#L1086-L1090) that the `ParquetWriter` schema matches the schema of the table being written πŸ™Œ https://github.com/huggingface/datasets/blob/6ed837325cb539a5deb99129e5ad181d0269e050/src/datasets/io/parquet.py#L139-L141 ### Expected behavior The dataset gets successfully saved as parquet. *In the same way as it does if saving it as csv: ```python import datasets dataset = datasets.Dataset.from_dict( { "x1": [1, 2, 3], "x2": [10, 11, 12], } ) ds = dataset.select_columns(["x2", "x1"]) ds.to_csv("demo.csv") ``` ### Environment info `python==3.11` `datasets==2.13.1` We'll do a new release of `datasets` soon to make the fix available :) In the meantime you can use `datasets` from source (main)
https://github.com/huggingface/datasets/issues/5989
Set a rule on the config and split names
in this case we need to decide what to do with the existing datasets with white space characters (there shouldn't be a lot of them I think)
> should we actually allow characters like spaces? maybe it's better to add validation for whitespace symbols and directly in datasets and raise https://github.com/huggingface/datasets-server/issues/853
27
Set a rule on the config and split names > should we actually allow characters like spaces? maybe it's better to add validation for whitespace symbols and directly in datasets and raise https://github.com/huggingface/datasets-server/issues/853 in this case we need to decide what to do with the existing datasets with white space characters (there shouldn't be a lot of them I think)
https://github.com/huggingface/datasets/issues/5988
ConnectionError: Couldn't reach dataset_infos.json
Unfortunately, I can't reproduce the error. What does the following code return for you? ```python import requests from huggingface_hub import hf_hub_url r = requests.get(hf_hub_url("codeparrot/codeparrot-clean-train", "dataset_infos.json", repo_type="dataset")) ``` Also, can you provide more info about your network (region, proxies, etc.)?
### Describe the bug I'm trying to load codeparrot/codeparrot-clean-train, but get the following error: ConnectionError: Couldn't reach https://huggingface.co/datasets/codeparrot/codeparrot-clean-train/resolve/main/dataset_infos.json (ConnectionError(ProtocolError('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer')))) ### Steps to reproduce the bug train_data = load_dataset('codeparrot/codeparrot-clean-train', split='train') ### Expected behavior download the dataset ### Environment info centos7
39
ConnectionError: Couldn't reach dataset_infos.json ### Describe the bug I'm trying to load codeparrot/codeparrot-clean-train, but get the following error: ConnectionError: Couldn't reach https://huggingface.co/datasets/codeparrot/codeparrot-clean-train/resolve/main/dataset_infos.json (ConnectionError(ProtocolError('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer')))) ### Steps to reproduce the bug train_data = load_dataset('codeparrot/codeparrot-clean-train', split='train') ### Expected behavior download the dataset ### Environment info centos7 Unfortunately, I can't reproduce the error. What does the following code return for you? ```python import requests from huggingface_hub import hf_hub_url r = requests.get(hf_hub_url("codeparrot/codeparrot-clean-train", "dataset_infos.json", repo_type="dataset")) ``` Also, can you provide more info about your network (region, proxies, etc.)?
https://github.com/huggingface/datasets/issues/5987
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare
Can you explain your use case for `max_shard_size`? On some systems, there is a limit to the size of a memory-mapped file, so we could consider exposing this parameter in `load_dataset`.
### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1
31
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare ### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1 Can you explain your use case for `max_shard_size`? On some systems, there is a limit to the size of a memory-mapped file, so we could consider exposing this parameter in `load_dataset`.
https://github.com/huggingface/datasets/issues/5987
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare
In my use case, users may choose a proper size to balance the cost and benefit of using large shard size. (On azure blob or hdfs which may automatically download the shard from background)
### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1
34
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare ### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1 In my use case, users may choose a proper size to balance the cost and benefit of using large shard size. (On azure blob or hdfs which may automatically download the shard from background)
https://github.com/huggingface/datasets/issues/5987
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare
But `load_dataset` doesn't support caching (and reading) Arrow datasets from remote storage. `load_datset_builder` + `download_and_prepare` is not equal to `load_dataset`. The latter has one more step, `builder.as_dataset`, that memory-maps Arrow files, which only works for local files.
### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1
37
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare ### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1 But `load_dataset` doesn't support caching (and reading) Arrow datasets from remote storage. `load_datset_builder` + `download_and_prepare` is not equal to `load_dataset`. The latter has one more step, `builder.as_dataset`, that memory-maps Arrow files, which only works for local files.
https://github.com/huggingface/datasets/issues/5987
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare
Thanks. So if I want to use `IterableDataset` and control the size of single arrow file, how should I organize the data loader? Maybe `load_dataset_build` + `download_and_prepare` + `builder.as_dataset` + `dataset.to_iterable_dataset`?
### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1
31
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare ### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1 Thanks. So if I want to use `IterableDataset` and control the size of single arrow file, how should I organize the data loader? Maybe `load_dataset_build` + `download_and_prepare` + `builder.as_dataset` + `dataset.to_iterable_dataset`?
https://github.com/huggingface/datasets/issues/5987
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare
Yes, this should work. I think we can expose `max_shard_size` in `load_dataset`, so feel free to open a PR.
### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1
19
Why max_shard_size is not supported in load_dataset and passed to download_and_prepare ### Describe the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 What I can to is break the `load_dataset` and use `load_datset_builder` + `download_and_prepare` instead. ### Steps to reproduce the bug https://github.com/huggingface/datasets/blob/a8a797cc92e860c8d0df71e0aa826f4d2690713e/src/datasets/load.py#L1809 ### Expected behavior Users can define the max shard size. ### Environment info datasets==2.13.1 Yes, this should work. I think we can expose `max_shard_size` in `load_dataset`, so feel free to open a PR.
https://github.com/huggingface/datasets/issues/5985
Cannot reuse tokenizer object for dataset map
This is a known issue: https://github.com/huggingface/datasets/issues/3847. Fixing this requires significant work - rewriting the `tokenizers` lib to make them immutable. The current solution is to pass `cache_file_name` to `map` to use that file for caching or calling a tokenizer before `map` (with the same set of parameters as the ones in the map transform)
### Describe the bug Related to https://github.com/huggingface/transformers/issues/24441. Not sure if this is a tokenizer issue or caching issue, so filing in both. Passing the tokenizer to the dataset map function causes the tokenizer to be fingerprinted weirdly. After calling the tokenizer with arguments like padding and truncation the tokenizer object changes interanally, even though the hash remains the same. But dumps is able to detect that internal change which causes the tokenizer object's fingerprint to change. ### Steps to reproduce the bug ```python from transformers import AutoTokenizer from datasets.utils.py_utils import dumps # Huggingface datasets t = AutoTokenizer.from_pretrained('bert-base-uncased') t.save_pretrained("tok1") th1 = hash(dumps(t)) text = "This is an example text" ttext = t(text, max_length=512, padding="max_length", truncation=True) t.save_pretrained("tok2") th2 = hash(dumps(t)) assert th1 == th2 # Assertion Error ``` But if you use just the hash of the object without dumps, the hashes don't change ```python from transformers import AutoTokenizer from datasets.utils.py_utils import dumps # Huggingface datasets t = AutoTokenizer.from_pretrained('bert-base-uncased') th1 = hash(t) # Just hash no dumps text = "This is an example text" ttext = t(text, max_length=512, padding="max_length", truncation=True) th2 = hash(t) # Just hash no dumps assert th1 == th2 # This is OK ``` This causes situations such as the following 1. Create a text file like this `yes "This is an example text" | head -n 10000 > lines.txt` ```python from transformers import AutoTokenizer import datasets class TokenizeMapper(object): """Mapper for tokenizer. This is needed because the caching mechanism of HuggingFace does not work on lambdas. Each time a new lambda will be created by a new process which will lead to a different hash. This way we can have a universal mapper object in init and reuse it with the same hash for each process. """ def __init__(self, tokenizer): """Initialize the tokenizer.""" self.tokenizer = tokenizer def __call__(self, examples, **kwargs): """Run the mapper.""" texts = examples["text"] tt = self.tokenizer(texts, max_length=256, padding="max_length", truncation=True) batch_outputs = { "input_ids": tt.input_ids, "attention_mask": tt.attention_mask, } return batch_outputs t = AutoTokenizer.from_pretrained('bert-base-uncased') mapper = TokenizeMapper(t) ds = datasets.load_dataset("text", data_files="lines.txt") mds1 = ds.map( mapper, batched=False, remove_columns=["text"], ).with_format("torch") mds2 = ds.map( mapper, batched=False, remove_columns=["text"], ).with_format("torch") ``` The second call to map should reuse the cached processed dataset from mds1, but it instead it redoes the tokenization because of the behavior of dumps. ### Expected behavior We should be able to initialize a tokenizer. And reusing it should let us reuse the same map computation for the same dataset. The second call to map should reuse the cached processed dataset from mds1, but it instead it redoes the tokenization because of the behavior of dumps. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-6.1.31_1-x86_64-with-glibc2.36 - Python version: 3.9.16 - Huggingface_hub version: 0.15.1 - PyArrow version: 12.0.1 - Pandas version: 2.0.2
54
Cannot reuse tokenizer object for dataset map ### Describe the bug Related to https://github.com/huggingface/transformers/issues/24441. Not sure if this is a tokenizer issue or caching issue, so filing in both. Passing the tokenizer to the dataset map function causes the tokenizer to be fingerprinted weirdly. After calling the tokenizer with arguments like padding and truncation the tokenizer object changes interanally, even though the hash remains the same. But dumps is able to detect that internal change which causes the tokenizer object's fingerprint to change. ### Steps to reproduce the bug ```python from transformers import AutoTokenizer from datasets.utils.py_utils import dumps # Huggingface datasets t = AutoTokenizer.from_pretrained('bert-base-uncased') t.save_pretrained("tok1") th1 = hash(dumps(t)) text = "This is an example text" ttext = t(text, max_length=512, padding="max_length", truncation=True) t.save_pretrained("tok2") th2 = hash(dumps(t)) assert th1 == th2 # Assertion Error ``` But if you use just the hash of the object without dumps, the hashes don't change ```python from transformers import AutoTokenizer from datasets.utils.py_utils import dumps # Huggingface datasets t = AutoTokenizer.from_pretrained('bert-base-uncased') th1 = hash(t) # Just hash no dumps text = "This is an example text" ttext = t(text, max_length=512, padding="max_length", truncation=True) th2 = hash(t) # Just hash no dumps assert th1 == th2 # This is OK ``` This causes situations such as the following 1. Create a text file like this `yes "This is an example text" | head -n 10000 > lines.txt` ```python from transformers import AutoTokenizer import datasets class TokenizeMapper(object): """Mapper for tokenizer. This is needed because the caching mechanism of HuggingFace does not work on lambdas. Each time a new lambda will be created by a new process which will lead to a different hash. This way we can have a universal mapper object in init and reuse it with the same hash for each process. """ def __init__(self, tokenizer): """Initialize the tokenizer.""" self.tokenizer = tokenizer def __call__(self, examples, **kwargs): """Run the mapper.""" texts = examples["text"] tt = self.tokenizer(texts, max_length=256, padding="max_length", truncation=True) batch_outputs = { "input_ids": tt.input_ids, "attention_mask": tt.attention_mask, } return batch_outputs t = AutoTokenizer.from_pretrained('bert-base-uncased') mapper = TokenizeMapper(t) ds = datasets.load_dataset("text", data_files="lines.txt") mds1 = ds.map( mapper, batched=False, remove_columns=["text"], ).with_format("torch") mds2 = ds.map( mapper, batched=False, remove_columns=["text"], ).with_format("torch") ``` The second call to map should reuse the cached processed dataset from mds1, but it instead it redoes the tokenization because of the behavior of dumps. ### Expected behavior We should be able to initialize a tokenizer. And reusing it should let us reuse the same map computation for the same dataset. The second call to map should reuse the cached processed dataset from mds1, but it instead it redoes the tokenization because of the behavior of dumps. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-6.1.31_1-x86_64-with-glibc2.36 - Python version: 3.9.16 - Huggingface_hub version: 0.15.1 - PyArrow version: 12.0.1 - Pandas version: 2.0.2 This is a known issue: https://github.com/huggingface/datasets/issues/3847. Fixing this requires significant work - rewriting the `tokenizers` lib to make them immutable. The current solution is to pass `cache_file_name` to `map` to use that file for caching or calling a tokenizer before `map` (with the same set of parameters as the ones in the map transform)
https://github.com/huggingface/datasets/issues/5984
AutoSharding IterableDataset's when num_workers > 1
For this to be possible, we would have to switch from the "Streaming" Arrow format to the "Random Access" (IPC/Feather) format, which allows reading arbitrary record batches (explained [here](https://arrow.apache.org/docs/python/ipc.html)). We could then use these batches to construct shards. @lhoestq @albertvillanova Do you think this use case is worth the switch? Also, we currently shard files, not inner row groups/chunks. Should we also support sharding row groups (e.g. if the number of input files is 1)? PS: I don't expect significant speed-up for local, uncompressed Arrow files.
### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR.
86
AutoSharding IterableDataset's when num_workers > 1 ### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR. For this to be possible, we would have to switch from the "Streaming" Arrow format to the "Random Access" (IPC/Feather) format, which allows reading arbitrary record batches (explained [here](https://arrow.apache.org/docs/python/ipc.html)). We could then use these batches to construct shards. @lhoestq @albertvillanova Do you think this use case is worth the switch? Also, we currently shard files, not inner row groups/chunks. Should we also support sharding row groups (e.g. if the number of input files is 1)? PS: I don't expect significant speed-up for local, uncompressed Arrow files.
https://github.com/huggingface/datasets/issues/5984
AutoSharding IterableDataset's when num_workers > 1
Alternatively we could support multiprocessing map for iterable datasets and let the user do the CPU intensive task there ? This way it would work on arrow data but also on any iterable dataset
### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR.
34
AutoSharding IterableDataset's when num_workers > 1 ### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR. Alternatively we could support multiprocessing map for iterable datasets and let the user do the CPU intensive task there ? This way it would work on arrow data but also on any iterable dataset
https://github.com/huggingface/datasets/issues/5984
AutoSharding IterableDataset's when num_workers > 1
> For this to be possible, we would have to switch from the "Streaming" Arrow format to the "Random Access" (IPC/Feather) format, which allows reading arbitrary record batches (explained [here](https://arrow.apache.org/docs/python/ipc.html)). We could then use these batches to construct shards. > > @lhoestq @albertvillanova Do you think this use case is worth the switch? Also, we currently shard files, not inner row groups/chunks. Should we also support sharding row groups (e.g. if the number of input files is 1)? > > PS: I don't expect significant speed-up for local, uncompressed Arrow files. Could you explain why you'd need to change the arrow format? When we use streaming datasets we simply determine the number of worker shards and then add some modulo logic at the appropriate place. Worst case scenario, you'd skip streaming entries according to the number of shards. For PyTorch, I'd be happy to provide an implementation or a sketch thereof, if you point me toward what the testing requirements would be for such a PR.
### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR.
166
AutoSharding IterableDataset's when num_workers > 1 ### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR. > For this to be possible, we would have to switch from the "Streaming" Arrow format to the "Random Access" (IPC/Feather) format, which allows reading arbitrary record batches (explained [here](https://arrow.apache.org/docs/python/ipc.html)). We could then use these batches to construct shards. > > @lhoestq @albertvillanova Do you think this use case is worth the switch? Also, we currently shard files, not inner row groups/chunks. Should we also support sharding row groups (e.g. if the number of input files is 1)? > > PS: I don't expect significant speed-up for local, uncompressed Arrow files. Could you explain why you'd need to change the arrow format? When we use streaming datasets we simply determine the number of worker shards and then add some modulo logic at the appropriate place. Worst case scenario, you'd skip streaming entries according to the number of shards. For PyTorch, I'd be happy to provide an implementation or a sketch thereof, if you point me toward what the testing requirements would be for such a PR.
https://github.com/huggingface/datasets/issues/5984
AutoSharding IterableDataset's when num_workers > 1
> Could you explain why you'd need to change the arrow format? This way workers have random access to the location of the file where its dataset subset starts. Currently we're using the Arrow streaming format which doesn't include the metadata of the record batches offsets. This is needed here to efficiently split a dataset made of one single file.
### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR.
60
AutoSharding IterableDataset's when num_workers > 1 ### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR. > Could you explain why you'd need to change the arrow format? This way workers have random access to the location of the file where its dataset subset starts. Currently we're using the Arrow streaming format which doesn't include the metadata of the record batches offsets. This is needed here to efficiently split a dataset made of one single file.
https://github.com/huggingface/datasets/issues/5984
AutoSharding IterableDataset's when num_workers > 1
> > Could you explain why you'd need to change the arrow format? > > This way workers have random access to the location of the file where its dataset subset starts. Currently we're using the Arrow streaming format which doesn't include the metadata of the record batches offsets. This is needed here to efficiently split a dataset made of one single file. I guess I don't understand why you'd need to subset the dataset in the first place. It seems sufficient to figure out how to offset or skip rows. For instance, using pyArrow, you could use RecordBatchStreamReader to zero-copy iterate over records with read_next_batch and then only initiate the next step for records modulo worker shard. That's one way to do it, where of course you'd need to account for gpu sharding as well. Otherwise, how did you implement worker/node/GPU sharding for iterable/streaming data where you do not have index information or prior splits (e.g. files)?
### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR.
158
AutoSharding IterableDataset's when num_workers > 1 ### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR. > > Could you explain why you'd need to change the arrow format? > > This way workers have random access to the location of the file where its dataset subset starts. Currently we're using the Arrow streaming format which doesn't include the metadata of the record batches offsets. This is needed here to efficiently split a dataset made of one single file. I guess I don't understand why you'd need to subset the dataset in the first place. It seems sufficient to figure out how to offset or skip rows. For instance, using pyArrow, you could use RecordBatchStreamReader to zero-copy iterate over records with read_next_batch and then only initiate the next step for records modulo worker shard. That's one way to do it, where of course you'd need to account for gpu sharding as well. Otherwise, how did you implement worker/node/GPU sharding for iterable/streaming data where you do not have index information or prior splits (e.g. files)?
https://github.com/huggingface/datasets/issues/5984
AutoSharding IterableDataset's when num_workers > 1
> For instance, using pyArrow, you could use RecordBatchStreamReader to zero-copy iterate over records with read_next_batch and then only initiate the next step for records modulo worker shard. That works indeed ! And what we meant is that you can make it even faster to instantiate. Indeed using RecordBatchStreamReader you need to get the list of all the record batches in each worker, whereas you could just get the list of record batches per worker if you use the record batches locations in the Arrow IPC file footer. This would be especially appreciated to have a fast instantiation in case you have tens of thousands of Arrow files for example.
### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR.
110
AutoSharding IterableDataset's when num_workers > 1 ### Feature request Minimal Example ``` import torch from datasets import IterableDataset d = IterableDataset.from_file(<file_name>) dl = torch.utils.data.dataloader.DataLoader(d,num_workers=3) for sample in dl: print(sample) ``` Warning: Too many dataloader workers: 2 (max is dataset.n_shards=1). Stopping 1 dataloader workers. To parallelize data loading, we give each process some shards (or data sources) to process. Therefore it's unnecessary to have a number of workers greater than dataset.n_shards=1. To enable more parallelism, please split the dataset in more files than 1. Expected Behavior: Dataset is sharded each cpu uses subset (contiguously - so you can do checkpoint loading/saving) ### Motivation I have a lot of unused cpu's and would like to be able to shard iterable datasets with pytorch's dataloader when num_workers > 1. This is for a very large single file. I am aware that we can use the `split_dataset_by_node` to ensure that each node (for distributed) gets different shards, but we should extend it so that this also continues for multiple workers. ### Your contribution If someone points me to what needs to change, I can create a PR. > For instance, using pyArrow, you could use RecordBatchStreamReader to zero-copy iterate over records with read_next_batch and then only initiate the next step for records modulo worker shard. That works indeed ! And what we meant is that you can make it even faster to instantiate. Indeed using RecordBatchStreamReader you need to get the list of all the record batches in each worker, whereas you could just get the list of record batches per worker if you use the record batches locations in the Arrow IPC file footer. This would be especially appreciated to have a fast instantiation in case you have tens of thousands of Arrow files for example.
https://github.com/huggingface/datasets/issues/5982
404 on Datasets Documentation Page
This wasn’t working for me a bit earlier, but it looks to be back up now
### Describe the bug Getting a 404 from the Hugging Face Datasets docs page: https://huggingface.co/docs/datasets/index ### Steps to reproduce the bug 1. Go to URL https://huggingface.co/docs/datasets/index 2. Notice 404 not found ### Expected behavior URL should either show docs or redirect to new location ### Environment info hugginface.co
16
404 on Datasets Documentation Page ### Describe the bug Getting a 404 from the Hugging Face Datasets docs page: https://huggingface.co/docs/datasets/index ### Steps to reproduce the bug 1. Go to URL https://huggingface.co/docs/datasets/index 2. Notice 404 not found ### Expected behavior URL should either show docs or redirect to new location ### Environment info hugginface.co This wasn’t working for me a bit earlier, but it looks to be back up now
https://github.com/huggingface/datasets/issues/5982
404 on Datasets Documentation Page
We had a minor issue updating the docs after the latest release. It should work now :).
### Describe the bug Getting a 404 from the Hugging Face Datasets docs page: https://huggingface.co/docs/datasets/index ### Steps to reproduce the bug 1. Go to URL https://huggingface.co/docs/datasets/index 2. Notice 404 not found ### Expected behavior URL should either show docs or redirect to new location ### Environment info hugginface.co
17
404 on Datasets Documentation Page ### Describe the bug Getting a 404 from the Hugging Face Datasets docs page: https://huggingface.co/docs/datasets/index ### Steps to reproduce the bug 1. Go to URL https://huggingface.co/docs/datasets/index 2. Notice 404 not found ### Expected behavior URL should either show docs or redirect to new location ### Environment info hugginface.co We had a minor issue updating the docs after the latest release. It should work now :).
https://github.com/huggingface/datasets/issues/5981
Only two cores are getting used in sagemaker with pytorch 3.10 kernel
I think it's more likely that this issue is related to PyTorch than Datasets, as PyTorch (on import) registers functions to execute when forking a process. Maybe this is the culprit: https://github.com/pytorch/pytorch/issues/99625
### Describe the bug When using the newer pytorch 3.10 kernel, only 2 cores are being used by huggingface filter and map functions. The Pytorch 3.9 kernel would use as many cores as specified in the num_proc field. We have solved this in our own code by placing the following snippet in the code that is called inside subprocesses: ```os.sched_setaffinity(0, {i for i in range(1000)})``` The problem, as near as we can tell, us that once upon a time, cpu affinity was set using a bitmask ("0xfffff" and the like), and affinity recently changed to a list of processors rather than to using the mask. As such, only processors 1 and 17 are shown to be working in htop. ![Selection_072](https://github.com/huggingface/datasets/assets/107141022/04c5a824-5321-4531-afca-7bc84dff36b4) When running functions via `map`, the above resetting of affinity works to spread across the cores. When using `filter`, however, only two cores are active. ### Steps to reproduce the bug Repro steps: 1. Create an aws sagemaker instance 2. use the pytorch 3_10 kernel 3. Load a dataset 4. run a filter operation 5. watch as only 2 cores are used when num_proc > 2 6. run a map operation 7. watch as only 2 cores are used when num_proc > 2 8. run a map operation with processor affinity reset inside the function called via map 9. Watch as all cores run ### Expected behavior All specified cores are used via the num_proc argument. ### Environment info AWS sagemaker with the following init script run in the terminal after instance creation: conda init bash bash conda activate pytorch_p310 pip install Wand PyPDF pytesseract datasets seqeval pdfplumber transformers pymupdf sentencepiece timm donut-python accelerate optimum xgboost python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' sudo yum -y install htop sudo yum -y update sudo yum -y install wget libstdc++ autoconf automake libtool autoconf-archive pkg-config gcc gcc-c++ make libjpeg-devel libpng-devel libtiff-devel zlib-devel
32
Only two cores are getting used in sagemaker with pytorch 3.10 kernel ### Describe the bug When using the newer pytorch 3.10 kernel, only 2 cores are being used by huggingface filter and map functions. The Pytorch 3.9 kernel would use as many cores as specified in the num_proc field. We have solved this in our own code by placing the following snippet in the code that is called inside subprocesses: ```os.sched_setaffinity(0, {i for i in range(1000)})``` The problem, as near as we can tell, us that once upon a time, cpu affinity was set using a bitmask ("0xfffff" and the like), and affinity recently changed to a list of processors rather than to using the mask. As such, only processors 1 and 17 are shown to be working in htop. ![Selection_072](https://github.com/huggingface/datasets/assets/107141022/04c5a824-5321-4531-afca-7bc84dff36b4) When running functions via `map`, the above resetting of affinity works to spread across the cores. When using `filter`, however, only two cores are active. ### Steps to reproduce the bug Repro steps: 1. Create an aws sagemaker instance 2. use the pytorch 3_10 kernel 3. Load a dataset 4. run a filter operation 5. watch as only 2 cores are used when num_proc > 2 6. run a map operation 7. watch as only 2 cores are used when num_proc > 2 8. run a map operation with processor affinity reset inside the function called via map 9. Watch as all cores run ### Expected behavior All specified cores are used via the num_proc argument. ### Environment info AWS sagemaker with the following init script run in the terminal after instance creation: conda init bash bash conda activate pytorch_p310 pip install Wand PyPDF pytesseract datasets seqeval pdfplumber transformers pymupdf sentencepiece timm donut-python accelerate optimum xgboost python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' sudo yum -y install htop sudo yum -y update sudo yum -y install wget libstdc++ autoconf automake libtool autoconf-archive pkg-config gcc gcc-c++ make libjpeg-devel libpng-devel libtiff-devel zlib-devel I think it's more likely that this issue is related to PyTorch than Datasets, as PyTorch (on import) registers functions to execute when forking a process. Maybe this is the culprit: https://github.com/pytorch/pytorch/issues/99625
https://github.com/huggingface/datasets/issues/5981
Only two cores are getting used in sagemaker with pytorch 3.10 kernel
From reading that ticket, it may be down in mkl? Is it worth hotfixing in the meantime, with the express intention of turning it off? I know that's a horribly crufty solution, but it's also deeply frustrating to be limited to 2 cores for operations as simple as filtration.
### Describe the bug When using the newer pytorch 3.10 kernel, only 2 cores are being used by huggingface filter and map functions. The Pytorch 3.9 kernel would use as many cores as specified in the num_proc field. We have solved this in our own code by placing the following snippet in the code that is called inside subprocesses: ```os.sched_setaffinity(0, {i for i in range(1000)})``` The problem, as near as we can tell, us that once upon a time, cpu affinity was set using a bitmask ("0xfffff" and the like), and affinity recently changed to a list of processors rather than to using the mask. As such, only processors 1 and 17 are shown to be working in htop. ![Selection_072](https://github.com/huggingface/datasets/assets/107141022/04c5a824-5321-4531-afca-7bc84dff36b4) When running functions via `map`, the above resetting of affinity works to spread across the cores. When using `filter`, however, only two cores are active. ### Steps to reproduce the bug Repro steps: 1. Create an aws sagemaker instance 2. use the pytorch 3_10 kernel 3. Load a dataset 4. run a filter operation 5. watch as only 2 cores are used when num_proc > 2 6. run a map operation 7. watch as only 2 cores are used when num_proc > 2 8. run a map operation with processor affinity reset inside the function called via map 9. Watch as all cores run ### Expected behavior All specified cores are used via the num_proc argument. ### Environment info AWS sagemaker with the following init script run in the terminal after instance creation: conda init bash bash conda activate pytorch_p310 pip install Wand PyPDF pytesseract datasets seqeval pdfplumber transformers pymupdf sentencepiece timm donut-python accelerate optimum xgboost python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' sudo yum -y install htop sudo yum -y update sudo yum -y install wget libstdc++ autoconf automake libtool autoconf-archive pkg-config gcc gcc-c++ make libjpeg-devel libpng-devel libtiff-devel zlib-devel
49
Only two cores are getting used in sagemaker with pytorch 3.10 kernel ### Describe the bug When using the newer pytorch 3.10 kernel, only 2 cores are being used by huggingface filter and map functions. The Pytorch 3.9 kernel would use as many cores as specified in the num_proc field. We have solved this in our own code by placing the following snippet in the code that is called inside subprocesses: ```os.sched_setaffinity(0, {i for i in range(1000)})``` The problem, as near as we can tell, us that once upon a time, cpu affinity was set using a bitmask ("0xfffff" and the like), and affinity recently changed to a list of processors rather than to using the mask. As such, only processors 1 and 17 are shown to be working in htop. ![Selection_072](https://github.com/huggingface/datasets/assets/107141022/04c5a824-5321-4531-afca-7bc84dff36b4) When running functions via `map`, the above resetting of affinity works to spread across the cores. When using `filter`, however, only two cores are active. ### Steps to reproduce the bug Repro steps: 1. Create an aws sagemaker instance 2. use the pytorch 3_10 kernel 3. Load a dataset 4. run a filter operation 5. watch as only 2 cores are used when num_proc > 2 6. run a map operation 7. watch as only 2 cores are used when num_proc > 2 8. run a map operation with processor affinity reset inside the function called via map 9. Watch as all cores run ### Expected behavior All specified cores are used via the num_proc argument. ### Environment info AWS sagemaker with the following init script run in the terminal after instance creation: conda init bash bash conda activate pytorch_p310 pip install Wand PyPDF pytesseract datasets seqeval pdfplumber transformers pymupdf sentencepiece timm donut-python accelerate optimum xgboost python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' sudo yum -y install htop sudo yum -y update sudo yum -y install wget libstdc++ autoconf automake libtool autoconf-archive pkg-config gcc gcc-c++ make libjpeg-devel libpng-devel libtiff-devel zlib-devel From reading that ticket, it may be down in mkl? Is it worth hotfixing in the meantime, with the express intention of turning it off? I know that's a horribly crufty solution, but it's also deeply frustrating to be limited to 2 cores for operations as simple as filtration.
https://github.com/huggingface/datasets/issues/5980
Viewing dataset card returns β€œ502 Bad Gateway”
Yes, it seems to be working now. In case it's helpful, the outage lasted several days. It was failing as late as yesterday morning.
The url is: https://huggingface.co/datasets/Confirm-Labs/pile_ngrams_trigrams I am able to successfully view the β€œFiles and versions” tab: [Confirm-Labs/pile_ngrams_trigrams at main](https://huggingface.co/datasets/Confirm-Labs/pile_ngrams_trigrams/tree/main) Any help would be appreciated! Thanks! I hope this is the right place to report an issue like this.
24
Viewing dataset card returns β€œ502 Bad Gateway” The url is: https://huggingface.co/datasets/Confirm-Labs/pile_ngrams_trigrams I am able to successfully view the β€œFiles and versions” tab: [Confirm-Labs/pile_ngrams_trigrams at main](https://huggingface.co/datasets/Confirm-Labs/pile_ngrams_trigrams/tree/main) Any help would be appreciated! Thanks! I hope this is the right place to report an issue like this. Yes, it seems to be working now. In case it's helpful, the outage lasted several days. It was failing as late as yesterday morning.
https://github.com/huggingface/datasets/issues/5975
Streaming Dataset behind Proxy - FileNotFoundError
Hi ! can you try to set the upper case environment variables `HTTP_PROXY` and `HTTPS_PROXY` ? We use `aiohttp` for streaming and it uses case sensitive environment variables
### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2
28
Streaming Dataset behind Proxy - FileNotFoundError ### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2 Hi ! can you try to set the upper case environment variables `HTTP_PROXY` and `HTTPS_PROXY` ? We use `aiohttp` for streaming and it uses case sensitive environment variables
https://github.com/huggingface/datasets/issues/5975
Streaming Dataset behind Proxy - FileNotFoundError
Hi, thanks for the quick reply. I set the uppercase env variables with ` os.environ['HTTP_PROXY'] = "http://example.com:xxxx" os.environ['HTTPS_PROXY'] = "http://example.com:xxxx" ` However, I still get the same error. One thing that could be helpfull: When downloading a dataset without streaming i get the following message: _HF google storage unreachable. Downloading and preparing it from source_. The download does however work as expected.
### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2
62
Streaming Dataset behind Proxy - FileNotFoundError ### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2 Hi, thanks for the quick reply. I set the uppercase env variables with ` os.environ['HTTP_PROXY'] = "http://example.com:xxxx" os.environ['HTTPS_PROXY'] = "http://example.com:xxxx" ` However, I still get the same error. One thing that could be helpfull: When downloading a dataset without streaming i get the following message: _HF google storage unreachable. Downloading and preparing it from source_. The download does however work as expected.
https://github.com/huggingface/datasets/issues/5975
Streaming Dataset behind Proxy - FileNotFoundError
Are you able to use `aiohttp` to get the file at `https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json` using your proxy ?
### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2
16
Streaming Dataset behind Proxy - FileNotFoundError ### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2 Are you able to use `aiohttp` to get the file at `https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json` using your proxy ?
https://github.com/huggingface/datasets/issues/5975
Streaming Dataset behind Proxy - FileNotFoundError
It only works when passing trust_env=True when creating the ClientSession, as well as setting ssl=False. Working Example: ``` import os os.environ['HTTP_PROXY'] = "xyz" os.environ['HTTPS_PROXY'] = "xyz" import asyncio import aiohttp async def download_pep(url): async with aiohttp.ClientSession(trust_env=True) as session: print("1") async with session.get(url, ssl=False) as resp: print("2") content = await resp.text() print(content) return content asyncio.run(download_pep("https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json")) ``` SSL Verification has been a problem with other packages as well. Usually I circumvent the problem by setting ``` import ssl ssl._create_default_https_context = ssl._create_unverified_context ``` (probably not the best idea for security), although here aiohttp does not seem to use this default context.
### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2
98
Streaming Dataset behind Proxy - FileNotFoundError ### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2 It only works when passing trust_env=True when creating the ClientSession, as well as setting ssl=False. Working Example: ``` import os os.environ['HTTP_PROXY'] = "xyz" os.environ['HTTPS_PROXY'] = "xyz" import asyncio import aiohttp async def download_pep(url): async with aiohttp.ClientSession(trust_env=True) as session: print("1") async with session.get(url, ssl=False) as resp: print("2") content = await resp.text() print(content) return content asyncio.run(download_pep("https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json")) ``` SSL Verification has been a problem with other packages as well. Usually I circumvent the problem by setting ``` import ssl ssl._create_default_https_context = ssl._create_unverified_context ``` (probably not the best idea for security), although here aiohttp does not seem to use this default context.
https://github.com/huggingface/datasets/issues/5975
Streaming Dataset behind Proxy - FileNotFoundError
We do pass `trust_env` as well. Could you share the full stack trace you get when streaming using `datasets` ? That could help locate where we might have forgotten to pass `trust_env`
### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2
32
Streaming Dataset behind Proxy - FileNotFoundError ### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2 We do pass `trust_env` as well. Could you share the full stack trace you get when streaming using `datasets` ? That could help locate where we might have forgotten to pass `trust_env`
https://github.com/huggingface/datasets/issues/5975
Streaming Dataset behind Proxy - FileNotFoundError
Is there a way to disable ssl verification when streaming a dataset. I suspect this might be the isssue with my proxy. Here you go: ``` FileNotFoundError Traceback (most recent call last) Cell In[8], line 3 1 from datasets import load_dataset ----> 3 ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) 5 sample = next(iter(ds)) File [~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/load.py:1790](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/load.py:1790), 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, use_auth_token, task, streaming, num_proc, storage_options, **config_kwargs) 1788 # Return iterable dataset in case of streaming 1789 if streaming: -> 1790 return builder_instance.as_streaming_dataset(split=split) 1792 # Some datasets are already processed on the HF google storage 1793 # Don't try downloading from Google storage for the packaged datasets as text, json, csv or pandas 1794 try_from_hf_gcs = path not in _PACKAGED_DATASETS_MODULES File [~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/builder.py:1281](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/builder.py:1281), in DatasetBuilder.as_streaming_dataset(self, split, base_path) 1274 dl_manager = StreamingDownloadManager( 1275 base_path=base_path or self.base_path, 1276 download_config=DownloadConfig(use_auth_token=self.use_auth_token, storage_options=self.storage_options), 1277 dataset_name=self.name, 1278 data_dir=self.config.data_dir, 1279 ) 1280 self._check_manual_download(dl_manager) -> 1281 splits_generators = {sg.name: sg for sg in self._split_generators(dl_manager)} 1282 # By default, return all splits 1283 if split is None: File [~/.cache/huggingface/modules/datasets_modules/datasets/facebook--voxpopuli/b5ff837284f0778eefe0f642734e142d8c3f574eba8c9c8a4b13602297f73604/voxpopuli.py:120](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.cache/huggingface/modules/datasets_modules/datasets/facebook--voxpopuli/b5ff837284f0778eefe0f642734e142d8c3f574eba8c9c8a4b13602297f73604/voxpopuli.py:120), in Voxpopuli._split_generators(self, dl_manager) 118 def _split_generators(self, dl_manager): 119 n_shards_path = dl_manager.download_and_extract(_N_SHARDS_FILE) --> 120 with open(n_shards_path) as f: 121 n_shards = json.load(f) 123 if self.config.name == "en_accented": File [~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/streaming.py:71](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/streaming.py:71), in extend_module_for_streaming..wrap_auth..wrapper(*args, **kwargs) 69 @wraps(function) 70 def wrapper(*args, **kwargs): ---> 71 return function(*args, use_auth_token=use_auth_token, **kwargs) File [~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/download/streaming_download_manager.py:517](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/download/streaming_download_manager.py:517), in xopen(file, mode, use_auth_token, *args, **kwargs) 515 except FileNotFoundError: 516 if file.startswith(config.HF_ENDPOINT): --> 517 raise FileNotFoundError( 518 file + "\nIf the repo is private or gated, make sure to log in with `huggingface-cli login`." 519 ) from None 520 else: 521 raise FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ```
### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2
282
Streaming Dataset behind Proxy - FileNotFoundError ### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2 Is there a way to disable ssl verification when streaming a dataset. I suspect this might be the isssue with my proxy. Here you go: ``` FileNotFoundError Traceback (most recent call last) Cell In[8], line 3 1 from datasets import load_dataset ----> 3 ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) 5 sample = next(iter(ds)) File [~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/load.py:1790](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/load.py:1790), 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, use_auth_token, task, streaming, num_proc, storage_options, **config_kwargs) 1788 # Return iterable dataset in case of streaming 1789 if streaming: -> 1790 return builder_instance.as_streaming_dataset(split=split) 1792 # Some datasets are already processed on the HF google storage 1793 # Don't try downloading from Google storage for the packaged datasets as text, json, csv or pandas 1794 try_from_hf_gcs = path not in _PACKAGED_DATASETS_MODULES File [~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/builder.py:1281](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/builder.py:1281), in DatasetBuilder.as_streaming_dataset(self, split, base_path) 1274 dl_manager = StreamingDownloadManager( 1275 base_path=base_path or self.base_path, 1276 download_config=DownloadConfig(use_auth_token=self.use_auth_token, storage_options=self.storage_options), 1277 dataset_name=self.name, 1278 data_dir=self.config.data_dir, 1279 ) 1280 self._check_manual_download(dl_manager) -> 1281 splits_generators = {sg.name: sg for sg in self._split_generators(dl_manager)} 1282 # By default, return all splits 1283 if split is None: File [~/.cache/huggingface/modules/datasets_modules/datasets/facebook--voxpopuli/b5ff837284f0778eefe0f642734e142d8c3f574eba8c9c8a4b13602297f73604/voxpopuli.py:120](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.cache/huggingface/modules/datasets_modules/datasets/facebook--voxpopuli/b5ff837284f0778eefe0f642734e142d8c3f574eba8c9c8a4b13602297f73604/voxpopuli.py:120), in Voxpopuli._split_generators(self, dl_manager) 118 def _split_generators(self, dl_manager): 119 n_shards_path = dl_manager.download_and_extract(_N_SHARDS_FILE) --> 120 with open(n_shards_path) as f: 121 n_shards = json.load(f) 123 if self.config.name == "en_accented": File [~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/streaming.py:71](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/streaming.py:71), in extend_module_for_streaming..wrap_auth..wrapper(*args, **kwargs) 69 @wraps(function) 70 def wrapper(*args, **kwargs): ---> 71 return function(*args, use_auth_token=use_auth_token, **kwargs) File [~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/download/streaming_download_manager.py:517](https://vscode-remote+ssh-002dremote-002bml-002er-002dsoftware-002eat.vscode-resource.vscode-cdn.net/home/wrsbri/projects/audio_course/~/.conda/envs/audio_hf/lib/python3.10/site-packages/datasets/download/streaming_download_manager.py:517), in xopen(file, mode, use_auth_token, *args, **kwargs) 515 except FileNotFoundError: 516 if file.startswith(config.HF_ENDPOINT): --> 517 raise FileNotFoundError( 518 file + "\nIf the repo is private or gated, make sure to log in with `huggingface-cli login`." 519 ) from None 520 else: 521 raise FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ```
https://github.com/huggingface/datasets/issues/5975
Streaming Dataset behind Proxy - FileNotFoundError
> Is there a way to disable ssl verification when streaming a dataset. I don't think so. We use `fsspec` HTTPFileSystem implementation that is based on `aiohttp`. If you register a subclass of HTTPFileSystem that has SSL disabled by default it could work, but I wouldn't recommended it because it can raise security issues.
### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2
54
Streaming Dataset behind Proxy - FileNotFoundError ### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2 > Is there a way to disable ssl verification when streaming a dataset. I don't think so. We use `fsspec` HTTPFileSystem implementation that is based on `aiohttp`. If you register a subclass of HTTPFileSystem that has SSL disabled by default it could work, but I wouldn't recommended it because it can raise security issues.
https://github.com/huggingface/datasets/issues/5975
Streaming Dataset behind Proxy - FileNotFoundError
Okay thanks for your help! I guess I have to figure out how to improve the proxy environment / see if I can make it work with ssl connections.
### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2
29
Streaming Dataset behind Proxy - FileNotFoundError ### Describe the bug When trying to stream a dataset i get the following error after a few minutes of waiting. ``` FileNotFoundError: https://huggingface.co/datasets/facebook/voxpopuli/resolve/main/data/n_files.json If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` I have already set the proxy environment variables. Downloading a Dataset without streaming works as expected. Still i suspect that this is connected to being behind a proxy. Is there a way to set the proxy for streaming datasets? Possibly a keyword argument that gets passed to ffspec? ### Steps to reproduce the bug This is the code i use. ``` import os os.environ['http_proxy'] = "http://example.com:xxxx" os.environ['https_proxy'] = "http://example.com:xxxx" from datasets import load_dataset ds = load_dataset("facebook/voxpopuli", name="de", streaming=True) ``` ### Expected behavior I would expect the streaming functionality to use the set proxy settings. ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.35 - Python version: 3.10.11 - Huggingface_hub version: 0.15.1 - PyArrow version: 11.0.0 - Pandas version: 2.0.2 Okay thanks for your help! I guess I have to figure out how to improve the proxy environment / see if I can make it work with ssl connections.
https://github.com/huggingface/datasets/issues/5971
Docs: make "repository structure" easier to find
Loading a local dataset also works the same way when `data_files` are not specified, so I agree we should make this info easier to discover cc @stevhliu
The page https://huggingface.co/docs/datasets/repository_structure explains how to create a simple repository structure without a dataset script. It's the simplest way to create a dataset and should be easier to find, particularly on the docs' first pages.
27
Docs: make "repository structure" easier to find The page https://huggingface.co/docs/datasets/repository_structure explains how to create a simple repository structure without a dataset script. It's the simplest way to create a dataset and should be easier to find, particularly on the docs' first pages. Loading a local dataset also works the same way when `data_files` are not specified, so I agree we should make this info easier to discover cc @stevhliu
https://github.com/huggingface/datasets/issues/5971
Docs: make "repository structure" easier to find
@benjaminbrown038 Yes, it is. Maybe @stevhliu can give some pointers on improving this doc page's discoverability.
The page https://huggingface.co/docs/datasets/repository_structure explains how to create a simple repository structure without a dataset script. It's the simplest way to create a dataset and should be easier to find, particularly on the docs' first pages.
16
Docs: make "repository structure" easier to find The page https://huggingface.co/docs/datasets/repository_structure explains how to create a simple repository structure without a dataset script. It's the simplest way to create a dataset and should be easier to find, particularly on the docs' first pages. @benjaminbrown038 Yes, it is. Maybe @stevhliu can give some pointers on improving this doc page's discoverability.
https://github.com/huggingface/datasets/issues/5971
Docs: make "repository structure" easier to find
I think we can add a version of the [Main use-case](https://huggingface.co/docs/datasets/repository_structure#main-usecase) section to the [Share a dataset to the Hub](https://huggingface.co/docs/datasets/upload_dataset) tutorial. Currently, it doesn't tell you *how* to structure the repository; it only tells you how to create it. So adding the "main use-case" will help bridge the gap and make it easier to find. We should also add a link to the [Structure your repository](https://huggingface.co/docs/datasets/repository_structure) guide for users who want to learn about the other options.
The page https://huggingface.co/docs/datasets/repository_structure explains how to create a simple repository structure without a dataset script. It's the simplest way to create a dataset and should be easier to find, particularly on the docs' first pages.
77
Docs: make "repository structure" easier to find The page https://huggingface.co/docs/datasets/repository_structure explains how to create a simple repository structure without a dataset script. It's the simplest way to create a dataset and should be easier to find, particularly on the docs' first pages. I think we can add a version of the [Main use-case](https://huggingface.co/docs/datasets/repository_structure#main-usecase) section to the [Share a dataset to the Hub](https://huggingface.co/docs/datasets/upload_dataset) tutorial. Currently, it doesn't tell you *how* to structure the repository; it only tells you how to create it. So adding the "main use-case" will help bridge the gap and make it easier to find. We should also add a link to the [Structure your repository](https://huggingface.co/docs/datasets/repository_structure) guide for users who want to learn about the other options.
https://github.com/huggingface/datasets/issues/5970
description disappearing from Info when Uploading a Dataset Created with `from_dict`
Here's a minimal way to reproduce the bug, for the sake of convenience. ```` from datasets import Dataset, DatasetInfo, load_dataset episodes_dict = {"test":[1,2,3],"test2": [1,2,4]} hugging_face_dataset = Dataset.from_dict( episodes_dict, info=DatasetInfo(description="test_str") ) print(hugging_face_dataset.info) hugging_face_dataset.push_to_hub("balisujohn/minari_test", private=True) redownloaded_dataset= load_dataset("balisujohn/minari_test")["train"] print(redownloaded_dataset.info) ````
### Describe the bug When uploading a dataset created locally using `from_dict` with a specified `description` field. It appears before upload, but is missing after upload and re-download. ### Steps to reproduce the bug I think the most relevant pattern in the code might be the following lines: ``` description_json_str = json.dumps( { "dataset_id": dataset.spec.dataset_id, "env_name": dataset.spec.env_spec.id, "action_space": serialize_space(dataset.spec.action_space), "observation_space": serialize_space(dataset.spec.observation_space), } ) hugging_face_dataset = Dataset.from_dict( episodes_dict, info=DatasetInfo(description=description_json_str) ) ``` Which comes from this function https://github.com/balisujohn/minarai/blob/8e023727f0a8488c4451651d9f7a79b981412c40/minari/integrations/hugging_face.py#L39 To replicate, clone this branch of my Minari fork https://github.com/balisujohn/minarai/tree/dev-huggingface then run ``` python3.8 -m venv env source env/bin/activate python3 -m pip install -e . python3 -m pip install pytest ``` The change the hugging face repo path in the test called `test_hugging_face_push_and_pull_dataset` in `tests/integrations/test_hugging_face.py` to one you have permissions to write to. Then run: ``` pytest tests/integrations/test_hugging_face.py::test_hugging_face_push_and_pull_dataset ``` ### Expected behavior DATASET INFO BEFORE UPLOADING DatasetInfo(description='{"dataset_id": "dummy-combo-test-v0", "env_name": "DummyComboEnv-v0", "action_space": "{\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [4.0], \\"high\\": [5.0]}]}", "observation_space": "{\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Dict\\", \\"subspaces\\": {\\"component_1\\": {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [-1.0], \\"high\\": [1.0]}, \\"component_2\\": {\\"type\\": \\"Dict\\", \\"subspaces\\": {\\"subcomponent_1\\": {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, \\"subcomponent_2\\": {\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [4.0], \\"high\\": [5.0]}, {\\"type\\": \\"Discrete\\", \\"dtype\\": \\"int64\\", \\"start\\": 0, \\"n\\": 10}]}}}}}]}]}"}', citation='', homepage='', license='', features={'observations': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'component_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'component_2': {'subcomponent_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'subcomponent_2': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Value(dtype='int64', id=None)}}}}}, 'actions': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None)}, 'rewards': Value(dtype='int64', id=None), 'truncations': Value(dtype='bool', id=None), 'terminations': Value(dtype='bool', id=None), 'episode_ids': Value(dtype='int64', id=None)}, post_processed=None, supervised_keys=None, task_templates=None, builder_name=None, config_name=None, version=None, splits=None, download_checksums=None, download_size=None, post_processing_size=None, dataset_size=None, size_in_bytes=None) ... DATASET INFO AFTER UPLOADING AND DOWNLOADING DatasetInfo(description='', citation='', homepage='', license='', features={'observations': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'component_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'component_2': {'subcomponent_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'subcomponent_2': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Value(dtype='int64', id=None)}}}}}, 'actions': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None)}, 'rewards': Value(dtype='int64', id=None), 'truncations': Value(dtype='bool', id=None), 'terminations': Value(dtype='bool', id=None), 'episode_ids': Value(dtype='int64', id=None)}, post_processed=None, supervised_keys=None, task_templates=None, builder_name=None, config_name=None, version=None, splits={'train': SplitInfo(name='train', num_bytes=4846, num_examples=60, shard_lengths=None, dataset_name='parquet')}, download_checksums={'https://huggingface.co/datasets/balisujohn/minari_test/resolve/8217b614ff9ba5edc1a30c7df430e92a46f65363/data/train-00000-of-00001-7c5900b93b35745e.parquet': {'num_bytes': 9052, 'checksum': None}}, download_size=9052, post_processing_size=None, dataset_size=4846, size_in_bytes=13898) ... ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-75-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.2
37
description disappearing from Info when Uploading a Dataset Created with `from_dict` ### Describe the bug When uploading a dataset created locally using `from_dict` with a specified `description` field. It appears before upload, but is missing after upload and re-download. ### Steps to reproduce the bug I think the most relevant pattern in the code might be the following lines: ``` description_json_str = json.dumps( { "dataset_id": dataset.spec.dataset_id, "env_name": dataset.spec.env_spec.id, "action_space": serialize_space(dataset.spec.action_space), "observation_space": serialize_space(dataset.spec.observation_space), } ) hugging_face_dataset = Dataset.from_dict( episodes_dict, info=DatasetInfo(description=description_json_str) ) ``` Which comes from this function https://github.com/balisujohn/minarai/blob/8e023727f0a8488c4451651d9f7a79b981412c40/minari/integrations/hugging_face.py#L39 To replicate, clone this branch of my Minari fork https://github.com/balisujohn/minarai/tree/dev-huggingface then run ``` python3.8 -m venv env source env/bin/activate python3 -m pip install -e . python3 -m pip install pytest ``` The change the hugging face repo path in the test called `test_hugging_face_push_and_pull_dataset` in `tests/integrations/test_hugging_face.py` to one you have permissions to write to. Then run: ``` pytest tests/integrations/test_hugging_face.py::test_hugging_face_push_and_pull_dataset ``` ### Expected behavior DATASET INFO BEFORE UPLOADING DatasetInfo(description='{"dataset_id": "dummy-combo-test-v0", "env_name": "DummyComboEnv-v0", "action_space": "{\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [4.0], \\"high\\": [5.0]}]}", "observation_space": "{\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Dict\\", \\"subspaces\\": {\\"component_1\\": {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [-1.0], \\"high\\": [1.0]}, \\"component_2\\": {\\"type\\": \\"Dict\\", \\"subspaces\\": {\\"subcomponent_1\\": {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, \\"subcomponent_2\\": {\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [4.0], \\"high\\": [5.0]}, {\\"type\\": \\"Discrete\\", \\"dtype\\": \\"int64\\", \\"start\\": 0, \\"n\\": 10}]}}}}}]}]}"}', citation='', homepage='', license='', features={'observations': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'component_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'component_2': {'subcomponent_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'subcomponent_2': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Value(dtype='int64', id=None)}}}}}, 'actions': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None)}, 'rewards': Value(dtype='int64', id=None), 'truncations': Value(dtype='bool', id=None), 'terminations': Value(dtype='bool', id=None), 'episode_ids': Value(dtype='int64', id=None)}, post_processed=None, supervised_keys=None, task_templates=None, builder_name=None, config_name=None, version=None, splits=None, download_checksums=None, download_size=None, post_processing_size=None, dataset_size=None, size_in_bytes=None) ... DATASET INFO AFTER UPLOADING AND DOWNLOADING DatasetInfo(description='', citation='', homepage='', license='', features={'observations': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'component_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'component_2': {'subcomponent_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'subcomponent_2': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Value(dtype='int64', id=None)}}}}}, 'actions': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None)}, 'rewards': Value(dtype='int64', id=None), 'truncations': Value(dtype='bool', id=None), 'terminations': Value(dtype='bool', id=None), 'episode_ids': Value(dtype='int64', id=None)}, post_processed=None, supervised_keys=None, task_templates=None, builder_name=None, config_name=None, version=None, splits={'train': SplitInfo(name='train', num_bytes=4846, num_examples=60, shard_lengths=None, dataset_name='parquet')}, download_checksums={'https://huggingface.co/datasets/balisujohn/minari_test/resolve/8217b614ff9ba5edc1a30c7df430e92a46f65363/data/train-00000-of-00001-7c5900b93b35745e.parquet': {'num_bytes': 9052, 'checksum': None}}, download_size=9052, post_processing_size=None, dataset_size=4846, size_in_bytes=13898) ... ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-75-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.2 Here's a minimal way to reproduce the bug, for the sake of convenience. ```` from datasets import Dataset, DatasetInfo, load_dataset episodes_dict = {"test":[1,2,3],"test2": [1,2,4]} hugging_face_dataset = Dataset.from_dict( episodes_dict, info=DatasetInfo(description="test_str") ) print(hugging_face_dataset.info) hugging_face_dataset.push_to_hub("balisujohn/minari_test", private=True) redownloaded_dataset= load_dataset("balisujohn/minari_test")["train"] print(redownloaded_dataset.info) ````
https://github.com/huggingface/datasets/issues/5970
description disappearing from Info when Uploading a Dataset Created with `from_dict`
Thanks for reporting ! For now I would recommend uploading a separate JSON file for your metadata. Alternatively you can upload a second configuration of the dataset containing your metadata but this feature is not released yet (though you can already use it from [here](https://github.com/huggingface/datasets/pull/5331), it will be released soon)
### Describe the bug When uploading a dataset created locally using `from_dict` with a specified `description` field. It appears before upload, but is missing after upload and re-download. ### Steps to reproduce the bug I think the most relevant pattern in the code might be the following lines: ``` description_json_str = json.dumps( { "dataset_id": dataset.spec.dataset_id, "env_name": dataset.spec.env_spec.id, "action_space": serialize_space(dataset.spec.action_space), "observation_space": serialize_space(dataset.spec.observation_space), } ) hugging_face_dataset = Dataset.from_dict( episodes_dict, info=DatasetInfo(description=description_json_str) ) ``` Which comes from this function https://github.com/balisujohn/minarai/blob/8e023727f0a8488c4451651d9f7a79b981412c40/minari/integrations/hugging_face.py#L39 To replicate, clone this branch of my Minari fork https://github.com/balisujohn/minarai/tree/dev-huggingface then run ``` python3.8 -m venv env source env/bin/activate python3 -m pip install -e . python3 -m pip install pytest ``` The change the hugging face repo path in the test called `test_hugging_face_push_and_pull_dataset` in `tests/integrations/test_hugging_face.py` to one you have permissions to write to. Then run: ``` pytest tests/integrations/test_hugging_face.py::test_hugging_face_push_and_pull_dataset ``` ### Expected behavior DATASET INFO BEFORE UPLOADING DatasetInfo(description='{"dataset_id": "dummy-combo-test-v0", "env_name": "DummyComboEnv-v0", "action_space": "{\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [4.0], \\"high\\": [5.0]}]}", "observation_space": "{\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Dict\\", \\"subspaces\\": {\\"component_1\\": {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [-1.0], \\"high\\": [1.0]}, \\"component_2\\": {\\"type\\": \\"Dict\\", \\"subspaces\\": {\\"subcomponent_1\\": {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, \\"subcomponent_2\\": {\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [4.0], \\"high\\": [5.0]}, {\\"type\\": \\"Discrete\\", \\"dtype\\": \\"int64\\", \\"start\\": 0, \\"n\\": 10}]}}}}}]}]}"}', citation='', homepage='', license='', features={'observations': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'component_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'component_2': {'subcomponent_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'subcomponent_2': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Value(dtype='int64', id=None)}}}}}, 'actions': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None)}, 'rewards': Value(dtype='int64', id=None), 'truncations': Value(dtype='bool', id=None), 'terminations': Value(dtype='bool', id=None), 'episode_ids': Value(dtype='int64', id=None)}, post_processed=None, supervised_keys=None, task_templates=None, builder_name=None, config_name=None, version=None, splits=None, download_checksums=None, download_size=None, post_processing_size=None, dataset_size=None, size_in_bytes=None) ... DATASET INFO AFTER UPLOADING AND DOWNLOADING DatasetInfo(description='', citation='', homepage='', license='', features={'observations': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'component_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'component_2': {'subcomponent_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'subcomponent_2': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Value(dtype='int64', id=None)}}}}}, 'actions': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None)}, 'rewards': Value(dtype='int64', id=None), 'truncations': Value(dtype='bool', id=None), 'terminations': Value(dtype='bool', id=None), 'episode_ids': Value(dtype='int64', id=None)}, post_processed=None, supervised_keys=None, task_templates=None, builder_name=None, config_name=None, version=None, splits={'train': SplitInfo(name='train', num_bytes=4846, num_examples=60, shard_lengths=None, dataset_name='parquet')}, download_checksums={'https://huggingface.co/datasets/balisujohn/minari_test/resolve/8217b614ff9ba5edc1a30c7df430e92a46f65363/data/train-00000-of-00001-7c5900b93b35745e.parquet': {'num_bytes': 9052, 'checksum': None}}, download_size=9052, post_processing_size=None, dataset_size=4846, size_in_bytes=13898) ... ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-75-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.2
50
description disappearing from Info when Uploading a Dataset Created with `from_dict` ### Describe the bug When uploading a dataset created locally using `from_dict` with a specified `description` field. It appears before upload, but is missing after upload and re-download. ### Steps to reproduce the bug I think the most relevant pattern in the code might be the following lines: ``` description_json_str = json.dumps( { "dataset_id": dataset.spec.dataset_id, "env_name": dataset.spec.env_spec.id, "action_space": serialize_space(dataset.spec.action_space), "observation_space": serialize_space(dataset.spec.observation_space), } ) hugging_face_dataset = Dataset.from_dict( episodes_dict, info=DatasetInfo(description=description_json_str) ) ``` Which comes from this function https://github.com/balisujohn/minarai/blob/8e023727f0a8488c4451651d9f7a79b981412c40/minari/integrations/hugging_face.py#L39 To replicate, clone this branch of my Minari fork https://github.com/balisujohn/minarai/tree/dev-huggingface then run ``` python3.8 -m venv env source env/bin/activate python3 -m pip install -e . python3 -m pip install pytest ``` The change the hugging face repo path in the test called `test_hugging_face_push_and_pull_dataset` in `tests/integrations/test_hugging_face.py` to one you have permissions to write to. Then run: ``` pytest tests/integrations/test_hugging_face.py::test_hugging_face_push_and_pull_dataset ``` ### Expected behavior DATASET INFO BEFORE UPLOADING DatasetInfo(description='{"dataset_id": "dummy-combo-test-v0", "env_name": "DummyComboEnv-v0", "action_space": "{\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [4.0], \\"high\\": [5.0]}]}", "observation_space": "{\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, {\\"type\\": \\"Dict\\", \\"subspaces\\": {\\"component_1\\": {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [-1.0], \\"high\\": [1.0]}, \\"component_2\\": {\\"type\\": \\"Dict\\", \\"subspaces\\": {\\"subcomponent_1\\": {\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [2.0], \\"high\\": [3.0]}, \\"subcomponent_2\\": {\\"type\\": \\"Tuple\\", \\"subspaces\\": [{\\"type\\": \\"Box\\", \\"dtype\\": \\"float32\\", \\"shape\\": [1], \\"low\\": [4.0], \\"high\\": [5.0]}, {\\"type\\": \\"Discrete\\", \\"dtype\\": \\"int64\\", \\"start\\": 0, \\"n\\": 10}]}}}}}]}]}"}', citation='', homepage='', license='', features={'observations': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'component_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'component_2': {'subcomponent_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'subcomponent_2': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Value(dtype='int64', id=None)}}}}}, 'actions': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None)}, 'rewards': Value(dtype='int64', id=None), 'truncations': Value(dtype='bool', id=None), 'terminations': Value(dtype='bool', id=None), 'episode_ids': Value(dtype='int64', id=None)}, post_processed=None, supervised_keys=None, task_templates=None, builder_name=None, config_name=None, version=None, splits=None, download_checksums=None, download_size=None, post_processing_size=None, dataset_size=None, size_in_bytes=None) ... DATASET INFO AFTER UPLOADING AND DOWNLOADING DatasetInfo(description='', citation='', homepage='', license='', features={'observations': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': {'component_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'component_2': {'subcomponent_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), 'subcomponent_2': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Value(dtype='int64', id=None)}}}}}, 'actions': {'_index_0': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None), '_index_1': Sequence(feature=Value(dtype='float32', id=None), length=-1, id=None)}, 'rewards': Value(dtype='int64', id=None), 'truncations': Value(dtype='bool', id=None), 'terminations': Value(dtype='bool', id=None), 'episode_ids': Value(dtype='int64', id=None)}, post_processed=None, supervised_keys=None, task_templates=None, builder_name=None, config_name=None, version=None, splits={'train': SplitInfo(name='train', num_bytes=4846, num_examples=60, shard_lengths=None, dataset_name='parquet')}, download_checksums={'https://huggingface.co/datasets/balisujohn/minari_test/resolve/8217b614ff9ba5edc1a30c7df430e92a46f65363/data/train-00000-of-00001-7c5900b93b35745e.parquet': {'num_bytes': 9052, 'checksum': None}}, download_size=9052, post_processing_size=None, dataset_size=4846, size_in_bytes=13898) ... ### Environment info - `datasets` version: 2.13.0 - Platform: Linux-5.15.0-75-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.2 Thanks for reporting ! For now I would recommend uploading a separate JSON file for your metadata. Alternatively you can upload a second configuration of the dataset containing your metadata but this feature is not released yet (though you can already use it from [here](https://github.com/huggingface/datasets/pull/5331), it will be released soon)
https://github.com/huggingface/datasets/issues/5968
Common Voice datasets still need `use_auth_token=True`
The issue commes from the dataset itself and is not related to the `datasets` lib see https://huggingface.co/datasets/mozilla-foundation/common_voice_6_1/blob/2c475b3b88e0f2e5828f830a4b91618a25ff20b7/common_voice_6_1.py#L148-L152
### Describe the bug We don't need to pass `use_auth_token=True` anymore to download gated datasets or models, so the following should work if correctly logged in. ```py from datasets import load_dataset load_dataset("mozilla-foundation/common_voice_6_1", "tr", split="train+validation") ``` However it throws an error - probably because something weird is hardcoded into the dataset loading script. ### Steps to reproduce the bug 1.) ``` huggingface-cli login ``` 2.) Make sure that you have accepted the license here: https://huggingface.co/datasets/mozilla-foundation/common_voice_6_1 3.) Run: ```py from datasets import load_dataset load_dataset("mozilla-foundation/common_voice_6_1", "tr", split="train+validation") ``` 4.) You'll get: ``` File ~/hf/lib/python3.10/site-packages/datasets/builder.py:963, in DatasetBuilder._download_and_prepare(self, dl_manager, verification_mode, **prepare_split_kwargs) 961 split_dict = SplitDict(dataset_name=self.name) 962 split_generators_kwargs = self._make_split_generators_kwargs(prepare_split_kwargs) --> 963 split_generators = self._split_generators(dl_manager, **split_generators_kwargs) 965 # Checksums verification 966 if verification_mode == VerificationMode.ALL_CHECKS and dl_manager.record_checksums: File ~/.cache/huggingface/modules/datasets_modules/datasets/mozilla-foundation--common_voice_6_1/f4d7854c466f5bd4908988dbd39044ec4fc634d89e0515ab0c51715c0127ffe3/common_voice_6_1.py:150, in CommonVoice._split_generators(self, dl_manager) 148 hf_auth_token = dl_manager.download_config.use_auth_token 149 if hf_auth_token is None: --> 150 raise ConnectionError( 151 "Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset" 152 ) 154 bundle_url_template = STATS["bundleURLTemplate"] 155 bundle_version = bundle_url_template.split("/")[0] ConnectionError: Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset ``` ### Expected behavior One should not have to pass `use_auth_token=True`. Also see discussion here: https://github.com/huggingface/blog/pull/1243#discussion_r1235131150 ### Environment info ``` - `datasets` version: 2.13.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 ```
17
Common Voice datasets still need `use_auth_token=True` ### Describe the bug We don't need to pass `use_auth_token=True` anymore to download gated datasets or models, so the following should work if correctly logged in. ```py from datasets import load_dataset load_dataset("mozilla-foundation/common_voice_6_1", "tr", split="train+validation") ``` However it throws an error - probably because something weird is hardcoded into the dataset loading script. ### Steps to reproduce the bug 1.) ``` huggingface-cli login ``` 2.) Make sure that you have accepted the license here: https://huggingface.co/datasets/mozilla-foundation/common_voice_6_1 3.) Run: ```py from datasets import load_dataset load_dataset("mozilla-foundation/common_voice_6_1", "tr", split="train+validation") ``` 4.) You'll get: ``` File ~/hf/lib/python3.10/site-packages/datasets/builder.py:963, in DatasetBuilder._download_and_prepare(self, dl_manager, verification_mode, **prepare_split_kwargs) 961 split_dict = SplitDict(dataset_name=self.name) 962 split_generators_kwargs = self._make_split_generators_kwargs(prepare_split_kwargs) --> 963 split_generators = self._split_generators(dl_manager, **split_generators_kwargs) 965 # Checksums verification 966 if verification_mode == VerificationMode.ALL_CHECKS and dl_manager.record_checksums: File ~/.cache/huggingface/modules/datasets_modules/datasets/mozilla-foundation--common_voice_6_1/f4d7854c466f5bd4908988dbd39044ec4fc634d89e0515ab0c51715c0127ffe3/common_voice_6_1.py:150, in CommonVoice._split_generators(self, dl_manager) 148 hf_auth_token = dl_manager.download_config.use_auth_token 149 if hf_auth_token is None: --> 150 raise ConnectionError( 151 "Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset" 152 ) 154 bundle_url_template = STATS["bundleURLTemplate"] 155 bundle_version = bundle_url_template.split("/")[0] ConnectionError: Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset ``` ### Expected behavior One should not have to pass `use_auth_token=True`. Also see discussion here: https://github.com/huggingface/blog/pull/1243#discussion_r1235131150 ### Environment info ``` - `datasets` version: 2.13.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 ``` The issue commes from the dataset itself and is not related to the `datasets` lib see https://huggingface.co/datasets/mozilla-foundation/common_voice_6_1/blob/2c475b3b88e0f2e5828f830a4b91618a25ff20b7/common_voice_6_1.py#L148-L152
https://github.com/huggingface/datasets/issues/5968
Common Voice datasets still need `use_auth_token=True`
Addressed in: * `mozilla-foundation/common_voice_1_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_1_0/discussions/4) * `mozilla-foundation/common_voice_2_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_2_0/discussions/3) * `mozilla-foundation/common_voice_3_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_3_0/discussions/3) * `mozilla-foundation/common_voice_4_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_4_0/discussions/3) * `mozilla-foundation/common_voice_5_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_5_0/discussions/3) * `mozilla-foundation/common_voice_5_1` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_5_1/discussions/3) * `mozilla-foundation/common_voice_6_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_6_0/discussions/3) * `mozilla-foundation/common_voice_6_1` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_6_1/discussions/3) * `mozilla-foundation/common_voice_7_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_7_0/discussions/3) * `mozilla-foundation/common_voice_8_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_8_0/discussions/7) * `mozilla-foundation/common_voice_9_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_9_0/discussions/8) * `mozilla-foundation/common_voice_10_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_10_0/discussions/7)
### Describe the bug We don't need to pass `use_auth_token=True` anymore to download gated datasets or models, so the following should work if correctly logged in. ```py from datasets import load_dataset load_dataset("mozilla-foundation/common_voice_6_1", "tr", split="train+validation") ``` However it throws an error - probably because something weird is hardcoded into the dataset loading script. ### Steps to reproduce the bug 1.) ``` huggingface-cli login ``` 2.) Make sure that you have accepted the license here: https://huggingface.co/datasets/mozilla-foundation/common_voice_6_1 3.) Run: ```py from datasets import load_dataset load_dataset("mozilla-foundation/common_voice_6_1", "tr", split="train+validation") ``` 4.) You'll get: ``` File ~/hf/lib/python3.10/site-packages/datasets/builder.py:963, in DatasetBuilder._download_and_prepare(self, dl_manager, verification_mode, **prepare_split_kwargs) 961 split_dict = SplitDict(dataset_name=self.name) 962 split_generators_kwargs = self._make_split_generators_kwargs(prepare_split_kwargs) --> 963 split_generators = self._split_generators(dl_manager, **split_generators_kwargs) 965 # Checksums verification 966 if verification_mode == VerificationMode.ALL_CHECKS and dl_manager.record_checksums: File ~/.cache/huggingface/modules/datasets_modules/datasets/mozilla-foundation--common_voice_6_1/f4d7854c466f5bd4908988dbd39044ec4fc634d89e0515ab0c51715c0127ffe3/common_voice_6_1.py:150, in CommonVoice._split_generators(self, dl_manager) 148 hf_auth_token = dl_manager.download_config.use_auth_token 149 if hf_auth_token is None: --> 150 raise ConnectionError( 151 "Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset" 152 ) 154 bundle_url_template = STATS["bundleURLTemplate"] 155 bundle_version = bundle_url_template.split("/")[0] ConnectionError: Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset ``` ### Expected behavior One should not have to pass `use_auth_token=True`. Also see discussion here: https://github.com/huggingface/blog/pull/1243#discussion_r1235131150 ### Environment info ``` - `datasets` version: 2.13.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 ```
38
Common Voice datasets still need `use_auth_token=True` ### Describe the bug We don't need to pass `use_auth_token=True` anymore to download gated datasets or models, so the following should work if correctly logged in. ```py from datasets import load_dataset load_dataset("mozilla-foundation/common_voice_6_1", "tr", split="train+validation") ``` However it throws an error - probably because something weird is hardcoded into the dataset loading script. ### Steps to reproduce the bug 1.) ``` huggingface-cli login ``` 2.) Make sure that you have accepted the license here: https://huggingface.co/datasets/mozilla-foundation/common_voice_6_1 3.) Run: ```py from datasets import load_dataset load_dataset("mozilla-foundation/common_voice_6_1", "tr", split="train+validation") ``` 4.) You'll get: ``` File ~/hf/lib/python3.10/site-packages/datasets/builder.py:963, in DatasetBuilder._download_and_prepare(self, dl_manager, verification_mode, **prepare_split_kwargs) 961 split_dict = SplitDict(dataset_name=self.name) 962 split_generators_kwargs = self._make_split_generators_kwargs(prepare_split_kwargs) --> 963 split_generators = self._split_generators(dl_manager, **split_generators_kwargs) 965 # Checksums verification 966 if verification_mode == VerificationMode.ALL_CHECKS and dl_manager.record_checksums: File ~/.cache/huggingface/modules/datasets_modules/datasets/mozilla-foundation--common_voice_6_1/f4d7854c466f5bd4908988dbd39044ec4fc634d89e0515ab0c51715c0127ffe3/common_voice_6_1.py:150, in CommonVoice._split_generators(self, dl_manager) 148 hf_auth_token = dl_manager.download_config.use_auth_token 149 if hf_auth_token is None: --> 150 raise ConnectionError( 151 "Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset" 152 ) 154 bundle_url_template = STATS["bundleURLTemplate"] 155 bundle_version = bundle_url_template.split("/")[0] ConnectionError: Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset ``` ### Expected behavior One should not have to pass `use_auth_token=True`. Also see discussion here: https://github.com/huggingface/blog/pull/1243#discussion_r1235131150 ### Environment info ``` - `datasets` version: 2.13.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 ``` Addressed in: * `mozilla-foundation/common_voice_1_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_1_0/discussions/4) * `mozilla-foundation/common_voice_2_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_2_0/discussions/3) * `mozilla-foundation/common_voice_3_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_3_0/discussions/3) * `mozilla-foundation/common_voice_4_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_4_0/discussions/3) * `mozilla-foundation/common_voice_5_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_5_0/discussions/3) * `mozilla-foundation/common_voice_5_1` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_5_1/discussions/3) * `mozilla-foundation/common_voice_6_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_6_0/discussions/3) * `mozilla-foundation/common_voice_6_1` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_6_1/discussions/3) * `mozilla-foundation/common_voice_7_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_7_0/discussions/3) * `mozilla-foundation/common_voice_8_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_8_0/discussions/7) * `mozilla-foundation/common_voice_9_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_9_0/discussions/8) * `mozilla-foundation/common_voice_10_0` [PR](https://huggingface.co/datasets/mozilla-foundation/common_voice_10_0/discussions/7)
https://github.com/huggingface/datasets/issues/5967
Config name / split name lost after map with multiproc
This must be due to DatasetInfo.from_merge which drops them and is used in `concatenate_datasets`. And you're experiencing this issue because multiprocessing does concatenate the resulting datasets from each process. Maybe they should be kept if all the subdatasets share the same values for config_name and split
### Describe the bug Performing a `.map` method on a dataset loses it's config name / split name only if run with multiproc ### Steps to reproduce the bug ```python from datasets import Audio, load_dataset from transformers import AutoFeatureExtractor import numpy as np # load dummy dataset libri = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean") # make train / test splits libri = libri["validation"].train_test_split(seed=42, shuffle=True, test_size=0.1) # example feature extractor model_id = "ntu-spml/distilhubert" feature_extractor = AutoFeatureExtractor.from_pretrained(model_id, do_normalize=True, return_attention_mask=True) sampling_rate = feature_extractor.sampling_rate libri = libri.cast_column("audio", Audio(sampling_rate=sampling_rate)) max_duration = 30.0 def preprocess_function(examples): audio_arrays = [x["array"] for x in examples["audio"]] inputs = feature_extractor( audio_arrays, sampling_rate=feature_extractor.sampling_rate, max_length=int(feature_extractor.sampling_rate * max_duration), truncation=True, return_attention_mask=True, ) return inputs # single proc map libri_encoded = libri.map( preprocess_function, remove_columns=["audio", "file"], batched=True, num_proc=1 ) print(10 * "=" ,"Single processing", 10 * "=") print("Config name before: ", libri["train"].config_name, " Split name before: ", libri["train"].split) print("Config name after: ", libri_encoded["train"].config_name, " Split name after: ", libri_encoded["train"].split) # multi proc map libri_encoded = libri.map( preprocess_function, remove_columns=["audio", "file"], batched=True, num_proc=2 ) print(10 * "=" ,"Multi processing", 10 * "=") print("Config name before: ", libri["train"].config_name, " Split name before: ", libri["train"].split) print("Config name after: ", libri_encoded["train"].config_name, " Split name after: ", libri_encoded["train"].split) ``` **Print Output:** ``` ========== Single processing ========== Config name before: clean Split name before: validation Config name after: clean Split name after: validation ========== Multi processing ========== Config name before: clean Split name before: validation Config name after: None Split name after: None ``` => we can see that the config/split names are lost in the multiprocessing setting ### Expected behavior Should retain both config / split names in the multiproc setting ### Environment info - `datasets` version: 2.13.1.dev0 - Platform: Linux-5.15.0-67-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.15.1 - PyArrow version: 12.0.0 - Pandas version: 2.0.2
46
Config name / split name lost after map with multiproc ### Describe the bug Performing a `.map` method on a dataset loses it's config name / split name only if run with multiproc ### Steps to reproduce the bug ```python from datasets import Audio, load_dataset from transformers import AutoFeatureExtractor import numpy as np # load dummy dataset libri = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean") # make train / test splits libri = libri["validation"].train_test_split(seed=42, shuffle=True, test_size=0.1) # example feature extractor model_id = "ntu-spml/distilhubert" feature_extractor = AutoFeatureExtractor.from_pretrained(model_id, do_normalize=True, return_attention_mask=True) sampling_rate = feature_extractor.sampling_rate libri = libri.cast_column("audio", Audio(sampling_rate=sampling_rate)) max_duration = 30.0 def preprocess_function(examples): audio_arrays = [x["array"] for x in examples["audio"]] inputs = feature_extractor( audio_arrays, sampling_rate=feature_extractor.sampling_rate, max_length=int(feature_extractor.sampling_rate * max_duration), truncation=True, return_attention_mask=True, ) return inputs # single proc map libri_encoded = libri.map( preprocess_function, remove_columns=["audio", "file"], batched=True, num_proc=1 ) print(10 * "=" ,"Single processing", 10 * "=") print("Config name before: ", libri["train"].config_name, " Split name before: ", libri["train"].split) print("Config name after: ", libri_encoded["train"].config_name, " Split name after: ", libri_encoded["train"].split) # multi proc map libri_encoded = libri.map( preprocess_function, remove_columns=["audio", "file"], batched=True, num_proc=2 ) print(10 * "=" ,"Multi processing", 10 * "=") print("Config name before: ", libri["train"].config_name, " Split name before: ", libri["train"].split) print("Config name after: ", libri_encoded["train"].config_name, " Split name after: ", libri_encoded["train"].split) ``` **Print Output:** ``` ========== Single processing ========== Config name before: clean Split name before: validation Config name after: clean Split name after: validation ========== Multi processing ========== Config name before: clean Split name before: validation Config name after: None Split name after: None ``` => we can see that the config/split names are lost in the multiprocessing setting ### Expected behavior Should retain both config / split names in the multiproc setting ### Environment info - `datasets` version: 2.13.1.dev0 - Platform: Linux-5.15.0-67-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.15.1 - PyArrow version: 12.0.0 - Pandas version: 2.0.2 This must be due to DatasetInfo.from_merge which drops them and is used in `concatenate_datasets`. And you're experiencing this issue because multiprocessing does concatenate the resulting datasets from each process. Maybe they should be kept if all the subdatasets share the same values for config_name and split
https://github.com/huggingface/datasets/issues/5965
"Couldn't cast array of type" in complex datasets
Thanks for reporting! Specifying the target features explicitly should avoid this error: ```python dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, features=datasets.Features({"texts": datasets.Sequence(datasets.Value("string"))}) ) ``` This error stems from our type promotion not handling the nested case. But this promotion/casting allocates memory in most scenarios, which can be problematic for large datasets, so explicitly passing the features is the optimal solution.
### Describe the bug When doing a map of a dataset with complex types, sometimes `datasets` is unable to interpret the valid schema of a returned datasets.map() function. This often comes from conflicting types, like when both empty lists and filled lists are competing for the same field value. This is prone to happen in batch mapping, when the mapper returns a sequence of null/empty values and other batches are non-null. A workaround is to manually cast the new batch to a pyarrow table (like implemented in this [workaround](https://github.com/piercefreeman/lassen/pull/3)) but it feels like this ideally should be solved at the core library level. Note that the reproduction case only throws this error if the first datapoint has the empty list. If it is processed later, datasets already detects its representation as list-type and therefore allows the empty list to be provided. ### Steps to reproduce the bug A trivial reproduction case: ```python from typing import Iterator, Any import pandas as pd from datasets import Dataset def batch_to_examples(batch: dict[str, list[Any]]) -> Iterator[dict[str, Any]]: for i in range(next(iter(lengths))): yield {feature: values[i] for feature, values in batch.items()} def examples_to_batch(examples) -> dict[str, list[Any]]: batch = {} for example in examples: for feature, value in example.items(): if feature not in batch: batch[feature] = [] batch[feature].append(value) return batch def batch_process(examples, explicit_schema: bool): new_examples = [] for example in batch_to_examples(examples): new_examples.append(dict(texts=example["raw_text"].split())) return examples_to_batch(new_examples) df = pd.DataFrame( [ {"raw_text": ""}, {"raw_text": "This is a test"}, {"raw_text": "This is another test"}, ] ) dataset = Dataset.from_pandas(df) # datasets won't be able to typehint a dataset that starts with an empty example. with pytest.raises(TypeError, match="Couldn't cast array of type"): dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, ) ``` This results in crashes like: ```bash File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 2109, in cast_array_to_feature return array_cast(array, feature(), allow_number_to_str=allow_number_to_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1998, in array_cast raise TypeError(f"Couldn't cast array of type {array.type} to {pa_type}") TypeError: Couldn't cast array of type string to null ``` ### Expected behavior The code should successfully map and create a new dataset without error. ### Environment info Mac OSX, Linux
61
"Couldn't cast array of type" in complex datasets ### Describe the bug When doing a map of a dataset with complex types, sometimes `datasets` is unable to interpret the valid schema of a returned datasets.map() function. This often comes from conflicting types, like when both empty lists and filled lists are competing for the same field value. This is prone to happen in batch mapping, when the mapper returns a sequence of null/empty values and other batches are non-null. A workaround is to manually cast the new batch to a pyarrow table (like implemented in this [workaround](https://github.com/piercefreeman/lassen/pull/3)) but it feels like this ideally should be solved at the core library level. Note that the reproduction case only throws this error if the first datapoint has the empty list. If it is processed later, datasets already detects its representation as list-type and therefore allows the empty list to be provided. ### Steps to reproduce the bug A trivial reproduction case: ```python from typing import Iterator, Any import pandas as pd from datasets import Dataset def batch_to_examples(batch: dict[str, list[Any]]) -> Iterator[dict[str, Any]]: for i in range(next(iter(lengths))): yield {feature: values[i] for feature, values in batch.items()} def examples_to_batch(examples) -> dict[str, list[Any]]: batch = {} for example in examples: for feature, value in example.items(): if feature not in batch: batch[feature] = [] batch[feature].append(value) return batch def batch_process(examples, explicit_schema: bool): new_examples = [] for example in batch_to_examples(examples): new_examples.append(dict(texts=example["raw_text"].split())) return examples_to_batch(new_examples) df = pd.DataFrame( [ {"raw_text": ""}, {"raw_text": "This is a test"}, {"raw_text": "This is another test"}, ] ) dataset = Dataset.from_pandas(df) # datasets won't be able to typehint a dataset that starts with an empty example. with pytest.raises(TypeError, match="Couldn't cast array of type"): dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, ) ``` This results in crashes like: ```bash File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 2109, in cast_array_to_feature return array_cast(array, feature(), allow_number_to_str=allow_number_to_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1998, in array_cast raise TypeError(f"Couldn't cast array of type {array.type} to {pa_type}") TypeError: Couldn't cast array of type string to null ``` ### Expected behavior The code should successfully map and create a new dataset without error. ### Environment info Mac OSX, Linux Thanks for reporting! Specifying the target features explicitly should avoid this error: ```python dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, features=datasets.Features({"texts": datasets.Sequence(datasets.Value("string"))}) ) ``` This error stems from our type promotion not handling the nested case. But this promotion/casting allocates memory in most scenarios, which can be problematic for large datasets, so explicitly passing the features is the optimal solution.
https://github.com/huggingface/datasets/issues/5965
"Couldn't cast array of type" in complex datasets
Hi @mariosasko thanks for the context, this is helpful to know. Would it be worth having some logic to generate this explicit feature specification automatically if a type annotation for a .map returns a dataclass that can be inferred? Feels like something that would be easy to implement and could save memory / deal with this case in a standardized way.
### Describe the bug When doing a map of a dataset with complex types, sometimes `datasets` is unable to interpret the valid schema of a returned datasets.map() function. This often comes from conflicting types, like when both empty lists and filled lists are competing for the same field value. This is prone to happen in batch mapping, when the mapper returns a sequence of null/empty values and other batches are non-null. A workaround is to manually cast the new batch to a pyarrow table (like implemented in this [workaround](https://github.com/piercefreeman/lassen/pull/3)) but it feels like this ideally should be solved at the core library level. Note that the reproduction case only throws this error if the first datapoint has the empty list. If it is processed later, datasets already detects its representation as list-type and therefore allows the empty list to be provided. ### Steps to reproduce the bug A trivial reproduction case: ```python from typing import Iterator, Any import pandas as pd from datasets import Dataset def batch_to_examples(batch: dict[str, list[Any]]) -> Iterator[dict[str, Any]]: for i in range(next(iter(lengths))): yield {feature: values[i] for feature, values in batch.items()} def examples_to_batch(examples) -> dict[str, list[Any]]: batch = {} for example in examples: for feature, value in example.items(): if feature not in batch: batch[feature] = [] batch[feature].append(value) return batch def batch_process(examples, explicit_schema: bool): new_examples = [] for example in batch_to_examples(examples): new_examples.append(dict(texts=example["raw_text"].split())) return examples_to_batch(new_examples) df = pd.DataFrame( [ {"raw_text": ""}, {"raw_text": "This is a test"}, {"raw_text": "This is another test"}, ] ) dataset = Dataset.from_pandas(df) # datasets won't be able to typehint a dataset that starts with an empty example. with pytest.raises(TypeError, match="Couldn't cast array of type"): dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, ) ``` This results in crashes like: ```bash File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 2109, in cast_array_to_feature return array_cast(array, feature(), allow_number_to_str=allow_number_to_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1998, in array_cast raise TypeError(f"Couldn't cast array of type {array.type} to {pa_type}") TypeError: Couldn't cast array of type string to null ``` ### Expected behavior The code should successfully map and create a new dataset without error. ### Environment info Mac OSX, Linux
61
"Couldn't cast array of type" in complex datasets ### Describe the bug When doing a map of a dataset with complex types, sometimes `datasets` is unable to interpret the valid schema of a returned datasets.map() function. This often comes from conflicting types, like when both empty lists and filled lists are competing for the same field value. This is prone to happen in batch mapping, when the mapper returns a sequence of null/empty values and other batches are non-null. A workaround is to manually cast the new batch to a pyarrow table (like implemented in this [workaround](https://github.com/piercefreeman/lassen/pull/3)) but it feels like this ideally should be solved at the core library level. Note that the reproduction case only throws this error if the first datapoint has the empty list. If it is processed later, datasets already detects its representation as list-type and therefore allows the empty list to be provided. ### Steps to reproduce the bug A trivial reproduction case: ```python from typing import Iterator, Any import pandas as pd from datasets import Dataset def batch_to_examples(batch: dict[str, list[Any]]) -> Iterator[dict[str, Any]]: for i in range(next(iter(lengths))): yield {feature: values[i] for feature, values in batch.items()} def examples_to_batch(examples) -> dict[str, list[Any]]: batch = {} for example in examples: for feature, value in example.items(): if feature not in batch: batch[feature] = [] batch[feature].append(value) return batch def batch_process(examples, explicit_schema: bool): new_examples = [] for example in batch_to_examples(examples): new_examples.append(dict(texts=example["raw_text"].split())) return examples_to_batch(new_examples) df = pd.DataFrame( [ {"raw_text": ""}, {"raw_text": "This is a test"}, {"raw_text": "This is another test"}, ] ) dataset = Dataset.from_pandas(df) # datasets won't be able to typehint a dataset that starts with an empty example. with pytest.raises(TypeError, match="Couldn't cast array of type"): dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, ) ``` This results in crashes like: ```bash File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 2109, in cast_array_to_feature return array_cast(array, feature(), allow_number_to_str=allow_number_to_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1998, in array_cast raise TypeError(f"Couldn't cast array of type {array.type} to {pa_type}") TypeError: Couldn't cast array of type string to null ``` ### Expected behavior The code should successfully map and create a new dataset without error. ### Environment info Mac OSX, Linux Hi @mariosasko thanks for the context, this is helpful to know. Would it be worth having some logic to generate this explicit feature specification automatically if a type annotation for a .map returns a dataclass that can be inferred? Feels like something that would be easy to implement and could save memory / deal with this case in a standardized way.
https://github.com/huggingface/datasets/issues/5965
"Couldn't cast array of type" in complex datasets
> . Would it be worth having some logic to generate this explicit feature specification automatically if a type annotation for a .map returns a dataclass that can be inferred? Interesting proposal! Yes, we could consider doing this if the (return) type hint is `TypedDict`, and raise an error that type hints are incorrect if the cast using the inferred types fails.
### Describe the bug When doing a map of a dataset with complex types, sometimes `datasets` is unable to interpret the valid schema of a returned datasets.map() function. This often comes from conflicting types, like when both empty lists and filled lists are competing for the same field value. This is prone to happen in batch mapping, when the mapper returns a sequence of null/empty values and other batches are non-null. A workaround is to manually cast the new batch to a pyarrow table (like implemented in this [workaround](https://github.com/piercefreeman/lassen/pull/3)) but it feels like this ideally should be solved at the core library level. Note that the reproduction case only throws this error if the first datapoint has the empty list. If it is processed later, datasets already detects its representation as list-type and therefore allows the empty list to be provided. ### Steps to reproduce the bug A trivial reproduction case: ```python from typing import Iterator, Any import pandas as pd from datasets import Dataset def batch_to_examples(batch: dict[str, list[Any]]) -> Iterator[dict[str, Any]]: for i in range(next(iter(lengths))): yield {feature: values[i] for feature, values in batch.items()} def examples_to_batch(examples) -> dict[str, list[Any]]: batch = {} for example in examples: for feature, value in example.items(): if feature not in batch: batch[feature] = [] batch[feature].append(value) return batch def batch_process(examples, explicit_schema: bool): new_examples = [] for example in batch_to_examples(examples): new_examples.append(dict(texts=example["raw_text"].split())) return examples_to_batch(new_examples) df = pd.DataFrame( [ {"raw_text": ""}, {"raw_text": "This is a test"}, {"raw_text": "This is another test"}, ] ) dataset = Dataset.from_pandas(df) # datasets won't be able to typehint a dataset that starts with an empty example. with pytest.raises(TypeError, match="Couldn't cast array of type"): dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, ) ``` This results in crashes like: ```bash File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 2109, in cast_array_to_feature return array_cast(array, feature(), allow_number_to_str=allow_number_to_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1998, in array_cast raise TypeError(f"Couldn't cast array of type {array.type} to {pa_type}") TypeError: Couldn't cast array of type string to null ``` ### Expected behavior The code should successfully map and create a new dataset without error. ### Environment info Mac OSX, Linux
62
"Couldn't cast array of type" in complex datasets ### Describe the bug When doing a map of a dataset with complex types, sometimes `datasets` is unable to interpret the valid schema of a returned datasets.map() function. This often comes from conflicting types, like when both empty lists and filled lists are competing for the same field value. This is prone to happen in batch mapping, when the mapper returns a sequence of null/empty values and other batches are non-null. A workaround is to manually cast the new batch to a pyarrow table (like implemented in this [workaround](https://github.com/piercefreeman/lassen/pull/3)) but it feels like this ideally should be solved at the core library level. Note that the reproduction case only throws this error if the first datapoint has the empty list. If it is processed later, datasets already detects its representation as list-type and therefore allows the empty list to be provided. ### Steps to reproduce the bug A trivial reproduction case: ```python from typing import Iterator, Any import pandas as pd from datasets import Dataset def batch_to_examples(batch: dict[str, list[Any]]) -> Iterator[dict[str, Any]]: for i in range(next(iter(lengths))): yield {feature: values[i] for feature, values in batch.items()} def examples_to_batch(examples) -> dict[str, list[Any]]: batch = {} for example in examples: for feature, value in example.items(): if feature not in batch: batch[feature] = [] batch[feature].append(value) return batch def batch_process(examples, explicit_schema: bool): new_examples = [] for example in batch_to_examples(examples): new_examples.append(dict(texts=example["raw_text"].split())) return examples_to_batch(new_examples) df = pd.DataFrame( [ {"raw_text": ""}, {"raw_text": "This is a test"}, {"raw_text": "This is another test"}, ] ) dataset = Dataset.from_pandas(df) # datasets won't be able to typehint a dataset that starts with an empty example. with pytest.raises(TypeError, match="Couldn't cast array of type"): dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, ) ``` This results in crashes like: ```bash File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 2109, in cast_array_to_feature return array_cast(array, feature(), allow_number_to_str=allow_number_to_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1998, in array_cast raise TypeError(f"Couldn't cast array of type {array.type} to {pa_type}") TypeError: Couldn't cast array of type string to null ``` ### Expected behavior The code should successfully map and create a new dataset without error. ### Environment info Mac OSX, Linux > . Would it be worth having some logic to generate this explicit feature specification automatically if a type annotation for a .map returns a dataclass that can be inferred? Interesting proposal! Yes, we could consider doing this if the (return) type hint is `TypedDict`, and raise an error that type hints are incorrect if the cast using the inferred types fails.
https://github.com/huggingface/datasets/issues/5965
"Couldn't cast array of type" in complex datasets
@mariosasko Put up an initial PR to implement this proposal. Let me know your thoughts on direction and what else should be in-scope here.
### Describe the bug When doing a map of a dataset with complex types, sometimes `datasets` is unable to interpret the valid schema of a returned datasets.map() function. This often comes from conflicting types, like when both empty lists and filled lists are competing for the same field value. This is prone to happen in batch mapping, when the mapper returns a sequence of null/empty values and other batches are non-null. A workaround is to manually cast the new batch to a pyarrow table (like implemented in this [workaround](https://github.com/piercefreeman/lassen/pull/3)) but it feels like this ideally should be solved at the core library level. Note that the reproduction case only throws this error if the first datapoint has the empty list. If it is processed later, datasets already detects its representation as list-type and therefore allows the empty list to be provided. ### Steps to reproduce the bug A trivial reproduction case: ```python from typing import Iterator, Any import pandas as pd from datasets import Dataset def batch_to_examples(batch: dict[str, list[Any]]) -> Iterator[dict[str, Any]]: for i in range(next(iter(lengths))): yield {feature: values[i] for feature, values in batch.items()} def examples_to_batch(examples) -> dict[str, list[Any]]: batch = {} for example in examples: for feature, value in example.items(): if feature not in batch: batch[feature] = [] batch[feature].append(value) return batch def batch_process(examples, explicit_schema: bool): new_examples = [] for example in batch_to_examples(examples): new_examples.append(dict(texts=example["raw_text"].split())) return examples_to_batch(new_examples) df = pd.DataFrame( [ {"raw_text": ""}, {"raw_text": "This is a test"}, {"raw_text": "This is another test"}, ] ) dataset = Dataset.from_pandas(df) # datasets won't be able to typehint a dataset that starts with an empty example. with pytest.raises(TypeError, match="Couldn't cast array of type"): dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, ) ``` This results in crashes like: ```bash File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 2109, in cast_array_to_feature return array_cast(array, feature(), allow_number_to_str=allow_number_to_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1998, in array_cast raise TypeError(f"Couldn't cast array of type {array.type} to {pa_type}") TypeError: Couldn't cast array of type string to null ``` ### Expected behavior The code should successfully map and create a new dataset without error. ### Environment info Mac OSX, Linux
24
"Couldn't cast array of type" in complex datasets ### Describe the bug When doing a map of a dataset with complex types, sometimes `datasets` is unable to interpret the valid schema of a returned datasets.map() function. This often comes from conflicting types, like when both empty lists and filled lists are competing for the same field value. This is prone to happen in batch mapping, when the mapper returns a sequence of null/empty values and other batches are non-null. A workaround is to manually cast the new batch to a pyarrow table (like implemented in this [workaround](https://github.com/piercefreeman/lassen/pull/3)) but it feels like this ideally should be solved at the core library level. Note that the reproduction case only throws this error if the first datapoint has the empty list. If it is processed later, datasets already detects its representation as list-type and therefore allows the empty list to be provided. ### Steps to reproduce the bug A trivial reproduction case: ```python from typing import Iterator, Any import pandas as pd from datasets import Dataset def batch_to_examples(batch: dict[str, list[Any]]) -> Iterator[dict[str, Any]]: for i in range(next(iter(lengths))): yield {feature: values[i] for feature, values in batch.items()} def examples_to_batch(examples) -> dict[str, list[Any]]: batch = {} for example in examples: for feature, value in example.items(): if feature not in batch: batch[feature] = [] batch[feature].append(value) return batch def batch_process(examples, explicit_schema: bool): new_examples = [] for example in batch_to_examples(examples): new_examples.append(dict(texts=example["raw_text"].split())) return examples_to_batch(new_examples) df = pd.DataFrame( [ {"raw_text": ""}, {"raw_text": "This is a test"}, {"raw_text": "This is another test"}, ] ) dataset = Dataset.from_pandas(df) # datasets won't be able to typehint a dataset that starts with an empty example. with pytest.raises(TypeError, match="Couldn't cast array of type"): dataset = dataset.map( batch_process, batched=True, batch_size=1, num_proc=1, remove_columns=dataset.column_names, ) ``` This results in crashes like: ```bash File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 2109, in cast_array_to_feature return array_cast(array, feature(), allow_number_to_str=allow_number_to_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1819, in wrapper return func(array, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/piercefreeman/Library/Caches/pypoetry/virtualenvs/example-9kBqeSPy-py3.11/lib/python3.11/site-packages/datasets/table.py", line 1998, in array_cast raise TypeError(f"Couldn't cast array of type {array.type} to {pa_type}") TypeError: Couldn't cast array of type string to null ``` ### Expected behavior The code should successfully map and create a new dataset without error. ### Environment info Mac OSX, Linux @mariosasko Put up an initial PR to implement this proposal. Let me know your thoughts on direction and what else should be in-scope here.
https://github.com/huggingface/datasets/issues/5963
Got an error _pickle.PicklingError use Dataset.from_spark.
i got error using method from_spark when using multi-node Spark cluster. seems could only use "from_spark" in local?
python 3.9.2 Got an error _pickle.PicklingError use Dataset.from_spark. Did the dataset import load data from spark dataframe using multi-node Spark cluster df = spark.read.parquet(args.input_data).repartition(50) ds = Dataset.from_spark(df, keep_in_memory=True, cache_dir="/pnc-data/data/nuplan/t5_spark/cache_data") ds.save_to_disk(args.output_data) Error : _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transforma tion. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/16 21:17:20 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) _Originally posted by @yanzia12138 in https://github.com/huggingface/datasets/issues/5701#issuecomment-1594674306_ W Traceback (most recent call last): File "/home/work/main.py", line 100, in <module> run(args) File "/home/work/main.py", line 80, in run ds = Dataset.from_spark(df1, keep_in_memory=True, File "/home/work/.local/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 1281, in from_spark return SparkDatasetReader( File "/home/work/.local/lib/python3.9/site-packages/datasets/io/spark.py", line 53, in read self.builder.download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 1004, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 254, in _prepare_split self._validate_cache_dir() File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 122, in _validate_cache_dir self._spark.sparkContext.parallelize(range(1), 1).mapPartitions(create_cache_and_write_probe).collect() File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 950, in collect sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2951, in _jrdd wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer, File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2830, in _wrap_function pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2816, in _prepare_for_python_RDD pickled_command = ser.dumps(command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/serializers.py", line 447, in dumps raise pickle.PicklingError(msg) _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. S parkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/19 13:51:21 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.)
18
Got an error _pickle.PicklingError use Dataset.from_spark. python 3.9.2 Got an error _pickle.PicklingError use Dataset.from_spark. Did the dataset import load data from spark dataframe using multi-node Spark cluster df = spark.read.parquet(args.input_data).repartition(50) ds = Dataset.from_spark(df, keep_in_memory=True, cache_dir="/pnc-data/data/nuplan/t5_spark/cache_data") ds.save_to_disk(args.output_data) Error : _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transforma tion. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/16 21:17:20 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) _Originally posted by @yanzia12138 in https://github.com/huggingface/datasets/issues/5701#issuecomment-1594674306_ W Traceback (most recent call last): File "/home/work/main.py", line 100, in <module> run(args) File "/home/work/main.py", line 80, in run ds = Dataset.from_spark(df1, keep_in_memory=True, File "/home/work/.local/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 1281, in from_spark return SparkDatasetReader( File "/home/work/.local/lib/python3.9/site-packages/datasets/io/spark.py", line 53, in read self.builder.download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 1004, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 254, in _prepare_split self._validate_cache_dir() File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 122, in _validate_cache_dir self._spark.sparkContext.parallelize(range(1), 1).mapPartitions(create_cache_and_write_probe).collect() File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 950, in collect sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2951, in _jrdd wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer, File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2830, in _wrap_function pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2816, in _prepare_for_python_RDD pickled_command = ser.dumps(command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/serializers.py", line 447, in dumps raise pickle.PicklingError(msg) _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. S parkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/19 13:51:21 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) i got error using method from_spark when using multi-node Spark cluster. seems could only use "from_spark" in local?
https://github.com/huggingface/datasets/issues/5963
Got an error _pickle.PicklingError use Dataset.from_spark.
cc @maddiedawson it looks like there an issue with `_validate_cache_dir` ? It looks like the function passed to mapPartitions has a reference to the Spark dataset builder, and therefore contains the SparkContext itself. I think it can be fixed by defining `create_cache_and_write_probe` outside the Spark dataset builder, and pass a `partial(create_cache_and_write_probe, cache_dir=self._cache_dir)` to `mapPartitions`
python 3.9.2 Got an error _pickle.PicklingError use Dataset.from_spark. Did the dataset import load data from spark dataframe using multi-node Spark cluster df = spark.read.parquet(args.input_data).repartition(50) ds = Dataset.from_spark(df, keep_in_memory=True, cache_dir="/pnc-data/data/nuplan/t5_spark/cache_data") ds.save_to_disk(args.output_data) Error : _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transforma tion. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/16 21:17:20 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) _Originally posted by @yanzia12138 in https://github.com/huggingface/datasets/issues/5701#issuecomment-1594674306_ W Traceback (most recent call last): File "/home/work/main.py", line 100, in <module> run(args) File "/home/work/main.py", line 80, in run ds = Dataset.from_spark(df1, keep_in_memory=True, File "/home/work/.local/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 1281, in from_spark return SparkDatasetReader( File "/home/work/.local/lib/python3.9/site-packages/datasets/io/spark.py", line 53, in read self.builder.download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 1004, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 254, in _prepare_split self._validate_cache_dir() File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 122, in _validate_cache_dir self._spark.sparkContext.parallelize(range(1), 1).mapPartitions(create_cache_and_write_probe).collect() File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 950, in collect sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2951, in _jrdd wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer, File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2830, in _wrap_function pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2816, in _prepare_for_python_RDD pickled_command = ser.dumps(command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/serializers.py", line 447, in dumps raise pickle.PicklingError(msg) _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. S parkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/19 13:51:21 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.)
54
Got an error _pickle.PicklingError use Dataset.from_spark. python 3.9.2 Got an error _pickle.PicklingError use Dataset.from_spark. Did the dataset import load data from spark dataframe using multi-node Spark cluster df = spark.read.parquet(args.input_data).repartition(50) ds = Dataset.from_spark(df, keep_in_memory=True, cache_dir="/pnc-data/data/nuplan/t5_spark/cache_data") ds.save_to_disk(args.output_data) Error : _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transforma tion. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/16 21:17:20 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) _Originally posted by @yanzia12138 in https://github.com/huggingface/datasets/issues/5701#issuecomment-1594674306_ W Traceback (most recent call last): File "/home/work/main.py", line 100, in <module> run(args) File "/home/work/main.py", line 80, in run ds = Dataset.from_spark(df1, keep_in_memory=True, File "/home/work/.local/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 1281, in from_spark return SparkDatasetReader( File "/home/work/.local/lib/python3.9/site-packages/datasets/io/spark.py", line 53, in read self.builder.download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 1004, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 254, in _prepare_split self._validate_cache_dir() File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 122, in _validate_cache_dir self._spark.sparkContext.parallelize(range(1), 1).mapPartitions(create_cache_and_write_probe).collect() File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 950, in collect sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2951, in _jrdd wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer, File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2830, in _wrap_function pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2816, in _prepare_for_python_RDD pickled_command = ser.dumps(command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/serializers.py", line 447, in dumps raise pickle.PicklingError(msg) _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. S parkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/19 13:51:21 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) cc @maddiedawson it looks like there an issue with `_validate_cache_dir` ? It looks like the function passed to mapPartitions has a reference to the Spark dataset builder, and therefore contains the SparkContext itself. I think it can be fixed by defining `create_cache_and_write_probe` outside the Spark dataset builder, and pass a `partial(create_cache_and_write_probe, cache_dir=self._cache_dir)` to `mapPartitions`
https://github.com/huggingface/datasets/issues/5963
Got an error _pickle.PicklingError use Dataset.from_spark.
Just saw this; thanks for flagging! Your proposed solution sounds good. I can prepare a PR
python 3.9.2 Got an error _pickle.PicklingError use Dataset.from_spark. Did the dataset import load data from spark dataframe using multi-node Spark cluster df = spark.read.parquet(args.input_data).repartition(50) ds = Dataset.from_spark(df, keep_in_memory=True, cache_dir="/pnc-data/data/nuplan/t5_spark/cache_data") ds.save_to_disk(args.output_data) Error : _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transforma tion. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/16 21:17:20 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) _Originally posted by @yanzia12138 in https://github.com/huggingface/datasets/issues/5701#issuecomment-1594674306_ W Traceback (most recent call last): File "/home/work/main.py", line 100, in <module> run(args) File "/home/work/main.py", line 80, in run ds = Dataset.from_spark(df1, keep_in_memory=True, File "/home/work/.local/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 1281, in from_spark return SparkDatasetReader( File "/home/work/.local/lib/python3.9/site-packages/datasets/io/spark.py", line 53, in read self.builder.download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 1004, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 254, in _prepare_split self._validate_cache_dir() File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 122, in _validate_cache_dir self._spark.sparkContext.parallelize(range(1), 1).mapPartitions(create_cache_and_write_probe).collect() File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 950, in collect sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2951, in _jrdd wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer, File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2830, in _wrap_function pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2816, in _prepare_for_python_RDD pickled_command = ser.dumps(command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/serializers.py", line 447, in dumps raise pickle.PicklingError(msg) _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. S parkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/19 13:51:21 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.)
16
Got an error _pickle.PicklingError use Dataset.from_spark. python 3.9.2 Got an error _pickle.PicklingError use Dataset.from_spark. Did the dataset import load data from spark dataframe using multi-node Spark cluster df = spark.read.parquet(args.input_data).repartition(50) ds = Dataset.from_spark(df, keep_in_memory=True, cache_dir="/pnc-data/data/nuplan/t5_spark/cache_data") ds.save_to_disk(args.output_data) Error : _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transforma tion. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/16 21:17:20 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) _Originally posted by @yanzia12138 in https://github.com/huggingface/datasets/issues/5701#issuecomment-1594674306_ W Traceback (most recent call last): File "/home/work/main.py", line 100, in <module> run(args) File "/home/work/main.py", line 80, in run ds = Dataset.from_spark(df1, keep_in_memory=True, File "/home/work/.local/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 1281, in from_spark return SparkDatasetReader( File "/home/work/.local/lib/python3.9/site-packages/datasets/io/spark.py", line 53, in read self.builder.download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 1004, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 254, in _prepare_split self._validate_cache_dir() File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 122, in _validate_cache_dir self._spark.sparkContext.parallelize(range(1), 1).mapPartitions(create_cache_and_write_probe).collect() File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 950, in collect sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2951, in _jrdd wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer, File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2830, in _wrap_function pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2816, in _prepare_for_python_RDD pickled_command = ser.dumps(command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/serializers.py", line 447, in dumps raise pickle.PicklingError(msg) _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. S parkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/19 13:51:21 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) Just saw this; thanks for flagging! Your proposed solution sounds good. I can prepare a PR
https://github.com/huggingface/datasets/issues/5963
Got an error _pickle.PicklingError use Dataset.from_spark.
@maddiedawson can you show me the demo ,so i can test in local .before your PR
python 3.9.2 Got an error _pickle.PicklingError use Dataset.from_spark. Did the dataset import load data from spark dataframe using multi-node Spark cluster df = spark.read.parquet(args.input_data).repartition(50) ds = Dataset.from_spark(df, keep_in_memory=True, cache_dir="/pnc-data/data/nuplan/t5_spark/cache_data") ds.save_to_disk(args.output_data) Error : _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transforma tion. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/16 21:17:20 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) _Originally posted by @yanzia12138 in https://github.com/huggingface/datasets/issues/5701#issuecomment-1594674306_ W Traceback (most recent call last): File "/home/work/main.py", line 100, in <module> run(args) File "/home/work/main.py", line 80, in run ds = Dataset.from_spark(df1, keep_in_memory=True, File "/home/work/.local/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 1281, in from_spark return SparkDatasetReader( File "/home/work/.local/lib/python3.9/site-packages/datasets/io/spark.py", line 53, in read self.builder.download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 1004, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 254, in _prepare_split self._validate_cache_dir() File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 122, in _validate_cache_dir self._spark.sparkContext.parallelize(range(1), 1).mapPartitions(create_cache_and_write_probe).collect() File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 950, in collect sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2951, in _jrdd wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer, File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2830, in _wrap_function pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2816, in _prepare_for_python_RDD pickled_command = ser.dumps(command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/serializers.py", line 447, in dumps raise pickle.PicklingError(msg) _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. S parkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/19 13:51:21 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.)
16
Got an error _pickle.PicklingError use Dataset.from_spark. python 3.9.2 Got an error _pickle.PicklingError use Dataset.from_spark. Did the dataset import load data from spark dataframe using multi-node Spark cluster df = spark.read.parquet(args.input_data).repartition(50) ds = Dataset.from_spark(df, keep_in_memory=True, cache_dir="/pnc-data/data/nuplan/t5_spark/cache_data") ds.save_to_disk(args.output_data) Error : _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transforma tion. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/16 21:17:20 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) _Originally posted by @yanzia12138 in https://github.com/huggingface/datasets/issues/5701#issuecomment-1594674306_ W Traceback (most recent call last): File "/home/work/main.py", line 100, in <module> run(args) File "/home/work/main.py", line 80, in run ds = Dataset.from_spark(df1, keep_in_memory=True, File "/home/work/.local/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 1281, in from_spark return SparkDatasetReader( File "/home/work/.local/lib/python3.9/site-packages/datasets/io/spark.py", line 53, in read self.builder.download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 909, in download_and_prepare self._download_and_prepare( File "/home/work/.local/lib/python3.9/site-packages/datasets/builder.py", line 1004, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 254, in _prepare_split self._validate_cache_dir() File "/home/work/.local/lib/python3.9/site-packages/datasets/packaged_modules/spark/spark.py", line 122, in _validate_cache_dir self._spark.sparkContext.parallelize(range(1), 1).mapPartitions(create_cache_and_write_probe).collect() File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 950, in collect sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2951, in _jrdd wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer, File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2830, in _wrap_function pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/rdd.py", line 2816, in _prepare_for_python_RDD pickled_command = ser.dumps(command) File "/home/work/.local/lib/python3.9/site-packages/pyspark/serializers.py", line 447, in dumps raise pickle.PicklingError(msg) _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. S parkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063. 23/06/19 13:51:21 WARN ExecutorPodsWatchSnapshotSource: Kubernetes client has been closed (this is expected if the application is shutting down.) @maddiedawson can you show me the demo ,so i can test in local .before your PR
https://github.com/huggingface/datasets/issues/5961
IterableDataset: split by node and map may preprocess samples that will be skipped anyway
Does "number of shards" refer to the total number of data? my config: nproc_per_node=2 ds=ds['train'] = load_dataset(streaming=True).take(50000) I'm test again: in prepare_data(), data have the same for each GPU
There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_
29
IterableDataset: split by node and map may preprocess samples that will be skipped anyway There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_ Does "number of shards" refer to the total number of data? my config: nproc_per_node=2 ds=ds['train'] = load_dataset(streaming=True).take(50000) I'm test again: in prepare_data(), data have the same for each GPU
https://github.com/huggingface/datasets/issues/5961
IterableDataset: split by node and map may preprocess samples that will be skipped anyway
The number of shards is `ds.n_shards`. It corresponds generally to the number of files the dataset is made of, to be able to distribute to several nodes. **You don't end up with the same data per GPU**. But all the samples are going through your preprocessing function you pass to map. They are just skipped afterwards to only keep 1 sample out of n(GPUs)
There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_
64
IterableDataset: split by node and map may preprocess samples that will be skipped anyway There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_ The number of shards is `ds.n_shards`. It corresponds generally to the number of files the dataset is made of, to be able to distribute to several nodes. **You don't end up with the same data per GPU**. But all the samples are going through your preprocessing function you pass to map. They are just skipped afterwards to only keep 1 sample out of n(GPUs)
https://github.com/huggingface/datasets/issues/5961
IterableDataset: split by node and map may preprocess samples that will be skipped anyway
For each GPU, although see the same data in prepare_data(), the actual training data will not be the same in the end. Is my understanding correct? Where can I print the actual training data for each GPU?
There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_
37
IterableDataset: split by node and map may preprocess samples that will be skipped anyway There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_ For each GPU, although see the same data in prepare_data(), the actual training data will not be the same in the end. Is my understanding correct? Where can I print the actual training data for each GPU?
https://github.com/huggingface/datasets/issues/5961
IterableDataset: split by node and map may preprocess samples that will be skipped anyway
> For each GPU, although see the same data in prepare_data(), the actual training data will not be the same in the end. Is my understanding correct? Yes exactly :) > Where can I print the actual training data for each GPU? You should call print in the data_collator
There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_
49
IterableDataset: split by node and map may preprocess samples that will be skipped anyway There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_ > For each GPU, although see the same data in prepare_data(), the actual training data will not be the same in the end. Is my understanding correct? Yes exactly :) > Where can I print the actual training data for each GPU? You should call print in the data_collator
https://github.com/huggingface/datasets/issues/5961
IterableDataset: split by node and map may preprocess samples that will be skipped anyway
I print out n_shards, and under multiple GPUs, this value is always 1. Is this value correct?
There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_
17
IterableDataset: split by node and map may preprocess samples that will be skipped anyway There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_ I print out n_shards, and under multiple GPUs, this value is always 1. Is this value correct?
https://github.com/huggingface/datasets/issues/5961
IterableDataset: split by node and map may preprocess samples that will be skipped anyway
Yes it's correct, and it explains why you always have the same data passed to your map function (the data can't be split). But after being passed to `map`, each GPU keeps one example out of n(GPUs) so that you don't end up with duplicate data across GPUs
There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_
48
IterableDataset: split by node and map may preprocess samples that will be skipped anyway There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_ Yes it's correct, and it explains why you always have the same data passed to your map function (the data can't be split). But after being passed to `map`, each GPU keeps one example out of n(GPUs) so that you don't end up with duplicate data across GPUs
https://github.com/huggingface/datasets/issues/5961
IterableDataset: split by node and map may preprocess samples that will be skipped anyway
> > For each GPU, although see the same data in prepare_data(), the actual training data will not be the same in the end. > > Is my understanding correct? > > Yes exactly :) > > > Where can I print the actual training data for each GPU? > > You should call print in the data_collator OK, when printing the train data in the data collator, each GPU sees different data. Thanks for your reply
There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_
77
IterableDataset: split by node and map may preprocess samples that will be skipped anyway There are two ways an iterable dataset can be split by node: 1. if the number of shards is a factor of number of GPUs: in that case the shards are evenly distributed per GPU 2. otherwise, each GPU iterate on the data and at the end keeps 1 sample out of n(GPUs) - skipping the others. In case 2. it's therefore possible to have the same examples passed to `prepare_dataset` for each GPU. This doesn't sound optimized though, because it runs the preprocessing on samples that won't be used in the end. Could you open a new issue so that we can discuss about this and find a solution ? _Originally posted by @lhoestq in https://github.com/huggingface/datasets/issues/5360#issuecomment-1592729051_ > > For each GPU, although see the same data in prepare_data(), the actual training data will not be the same in the end. > > Is my understanding correct? > > Yes exactly :) > > > Where can I print the actual training data for each GPU? > > You should call print in the data_collator OK, when printing the train data in the data collator, each GPU sees different data. Thanks for your reply
https://github.com/huggingface/datasets/issues/5955
Strange bug in loading local JSON files, using load_dataset
This is the actual error: ``` Failed to read file '/home/lakala/hjc/code/pycode/glm/temp.json' with error <class 'pyarrow.lib.ArrowInvalid'>: cannot mix list and non-list, non-null values ``` Which means some samples are incorrectly formatted. PyArrow, a storage backend that we use under the hood, requires that all the list elements have the same level of nesting (same number of dimensions) or are `None`. ```python import pyarrow as pa pa.array([[1, 2, 3], 2]) # ArrowInvalid: cannot mix list and non-list, non-null values pa.array([[1, 2, 3], [2]]) # works ```
### Describe the bug I am using 'load_dataset 'loads a JSON file, but I found a strange bug: an error will be reported when the length of the JSON file exceeds 160000 (uncertain exact number). I have checked the data through the following code and there are no issues. So I cannot determine the true reason for this error. The data is a list containing a dictionary. As follows: [ {'input': 'someting...', 'target': 'someting...', 'type': 'someting...', 'history': ['someting...', ...]}, ... ] ### Steps to reproduce the bug ``` import json from datasets import load_dataset path = "target.json" temp_path = "temp.json" with open(path, "r") as f: data = json.load(f) print(f"\n-------the JSON file length is: {len(data)}-------\n") with open(temp_path, "w") as f: json.dump(data[:160000], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works when the JSON file length is 160000-------\n") with open(temp_path, "w") as f: json.dump(data[160000:], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works and eliminates data issues-------\n") with open(temp_path, "w") as f: json.dump(data[:170000], f) dataset = load_dataset("json", data_files=temp_path) ``` ### Expected behavior ``` -------the JSON file length is: 173049------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3328.81it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 639.47it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 265.85it/s] -------This works when the JSON file length is 160000------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 2038.05it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 794.83it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 681.00it/s] -------This works and eliminates data issues------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-63f391c89599c7b0/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3682.44it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 788.70it/s] Generating train split: 0 examples [00:00, ? examples/s]Failed to read file '/home/lakala/hjc/code/pycode/glm/temp.json' with error <class 'pyarrow.lib.ArrowInvalid'>: cannot mix list and non-list, non-null values Traceback (most recent call last): File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1858, in _prepare_split_single for _, table in generator: File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/packaged_modules/json/json.py", line 146, in _generate_tables raise ValueError(f"Not able to read records in the JSON file at {file}.") from None ValueError: Not able to read records in the JSON file at /home/lakala/hjc/code/pycode/glm/temp.json. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/lakala/hjc/code/pycode/glm/test.py", line 22, in <module> dataset = load_dataset("json", data_files=temp_path) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/load.py", line 1797, in load_dataset builder_instance.download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 890, in download_and_prepare self._download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 985, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1746, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1891, in _prepare_split_single raise DatasetGenerationError("An error occurred while generating the dataset") from e datasets.builder.DatasetGenerationError: An error occurred while generating the dataset ``` ### Environment info ``` Ubuntu==22.04 python==3.8 pytorch-transformers==1.2.0 transformers== 4.27.1 datasets==2.12.0 numpy==1.24.3 pandas==1.5.3 ```
84
Strange bug in loading local JSON files, using load_dataset ### Describe the bug I am using 'load_dataset 'loads a JSON file, but I found a strange bug: an error will be reported when the length of the JSON file exceeds 160000 (uncertain exact number). I have checked the data through the following code and there are no issues. So I cannot determine the true reason for this error. The data is a list containing a dictionary. As follows: [ {'input': 'someting...', 'target': 'someting...', 'type': 'someting...', 'history': ['someting...', ...]}, ... ] ### Steps to reproduce the bug ``` import json from datasets import load_dataset path = "target.json" temp_path = "temp.json" with open(path, "r") as f: data = json.load(f) print(f"\n-------the JSON file length is: {len(data)}-------\n") with open(temp_path, "w") as f: json.dump(data[:160000], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works when the JSON file length is 160000-------\n") with open(temp_path, "w") as f: json.dump(data[160000:], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works and eliminates data issues-------\n") with open(temp_path, "w") as f: json.dump(data[:170000], f) dataset = load_dataset("json", data_files=temp_path) ``` ### Expected behavior ``` -------the JSON file length is: 173049------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3328.81it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 639.47it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 265.85it/s] -------This works when the JSON file length is 160000------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 2038.05it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 794.83it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 681.00it/s] -------This works and eliminates data issues------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-63f391c89599c7b0/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3682.44it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 788.70it/s] Generating train split: 0 examples [00:00, ? examples/s]Failed to read file '/home/lakala/hjc/code/pycode/glm/temp.json' with error <class 'pyarrow.lib.ArrowInvalid'>: cannot mix list and non-list, non-null values Traceback (most recent call last): File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1858, in _prepare_split_single for _, table in generator: File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/packaged_modules/json/json.py", line 146, in _generate_tables raise ValueError(f"Not able to read records in the JSON file at {file}.") from None ValueError: Not able to read records in the JSON file at /home/lakala/hjc/code/pycode/glm/temp.json. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/lakala/hjc/code/pycode/glm/test.py", line 22, in <module> dataset = load_dataset("json", data_files=temp_path) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/load.py", line 1797, in load_dataset builder_instance.download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 890, in download_and_prepare self._download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 985, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1746, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1891, in _prepare_split_single raise DatasetGenerationError("An error occurred while generating the dataset") from e datasets.builder.DatasetGenerationError: An error occurred while generating the dataset ``` ### Environment info ``` Ubuntu==22.04 python==3.8 pytorch-transformers==1.2.0 transformers== 4.27.1 datasets==2.12.0 numpy==1.24.3 pandas==1.5.3 ``` This is the actual error: ``` Failed to read file '/home/lakala/hjc/code/pycode/glm/temp.json' with error <class 'pyarrow.lib.ArrowInvalid'>: cannot mix list and non-list, non-null values ``` Which means some samples are incorrectly formatted. PyArrow, a storage backend that we use under the hood, requires that all the list elements have the same level of nesting (same number of dimensions) or are `None`. ```python import pyarrow as pa pa.array([[1, 2, 3], 2]) # ArrowInvalid: cannot mix list and non-list, non-null values pa.array([[1, 2, 3], [2]]) # works ```
https://github.com/huggingface/datasets/issues/5955
Strange bug in loading local JSON files, using load_dataset
@mariosasko I used the same operation to check the original data before and after slicing. This is reflected in my code. 160000 is not a specific number. I can also get output using 150000. This doesn't seem to align very well with what you said. Because if only some sample formats are incorrect. So there should be an error in one of the front and back slices. thank you for your reply.
### Describe the bug I am using 'load_dataset 'loads a JSON file, but I found a strange bug: an error will be reported when the length of the JSON file exceeds 160000 (uncertain exact number). I have checked the data through the following code and there are no issues. So I cannot determine the true reason for this error. The data is a list containing a dictionary. As follows: [ {'input': 'someting...', 'target': 'someting...', 'type': 'someting...', 'history': ['someting...', ...]}, ... ] ### Steps to reproduce the bug ``` import json from datasets import load_dataset path = "target.json" temp_path = "temp.json" with open(path, "r") as f: data = json.load(f) print(f"\n-------the JSON file length is: {len(data)}-------\n") with open(temp_path, "w") as f: json.dump(data[:160000], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works when the JSON file length is 160000-------\n") with open(temp_path, "w") as f: json.dump(data[160000:], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works and eliminates data issues-------\n") with open(temp_path, "w") as f: json.dump(data[:170000], f) dataset = load_dataset("json", data_files=temp_path) ``` ### Expected behavior ``` -------the JSON file length is: 173049------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3328.81it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 639.47it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 265.85it/s] -------This works when the JSON file length is 160000------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 2038.05it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 794.83it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 681.00it/s] -------This works and eliminates data issues------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-63f391c89599c7b0/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3682.44it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 788.70it/s] Generating train split: 0 examples [00:00, ? examples/s]Failed to read file '/home/lakala/hjc/code/pycode/glm/temp.json' with error <class 'pyarrow.lib.ArrowInvalid'>: cannot mix list and non-list, non-null values Traceback (most recent call last): File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1858, in _prepare_split_single for _, table in generator: File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/packaged_modules/json/json.py", line 146, in _generate_tables raise ValueError(f"Not able to read records in the JSON file at {file}.") from None ValueError: Not able to read records in the JSON file at /home/lakala/hjc/code/pycode/glm/temp.json. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/lakala/hjc/code/pycode/glm/test.py", line 22, in <module> dataset = load_dataset("json", data_files=temp_path) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/load.py", line 1797, in load_dataset builder_instance.download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 890, in download_and_prepare self._download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 985, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1746, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1891, in _prepare_split_single raise DatasetGenerationError("An error occurred while generating the dataset") from e datasets.builder.DatasetGenerationError: An error occurred while generating the dataset ``` ### Environment info ``` Ubuntu==22.04 python==3.8 pytorch-transformers==1.2.0 transformers== 4.27.1 datasets==2.12.0 numpy==1.24.3 pandas==1.5.3 ```
72
Strange bug in loading local JSON files, using load_dataset ### Describe the bug I am using 'load_dataset 'loads a JSON file, but I found a strange bug: an error will be reported when the length of the JSON file exceeds 160000 (uncertain exact number). I have checked the data through the following code and there are no issues. So I cannot determine the true reason for this error. The data is a list containing a dictionary. As follows: [ {'input': 'someting...', 'target': 'someting...', 'type': 'someting...', 'history': ['someting...', ...]}, ... ] ### Steps to reproduce the bug ``` import json from datasets import load_dataset path = "target.json" temp_path = "temp.json" with open(path, "r") as f: data = json.load(f) print(f"\n-------the JSON file length is: {len(data)}-------\n") with open(temp_path, "w") as f: json.dump(data[:160000], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works when the JSON file length is 160000-------\n") with open(temp_path, "w") as f: json.dump(data[160000:], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works and eliminates data issues-------\n") with open(temp_path, "w") as f: json.dump(data[:170000], f) dataset = load_dataset("json", data_files=temp_path) ``` ### Expected behavior ``` -------the JSON file length is: 173049------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3328.81it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 639.47it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 265.85it/s] -------This works when the JSON file length is 160000------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 2038.05it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 794.83it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 681.00it/s] -------This works and eliminates data issues------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-63f391c89599c7b0/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3682.44it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 788.70it/s] Generating train split: 0 examples [00:00, ? examples/s]Failed to read file '/home/lakala/hjc/code/pycode/glm/temp.json' with error <class 'pyarrow.lib.ArrowInvalid'>: cannot mix list and non-list, non-null values Traceback (most recent call last): File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1858, in _prepare_split_single for _, table in generator: File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/packaged_modules/json/json.py", line 146, in _generate_tables raise ValueError(f"Not able to read records in the JSON file at {file}.") from None ValueError: Not able to read records in the JSON file at /home/lakala/hjc/code/pycode/glm/temp.json. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/lakala/hjc/code/pycode/glm/test.py", line 22, in <module> dataset = load_dataset("json", data_files=temp_path) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/load.py", line 1797, in load_dataset builder_instance.download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 890, in download_and_prepare self._download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 985, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1746, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1891, in _prepare_split_single raise DatasetGenerationError("An error occurred while generating the dataset") from e datasets.builder.DatasetGenerationError: An error occurred while generating the dataset ``` ### Environment info ``` Ubuntu==22.04 python==3.8 pytorch-transformers==1.2.0 transformers== 4.27.1 datasets==2.12.0 numpy==1.24.3 pandas==1.5.3 ``` @mariosasko I used the same operation to check the original data before and after slicing. This is reflected in my code. 160000 is not a specific number. I can also get output using 150000. This doesn't seem to align very well with what you said. Because if only some sample formats are incorrect. So there should be an error in one of the front and back slices. thank you for your reply.
https://github.com/huggingface/datasets/issues/5955
Strange bug in loading local JSON files, using load_dataset
Our JSON loader does the following in your case: ```python import json import pyarrow as pa with open(file, encoding="utf-8") as f: dataset = json.load(f) keys = set().union(*[row.keys() for row in dataset]) mapping = {col: [row.get(col) for row in dataset] for col in keys} pa_table = pa.Table.from_pydict(mapping) # the ArrowInvalid error comes from here ``` So if this code throws an error with correctly-formatted JSON, then this is an Arrow bug and should be reported in their repo. > I used the same operation to check the original data before and after slicing. This is reflected in my code. 160000 is not a specific number. I can also get output using 150000. This doesn't seem to align very well with what you said. Because if only some sample formats are incorrect. So there should be an error in one of the front and back slices. You should shuffle the data to make sure that's not the case
### Describe the bug I am using 'load_dataset 'loads a JSON file, but I found a strange bug: an error will be reported when the length of the JSON file exceeds 160000 (uncertain exact number). I have checked the data through the following code and there are no issues. So I cannot determine the true reason for this error. The data is a list containing a dictionary. As follows: [ {'input': 'someting...', 'target': 'someting...', 'type': 'someting...', 'history': ['someting...', ...]}, ... ] ### Steps to reproduce the bug ``` import json from datasets import load_dataset path = "target.json" temp_path = "temp.json" with open(path, "r") as f: data = json.load(f) print(f"\n-------the JSON file length is: {len(data)}-------\n") with open(temp_path, "w") as f: json.dump(data[:160000], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works when the JSON file length is 160000-------\n") with open(temp_path, "w") as f: json.dump(data[160000:], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works and eliminates data issues-------\n") with open(temp_path, "w") as f: json.dump(data[:170000], f) dataset = load_dataset("json", data_files=temp_path) ``` ### Expected behavior ``` -------the JSON file length is: 173049------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3328.81it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 639.47it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 265.85it/s] -------This works when the JSON file length is 160000------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 2038.05it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 794.83it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 681.00it/s] -------This works and eliminates data issues------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-63f391c89599c7b0/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3682.44it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 788.70it/s] Generating train split: 0 examples [00:00, ? examples/s]Failed to read file '/home/lakala/hjc/code/pycode/glm/temp.json' with error <class 'pyarrow.lib.ArrowInvalid'>: cannot mix list and non-list, non-null values Traceback (most recent call last): File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1858, in _prepare_split_single for _, table in generator: File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/packaged_modules/json/json.py", line 146, in _generate_tables raise ValueError(f"Not able to read records in the JSON file at {file}.") from None ValueError: Not able to read records in the JSON file at /home/lakala/hjc/code/pycode/glm/temp.json. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/lakala/hjc/code/pycode/glm/test.py", line 22, in <module> dataset = load_dataset("json", data_files=temp_path) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/load.py", line 1797, in load_dataset builder_instance.download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 890, in download_and_prepare self._download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 985, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1746, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1891, in _prepare_split_single raise DatasetGenerationError("An error occurred while generating the dataset") from e datasets.builder.DatasetGenerationError: An error occurred while generating the dataset ``` ### Environment info ``` Ubuntu==22.04 python==3.8 pytorch-transformers==1.2.0 transformers== 4.27.1 datasets==2.12.0 numpy==1.24.3 pandas==1.5.3 ```
156
Strange bug in loading local JSON files, using load_dataset ### Describe the bug I am using 'load_dataset 'loads a JSON file, but I found a strange bug: an error will be reported when the length of the JSON file exceeds 160000 (uncertain exact number). I have checked the data through the following code and there are no issues. So I cannot determine the true reason for this error. The data is a list containing a dictionary. As follows: [ {'input': 'someting...', 'target': 'someting...', 'type': 'someting...', 'history': ['someting...', ...]}, ... ] ### Steps to reproduce the bug ``` import json from datasets import load_dataset path = "target.json" temp_path = "temp.json" with open(path, "r") as f: data = json.load(f) print(f"\n-------the JSON file length is: {len(data)}-------\n") with open(temp_path, "w") as f: json.dump(data[:160000], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works when the JSON file length is 160000-------\n") with open(temp_path, "w") as f: json.dump(data[160000:], f) dataset = load_dataset("json", data_files=temp_path) print("\n-------This works and eliminates data issues-------\n") with open(temp_path, "w") as f: json.dump(data[:170000], f) dataset = load_dataset("json", data_files=temp_path) ``` ### Expected behavior ``` -------the JSON file length is: 173049------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3328.81it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 639.47it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-acf3c7f418c5f4b4/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 265.85it/s] -------This works when the JSON file length is 160000------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 2038.05it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 794.83it/s] Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-a42f04b263ceea6a/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4. Subsequent calls will reuse this data. 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 681.00it/s] -------This works and eliminates data issues------- Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-63f391c89599c7b0/0.0.0/e347ab1c932092252e717ff3f949105a4dd28b27e842dd53157d2f72e276c2e4... Downloading data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 3682.44it/s] Extracting data files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 788.70it/s] Generating train split: 0 examples [00:00, ? examples/s]Failed to read file '/home/lakala/hjc/code/pycode/glm/temp.json' with error <class 'pyarrow.lib.ArrowInvalid'>: cannot mix list and non-list, non-null values Traceback (most recent call last): File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1858, in _prepare_split_single for _, table in generator: File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/packaged_modules/json/json.py", line 146, in _generate_tables raise ValueError(f"Not able to read records in the JSON file at {file}.") from None ValueError: Not able to read records in the JSON file at /home/lakala/hjc/code/pycode/glm/temp.json. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/lakala/hjc/code/pycode/glm/test.py", line 22, in <module> dataset = load_dataset("json", data_files=temp_path) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/load.py", line 1797, in load_dataset builder_instance.download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 890, in download_and_prepare self._download_and_prepare( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 985, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1746, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/home/lakala/conda/envs/glm/lib/python3.8/site-packages/datasets/builder.py", line 1891, in _prepare_split_single raise DatasetGenerationError("An error occurred while generating the dataset") from e datasets.builder.DatasetGenerationError: An error occurred while generating the dataset ``` ### Environment info ``` Ubuntu==22.04 python==3.8 pytorch-transformers==1.2.0 transformers== 4.27.1 datasets==2.12.0 numpy==1.24.3 pandas==1.5.3 ``` Our JSON loader does the following in your case: ```python import json import pyarrow as pa with open(file, encoding="utf-8") as f: dataset = json.load(f) keys = set().union(*[row.keys() for row in dataset]) mapping = {col: [row.get(col) for row in dataset] for col in keys} pa_table = pa.Table.from_pydict(mapping) # the ArrowInvalid error comes from here ``` So if this code throws an error with correctly-formatted JSON, then this is an Arrow bug and should be reported in their repo. > I used the same operation to check the original data before and after slicing. This is reflected in my code. 160000 is not a specific number. I can also get output using 150000. This doesn't seem to align very well with what you said. Because if only some sample formats are incorrect. So there should be an error in one of the front and back slices. You should shuffle the data to make sure that's not the case
https://github.com/huggingface/datasets/issues/5953
Bad error message when trying to download gated dataset
cc @sanchit-gandhi @Vaibhavs10 @lhoestq - this is mainly for demos that use Common Voice datasets as done here: https://github.com/facebookresearch/fairseq/tree/main/examples/mms#-transformers
### Describe the bug When I attempt to download a model from the Hub that is gated without being logged in, I get a nice error message. E.g.: E.g. ```sh Repository Not Found for url: https://huggingface.co/api/models/DeepFloyd/IF-I-XL-v1.0. Please make sure you specified the correct `repo_id` and `repo_type`. If you are trying to access a private or gated repo, make sure you are authenticated. Invalid username or password.. Will try to load from local cache. ``` If I do the same for a gated dataset on the Hub, I'm not gated a nice error message IMO: ```sh File ~/hf/lib/python3.10/site-packages/fsspec/implementations/http.py:430, in HTTPFileSystem._info(self, url, **kwargs) 427 except Exception as exc: 428 if policy == "get": 429 # If get failed, then raise a FileNotFoundError --> 430 raise FileNotFoundError(url) from exc 431 logger.debug(str(exc)) 433 return {"name": url, "size": None, **info, "type": "file"} FileNotFoundError: https://huggingface.co/datasets/mozilla-foundation/common_voice_13_0/resolve/main/n_shards.json ``` ### Steps to reproduce the bug ``` huggingface-cli logout ``` and then: ```py from datasets import load_dataset, Audio # English stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "en", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) en_sample = next(iter(stream_data))["audio"]["array"] # Swahili stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "sw", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) sw_sample = next(iter(stream_data))["audio"]["array"] ``` ### Expected behavior Better error message ### Environment info Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.12.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3
19
Bad error message when trying to download gated dataset ### Describe the bug When I attempt to download a model from the Hub that is gated without being logged in, I get a nice error message. E.g.: E.g. ```sh Repository Not Found for url: https://huggingface.co/api/models/DeepFloyd/IF-I-XL-v1.0. Please make sure you specified the correct `repo_id` and `repo_type`. If you are trying to access a private or gated repo, make sure you are authenticated. Invalid username or password.. Will try to load from local cache. ``` If I do the same for a gated dataset on the Hub, I'm not gated a nice error message IMO: ```sh File ~/hf/lib/python3.10/site-packages/fsspec/implementations/http.py:430, in HTTPFileSystem._info(self, url, **kwargs) 427 except Exception as exc: 428 if policy == "get": 429 # If get failed, then raise a FileNotFoundError --> 430 raise FileNotFoundError(url) from exc 431 logger.debug(str(exc)) 433 return {"name": url, "size": None, **info, "type": "file"} FileNotFoundError: https://huggingface.co/datasets/mozilla-foundation/common_voice_13_0/resolve/main/n_shards.json ``` ### Steps to reproduce the bug ``` huggingface-cli logout ``` and then: ```py from datasets import load_dataset, Audio # English stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "en", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) en_sample = next(iter(stream_data))["audio"]["array"] # Swahili stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "sw", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) sw_sample = next(iter(stream_data))["audio"]["array"] ``` ### Expected behavior Better error message ### Environment info Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.12.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 cc @sanchit-gandhi @Vaibhavs10 @lhoestq - this is mainly for demos that use Common Voice datasets as done here: https://github.com/facebookresearch/fairseq/tree/main/examples/mms#-transformers
https://github.com/huggingface/datasets/issues/5953
Bad error message when trying to download gated dataset
Hi ! the error for me is ``` FileNotFoundError: Couldn't find a dataset script at /content/mozilla-foundation/common_voice_13_0/common_voice_13_0.py or any data file in the same directory. Couldn't find 'mozilla-foundation/common_voice_13_0' on the Hugging Face Hub either: FileNotFoundError: Dataset 'mozilla-foundation/common_voice_13_0' doesn't exist on the Hub. If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` And tbh idk how you managed to get your error. "n_shards.json" is not even a thing in `datasets`
### Describe the bug When I attempt to download a model from the Hub that is gated without being logged in, I get a nice error message. E.g.: E.g. ```sh Repository Not Found for url: https://huggingface.co/api/models/DeepFloyd/IF-I-XL-v1.0. Please make sure you specified the correct `repo_id` and `repo_type`. If you are trying to access a private or gated repo, make sure you are authenticated. Invalid username or password.. Will try to load from local cache. ``` If I do the same for a gated dataset on the Hub, I'm not gated a nice error message IMO: ```sh File ~/hf/lib/python3.10/site-packages/fsspec/implementations/http.py:430, in HTTPFileSystem._info(self, url, **kwargs) 427 except Exception as exc: 428 if policy == "get": 429 # If get failed, then raise a FileNotFoundError --> 430 raise FileNotFoundError(url) from exc 431 logger.debug(str(exc)) 433 return {"name": url, "size": None, **info, "type": "file"} FileNotFoundError: https://huggingface.co/datasets/mozilla-foundation/common_voice_13_0/resolve/main/n_shards.json ``` ### Steps to reproduce the bug ``` huggingface-cli logout ``` and then: ```py from datasets import load_dataset, Audio # English stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "en", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) en_sample = next(iter(stream_data))["audio"]["array"] # Swahili stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "sw", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) sw_sample = next(iter(stream_data))["audio"]["array"] ``` ### Expected behavior Better error message ### Environment info Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.12.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3
75
Bad error message when trying to download gated dataset ### Describe the bug When I attempt to download a model from the Hub that is gated without being logged in, I get a nice error message. E.g.: E.g. ```sh Repository Not Found for url: https://huggingface.co/api/models/DeepFloyd/IF-I-XL-v1.0. Please make sure you specified the correct `repo_id` and `repo_type`. If you are trying to access a private or gated repo, make sure you are authenticated. Invalid username or password.. Will try to load from local cache. ``` If I do the same for a gated dataset on the Hub, I'm not gated a nice error message IMO: ```sh File ~/hf/lib/python3.10/site-packages/fsspec/implementations/http.py:430, in HTTPFileSystem._info(self, url, **kwargs) 427 except Exception as exc: 428 if policy == "get": 429 # If get failed, then raise a FileNotFoundError --> 430 raise FileNotFoundError(url) from exc 431 logger.debug(str(exc)) 433 return {"name": url, "size": None, **info, "type": "file"} FileNotFoundError: https://huggingface.co/datasets/mozilla-foundation/common_voice_13_0/resolve/main/n_shards.json ``` ### Steps to reproduce the bug ``` huggingface-cli logout ``` and then: ```py from datasets import load_dataset, Audio # English stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "en", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) en_sample = next(iter(stream_data))["audio"]["array"] # Swahili stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "sw", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) sw_sample = next(iter(stream_data))["audio"]["array"] ``` ### Expected behavior Better error message ### Environment info Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.12.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 Hi ! the error for me is ``` FileNotFoundError: Couldn't find a dataset script at /content/mozilla-foundation/common_voice_13_0/common_voice_13_0.py or any data file in the same directory. Couldn't find 'mozilla-foundation/common_voice_13_0' on the Hugging Face Hub either: FileNotFoundError: Dataset 'mozilla-foundation/common_voice_13_0' doesn't exist on the Hub. If the repo is private or gated, make sure to log in with `huggingface-cli login`. ``` And tbh idk how you managed to get your error. "n_shards.json" is not even a thing in `datasets`
https://github.com/huggingface/datasets/issues/5953
Bad error message when trying to download gated dataset
Okay, I am able to reproduce @patrickvonplaten's original error: https://github.com/Vaibhavs10/scratchpad/blob/main/cv13_datasets_test.ipynb Also not sure why it looks for `n_shards.json`
### Describe the bug When I attempt to download a model from the Hub that is gated without being logged in, I get a nice error message. E.g.: E.g. ```sh Repository Not Found for url: https://huggingface.co/api/models/DeepFloyd/IF-I-XL-v1.0. Please make sure you specified the correct `repo_id` and `repo_type`. If you are trying to access a private or gated repo, make sure you are authenticated. Invalid username or password.. Will try to load from local cache. ``` If I do the same for a gated dataset on the Hub, I'm not gated a nice error message IMO: ```sh File ~/hf/lib/python3.10/site-packages/fsspec/implementations/http.py:430, in HTTPFileSystem._info(self, url, **kwargs) 427 except Exception as exc: 428 if policy == "get": 429 # If get failed, then raise a FileNotFoundError --> 430 raise FileNotFoundError(url) from exc 431 logger.debug(str(exc)) 433 return {"name": url, "size": None, **info, "type": "file"} FileNotFoundError: https://huggingface.co/datasets/mozilla-foundation/common_voice_13_0/resolve/main/n_shards.json ``` ### Steps to reproduce the bug ``` huggingface-cli logout ``` and then: ```py from datasets import load_dataset, Audio # English stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "en", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) en_sample = next(iter(stream_data))["audio"]["array"] # Swahili stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "sw", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) sw_sample = next(iter(stream_data))["audio"]["array"] ``` ### Expected behavior Better error message ### Environment info Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.12.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3
18
Bad error message when trying to download gated dataset ### Describe the bug When I attempt to download a model from the Hub that is gated without being logged in, I get a nice error message. E.g.: E.g. ```sh Repository Not Found for url: https://huggingface.co/api/models/DeepFloyd/IF-I-XL-v1.0. Please make sure you specified the correct `repo_id` and `repo_type`. If you are trying to access a private or gated repo, make sure you are authenticated. Invalid username or password.. Will try to load from local cache. ``` If I do the same for a gated dataset on the Hub, I'm not gated a nice error message IMO: ```sh File ~/hf/lib/python3.10/site-packages/fsspec/implementations/http.py:430, in HTTPFileSystem._info(self, url, **kwargs) 427 except Exception as exc: 428 if policy == "get": 429 # If get failed, then raise a FileNotFoundError --> 430 raise FileNotFoundError(url) from exc 431 logger.debug(str(exc)) 433 return {"name": url, "size": None, **info, "type": "file"} FileNotFoundError: https://huggingface.co/datasets/mozilla-foundation/common_voice_13_0/resolve/main/n_shards.json ``` ### Steps to reproduce the bug ``` huggingface-cli logout ``` and then: ```py from datasets import load_dataset, Audio # English stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "en", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) en_sample = next(iter(stream_data))["audio"]["array"] # Swahili stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "sw", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) sw_sample = next(iter(stream_data))["audio"]["array"] ``` ### Expected behavior Better error message ### Environment info Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.12.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 Okay, I am able to reproduce @patrickvonplaten's original error: https://github.com/Vaibhavs10/scratchpad/blob/main/cv13_datasets_test.ipynb Also not sure why it looks for `n_shards.json`
https://github.com/huggingface/datasets/issues/5953
Bad error message when trying to download gated dataset
Ok I see, this file is downloaded from the CV dataset script - let me investigate
### Describe the bug When I attempt to download a model from the Hub that is gated without being logged in, I get a nice error message. E.g.: E.g. ```sh Repository Not Found for url: https://huggingface.co/api/models/DeepFloyd/IF-I-XL-v1.0. Please make sure you specified the correct `repo_id` and `repo_type`. If you are trying to access a private or gated repo, make sure you are authenticated. Invalid username or password.. Will try to load from local cache. ``` If I do the same for a gated dataset on the Hub, I'm not gated a nice error message IMO: ```sh File ~/hf/lib/python3.10/site-packages/fsspec/implementations/http.py:430, in HTTPFileSystem._info(self, url, **kwargs) 427 except Exception as exc: 428 if policy == "get": 429 # If get failed, then raise a FileNotFoundError --> 430 raise FileNotFoundError(url) from exc 431 logger.debug(str(exc)) 433 return {"name": url, "size": None, **info, "type": "file"} FileNotFoundError: https://huggingface.co/datasets/mozilla-foundation/common_voice_13_0/resolve/main/n_shards.json ``` ### Steps to reproduce the bug ``` huggingface-cli logout ``` and then: ```py from datasets import load_dataset, Audio # English stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "en", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) en_sample = next(iter(stream_data))["audio"]["array"] # Swahili stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "sw", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) sw_sample = next(iter(stream_data))["audio"]["array"] ``` ### Expected behavior Better error message ### Environment info Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.12.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3
16
Bad error message when trying to download gated dataset ### Describe the bug When I attempt to download a model from the Hub that is gated without being logged in, I get a nice error message. E.g.: E.g. ```sh Repository Not Found for url: https://huggingface.co/api/models/DeepFloyd/IF-I-XL-v1.0. Please make sure you specified the correct `repo_id` and `repo_type`. If you are trying to access a private or gated repo, make sure you are authenticated. Invalid username or password.. Will try to load from local cache. ``` If I do the same for a gated dataset on the Hub, I'm not gated a nice error message IMO: ```sh File ~/hf/lib/python3.10/site-packages/fsspec/implementations/http.py:430, in HTTPFileSystem._info(self, url, **kwargs) 427 except Exception as exc: 428 if policy == "get": 429 # If get failed, then raise a FileNotFoundError --> 430 raise FileNotFoundError(url) from exc 431 logger.debug(str(exc)) 433 return {"name": url, "size": None, **info, "type": "file"} FileNotFoundError: https://huggingface.co/datasets/mozilla-foundation/common_voice_13_0/resolve/main/n_shards.json ``` ### Steps to reproduce the bug ``` huggingface-cli logout ``` and then: ```py from datasets import load_dataset, Audio # English stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "en", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) en_sample = next(iter(stream_data))["audio"]["array"] # Swahili stream_data = load_dataset("mozilla-foundation/common_voice_13_0", "sw", split="test", streaming=True) stream_data = stream_data.cast_column("audio", Audio(sampling_rate=16000)) sw_sample = next(iter(stream_data))["audio"]["array"] ``` ### Expected behavior Better error message ### Environment info Copy-and-paste the text below in your GitHub issue. - `datasets` version: 2.12.0 - Platform: Linux-6.2.0-76060200-generic-x86_64-with-glibc2.35 - Python version: 3.10.6 - Huggingface_hub version: 0.16.0.dev0 - PyArrow version: 11.0.0 - Pandas version: 1.5.3 Ok I see, this file is downloaded from the CV dataset script - let me investigate