html_url
stringlengths 48
51
| title
stringlengths 1
290
| comments
sequencelengths 0
30
| body
stringlengths 0
228k
⌀ | number
int64 2
7.08k
|
---|---|---|---|---|
https://github.com/huggingface/datasets/issues/6199 | Use load_dataset for local json files, but it not works | [
"Hugging Face's datasets library may prioritize remote configurations. Make sure there are no conflicting configurations causing the library to prefer downloading data\r\nMay be try debugging\r\nraw_datasets = load_dataset('json', data_files=data_files)\r\nprint(raw_datasets)\r\n",
"It doesn't download them but writes them to the local HF cache. The logging could indeed be better. Does loading the dataset succeed? If it doesn't, can you share the error stack trace?"
] | ### Describe the bug
when I use load_dataset to load my local datasets,it always goes to Hugging Face to download the data instead of loading the local dataset.
### Steps to reproduce the bug
`raw_datasets = load_dataset(
‘json’,
data_files=data_files)`
### Expected behavior
![image](https://github.com/huggingface/datasets/assets/50519434/add3747f-6481-4da7-b374-8f81c5a6472c)
### Environment info
python version 3.8.5
datasets version 2.12
os version unbuntu 18.04 | 6,199 |
https://github.com/huggingface/datasets/issues/6197 | ValueError: 'index=True' is only valid when 'orient' is 'split', 'table', 'index', or 'columns' | [
"Thanks for reporting. We are investigating it.",
"This issue is caused by latest `pandas` release 2.1.0 (released yesterday Aug 30).\r\n\r\nSee: https://github.com/huggingface/datasets/actions/runs/6035484010/job/16375932085?pr=6198\r\n",
"People using previous releases of `datasets` should pin `pandas` in their local environment:\r\n```\r\npython -m pip install 'pandas<2.1.0'\r\n```"
] | ### Describe the bug
Saving a dataset `.to_json()` fails with a `ValueError` since the latest `pandas` [release](https://pandas.pydata.org/docs/dev/whatsnew/v2.1.0.html) (`2.1.0`)
In their latest release we have:
> Improved error handling when using [DataFrame.to_json()](https://pandas.pydata.org/docs/dev/reference/api/pandas.DataFrame.to_json.html#pandas.DataFrame.to_json) with incompatible index and orient arguments ([GH 52143](https://github.com/pandas-dev/pandas/issues/52143))
i.e. an error is now raised for invalid combinations of `index` and `orient`.
This means that unfortunately the custom logic at this line might sometimes lead to contradictions:
https://github.com/huggingface/datasets/blob/029227a116c14720afca71b9b22e78eb2a1c09a6/src/datasets/io/json.py#L96
e.g. for the default case `orient=records` leads to `index=True`, which now raises a `ValueError`
### Steps to reproduce the bug
```python
import datasets
if __name__ == '__main__':
dataset = datasets.Dataset.from_dict({"A": [1, 2, 3], "B": [4, 5, 6]})
dataset.to_json("dataset.json")
```
```shell
>>>
ValueError: 'index=True' is only valid when 'orient' is 'split', 'table', 'index', or 'columns'.
```
### Expected behavior
The dataset is successfully saved as `.json`
### Environment info
`python >= 3.9`
`pandas >= 2.1.0` | 6,197 |
https://github.com/huggingface/datasets/issues/6196 | Split order is not preserved | [] | I have noticed that in some cases the split order is not preserved.
For example, consider a no-script dataset with configs:
```yaml
configs:
- config_name: default
data_files:
- split: train
path: train.csv
- split: test
path: test.csv
```
- Note the defined split order is [train, test]
Once the dataset is loaded, the split order is not preserved:
```python
In [16]: ds
Out[16]:
DatasetDict({
test: Dataset({
features: ['text', 'label'],
num_rows: 1
})
train: Dataset({
features: ['text', 'label'],
num_rows: 2
})
})
```
- Note the obtained split order is [test, train] | 6,196 |
https://github.com/huggingface/datasets/issues/6195 | Force to reuse cache at given path | [
"realized that need to pass the path at `cache_file_name` like\r\n\r\n```python\r\ntokenized_datasets = raw_datasets[\"train\"].map(\r\n tokenize_function,\r\n batched=True,\r\n num_proc=data_args.preprocessing_num_workers,\r\n remove_columns=[text_column_name],\r\n load_from_cache_file=True,\r\n desc=\"Running tokenizer on dataset line_by_line\",\r\n # cache_file_names= {\"train\": \"cache-1982fea76aa54a13.arrow\"}\r\n cache_file_name=\"/project/huggingface_cache/datasets/..../cache-1982fea76aa54a13.arrow\",\r\n new_fingerprint=\"1982fea76aa54a13\"\r\n )\r\n```",
"Thank you so much! I went through a lot of issues before finding similar experiences here. I have to say that the [docs](https://huggingface.co/docs/datasets/v2.11.0/en/package_reference/main_classes#datasets.Dataset.map) of `.map()` is really misleading, probably making people think that just assigning the file name to cache_file_name is enough."
] | ### Describe the bug
I have run the official example of MLM like:
```bash
python run_mlm.py \
--model_name_or_path roberta-base \
--dataset_name togethercomputer/RedPajama-Data-1T \
--dataset_config_name arxiv \
--per_device_train_batch_size 10 \
--preprocessing_num_workers 20 \
--validation_split_percentage 0 \
--cache_dir /project/huggingface_cache/datasets \
--line_by_line \
--do_train \
--pad_to_max_length \
--output_dir /project/huggingface_cache/test-mlm
```
it successfully runs and at my cache folder has `cache-1982fea76aa54a13_00001_of_00020.arrow`..... `cache-1982fea76aa54a13_00020_of_00020.arrow ` as tokenization cache of `map` method. And the cache works fine every time I run the command above.
However, when I switched to jupyter notebook (since I do not want to load datasets every time when I changed other parameters not related to the dataloading). It is not recognizing the cache files and starts to re-run the entire tokenization process.
I changed my code to
```python
tokenized_datasets = raw_datasets["train"].map(
tokenize_function,
batched=True,
num_proc=data_args.preprocessing_num_workers,
remove_columns=[text_column_name],
load_from_cache_file=True,
desc="Running tokenizer on dataset line_by_line",
# cache_file_names= {"train": "cache-1982fea76aa54a13.arrow"}
cache_file_name="cache-1982fea76aa54a13.arrow",
new_fingerprint="1982fea76aa54a13"
)
```
it still does not recognize the previously cached files and trying to re-run the tokenization process.
### Steps to reproduce the bug
use jupyter notebook for dataset map function.
### Expected behavior
the map function accepts the given cache_file_name and new_fingerprint then load the previously cached files.
### Environment info
- `datasets` version: 2.14.4.dev0
- Platform: Linux-3.10.0-1160.59.1.el7.x86_64-x86_64-with-glibc2.10
- Python version: 3.8.8
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3 | 6,195 |
https://github.com/huggingface/datasets/issues/6194 | Support custom fingerprinting with `Dataset.from_generator` | [
"The `fingerprint` parameter serves a slightly different purpose - we use it to inject a new fingerprint after transforming a `Dataset` (computed from the previous fingerprint + transform + transform args), e.g., to be able to compute the cache file for a transform. There is no concept of `fingerprint` before a `Dataset` is fully initialized, but we still need to hash the args (e.g., generator func) of the \"dataset creation methods\" (`from_generator`, `from_csv`, etc.) to compute the cache directory (to store the initial version and transformed dataset versions)\r\n\r\nI agree it should be easier to bypass the hashing mechanism in this instance, too. However, we should probably first address https://github.com/huggingface/datasets/issues/5080 before solving this (e.g., maybe exposing `hash` in `load_dataset`/`load_dataset_builder`.",
"Adding +1 here:\r\n\r\nIf the generator needs to access some external resources or state, then it's not always straightforward to make it pickle-able. So I'd like to be able to override how the default cache key derivation needs to pickle the generator (and of course, I'd accept responsibility for that part of cache consistency).\r\n\r\nAppears to be a recurrent roadbump: #6118 #5963 #5819 #5750 #4983 ",
"Silly hack incoming:\r\n\r\n```python\r\nimport uuid\r\n\r\nclass _DatasetGeneratorPickleHack:\r\n def __init__(self, generator, generator_id=None):\r\n self.generator = generator\r\n self.generator_id = (\r\n generator_id if generator_id is not None else str(uuid.uuid4())\r\n )\r\n\r\n def __call__(self, *args, **kwargs):\r\n return self.generator(*kwargs, **kwargs)\r\n\r\n def __reduce__(self):\r\n return (_DatasetGeneratorPickleHack_raise, (self.generator_id,))\r\n\r\n\r\ndef _DatasetGeneratorPickleHack_raise(*args, **kwargs):\r\n raise AssertionError(\"cannot actually unpickle _DatasetGeneratorPickleHack!\")\r\n```\r\n\r\nNow `Dataset.from_generator(_DatasetGeneratorPickleHack(gen))` works even if `gen` is unpicklable, because Dataset just pickles the shim object that avoids actually traversing `gen`. Then, one can work out how to set `generator_id` meaningfully to allow cache reuse.",
"I'd like some way to do this too. I find that sometimes the hash doesn't cover enough, and that the dataset is not regenerated even when underlying data has changed, and by supplying a custom fingerprint I could do a better job of controlling when my dataset is regenerated.",
"This is what I did and it works: \r\n\r\nhttps://github.com/stevemadere/s3-datasets/blob/e475a566a16d3051656a66f8ff4d3baa4c55a66c/src/tokengenerators/text_ds_2_tokens_generator.py#L200\r\n"
] | ### Feature request
When using `Dataset.from_generator`, the generator is hashed when building the fingerprint. Similar to `.map`, it would be interesting to let the user bypass this hashing by accepting a `fingerprint` argument to `.from_generator`.
### Motivation
Using the `.from_generator` constructor with a non-picklable generator fails. By accepting a `fingerprint` argument to `.from_generator`, the user would have the opportunity to manually fingerprint the dataset and thus bypass the crash.
### Your contribution
If validated, I can try to submit a PR for this. | 6,194 |
https://github.com/huggingface/datasets/issues/6193 | Dataset loading script method does not work with .pyc file | [
"Before dynamically loading `.py` scripts with `importlib.import_module`, we also parse their contents to check imports, which is tricky to implement for binary `.pyc` files (requires parsing bytecode), so I don't think this is something we want to support (unless more users request it ofc) as this use case is a bit too specific.\r\n\r\n@lhoestq What's your opinion on this?",
"> Before dynamically loading .py scripts with importlib.import_module, we also parse their contents to check imports, which is tricky to implement for binary .pyc files (requires parsing bytecode), so I don't think this is something we want to support (unless more users request it ofc) as this use case is a bit too specific.\r\n\r\nYes indeed. Though you can use a .py that imports a package that contains your .pyc code and that you previously installed",
"Hi @lhoestq ,\r\nCould you share some example code related to the approach that you are suggesting? "
] | ### Describe the bug
The huggingface dataset library specifically looks for ‘.py’ file while loading the dataset using loading script approach and it does not work with ‘.pyc’ file.
While deploying in production, it becomes an issue when we are restricted to use only .pyc files. Is there any work around for this ?
### Steps to reproduce the bug
1. Create a dataset loading script to read the custom data.
2. compile the code to make sure that .pyc file is created
3. Delete the loading script and re-run the code. Usually, python should make use of complied .pyc files. However, in this case, the dataset library errors out with the message that it's unable to find the data loader loading script.
### Expected behavior
The code should make use of .pyc file and run without any error.
### Environment info
NA | 6,193 |
https://github.com/huggingface/datasets/issues/6190 | `Invalid user token` even when correct user token is passed! | [
"This is because `download_config.use_auth_token` is deprecated - you should use `download_config.token` instead",
"Works! Thanks for the quick fix! <3"
] | ### Describe the bug
I'm working on a dataset which comprises other datasets on the hub.
URL: https://huggingface.co/datasets/open-asr-leaderboard/datasets-test-only
Note: Some of the sub-datasets in this metadataset require explicit access.
All the other datasets work fine, except, `common_voice`.
### Steps to reproduce the bug
https://github.com/Vaibhavs10/scratchpad/blob/main/cv_datasets_bug_repro.ipynb
### Expected behavior
It should work if the provided access token is valid (as it does for all the other datasets)
### Environment info
datasets version -> 2.14.4 | 6,190 |
https://github.com/huggingface/datasets/issues/6188 | [Feature Request] Check the length of batch before writing so that empty batch is allowed | [
"I think this error means you filter all examples within an (input) batch by deleting its columns. In that case, to avoid the error, you can set the column value to an empty list (`input_batch[\"col\"] = []`) instead."
] | ### Use Case
I use `dataset.map(process_fn, batched=True)` to process the dataset, with data **augmentations or filtering**. However, when all examples within a batch is filtered out, i.e. **an empty batch is returned**, the following error will be thrown:
```
ValueError: Schema and number of arrays unequal
```
This is because the empty batch does not comply with the schema of other batches. I think an empty batch should be allowed to facilitate coding (one does not need to assign an empty list manually for all keys.)
A simple fix is to check the length of `batch` before writing:
```
if len(batch):
writer.write_batch(batch)
```
instead of
https://github.com/huggingface/datasets/blob/74d60213dcbd7c99484c62ce1d3dfd90a1df0770/src/datasets/arrow_dataset.py#L3493
| 6,188 |
https://github.com/huggingface/datasets/issues/6187 | Couldn't find a dataset script at /content/tsv/tsv.py or any data file in the same directory | [
"Hi! You can load this dataset with:\r\n```python\r\ndata_files = {\r\n \"train\": \"/content/PUBHEALTH/train.tsv\",\r\n \"validation\": \"/content/PUBHEALTH/dev.tsv\",\r\n \"test\": \"/content/PUBHEALTH/test.tsv\",\r\n}\r\n\r\ntsv_datasets_reloaded = load_dataset(\"csv\", data_files=data_files, sep=\"\\t\")\r\n```\r\n\r\nTo support your `load_dataset` call, defining aliases for the packaged builders, as suggested in https://github.com/huggingface/datasets/issues/5625, must be implemented. We can consider adding this feature if more people request it.\r\n \r\n(Also answered on the Discord [here](https://discord.com/channels/879548962464493619/1145956791134470224/1146071491260186744))"
] | ### Describe the bug
```
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
[<ipython-input-48-6a7b3e847019>](https://localhost:8080/#) in <cell line: 7>()
5 }
6
----> 7 csv_datasets_reloaded = load_dataset("tsv", data_files=data_files)
8 csv_datasets_reloaded
2 frames
[/usr/local/lib/python3.10/dist-packages/datasets/load.py](https://localhost:8080/#) in dataset_module_factory(path, revision, download_config, download_mode, dynamic_modules_path, data_dir, data_files, **download_kwargs)
1489 raise e1 from None
1490 if isinstance(e1, FileNotFoundError):
-> 1491 raise FileNotFoundError(
1492 f"Couldn't find a dataset script at {relative_to_absolute_path(combined_path)} or any data file in the same directory. "
1493 f"Couldn't find '{path}' on the Hugging Face Hub either: {type(e1).__name__}: {e1}"
FileNotFoundError: Couldn't find a dataset script at /content/tsv/tsv.py or any data file in the same directory. Couldn't find 'tsv' on the Hugging Face Hub either: FileNotFoundError: Dataset 'tsv' doesn't exist on the Hub
```
### Steps to reproduce the bug
```
data_files = {
"train": "/content/PUBHEALTH/train.tsv",
"validation": "/content/PUBHEALTH/dev.tsv",
"test": "/content/PUBHEALTH/test.tsv",
}
tsv_datasets_reloaded = load_dataset("tsv", data_files=data_files)
tsv_datasets_reloaded
```
```
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-48-6a7b3e847019> in <cell line: 7>()
5 }
6
----> 7 csv_datasets_reloaded = load_dataset("tsv", data_files=data_files)
8 csv_datasets_reloaded
2 frames
/usr/local/lib/python3.10/dist-packages/datasets/load.py in dataset_module_factory(path, revision, download_config, download_mode, dynamic_modules_path, data_dir, data_files, **download_kwargs)
1489 raise e1 from None
1490 if isinstance(e1, FileNotFoundError):
-> 1491 raise FileNotFoundError(
1492 f"Couldn't find a dataset script at {relative_to_absolute_path(combined_path)} or any data file in the same directory. "
1493 f"Couldn't find '{path}' on the Hugging Face Hub either: {type(e1).__name__}: {e1}"
FileNotFoundError: Couldn't find a dataset script at /content/tsv/tsv.py or any data file in the same directory. Couldn't find 'tsv' on the Hugging Face Hub either: FileNotFoundError: Dataset 'tsv' doesn't exist on the Hub
```
### Expected behavior
load the data, push to hub
### Environment info
jupyter notebook RTX 3090 | 6,187 |
https://github.com/huggingface/datasets/issues/6186 | Feature request: add code example of multi-GPU processing | [
"That'd be a great idea! @mariosasko or @lhoestq, would it be possible to fix the code snippet or do you have another suggested way for doing this?",
"Indeed `if __name__ == \"__main__\"` is important in this case.\r\n\r\nNot sure about the imbalanced GPU usage though, but maybe you can try using the `torch.cuda.device` context manager ?\r\n\r\n> also, should I do it like this or use nn.DataParallel?\r\n\r\nIn this case you wouldn't need a multiprocessed map no ? Since nn.DataParallel would take care of parallelism",
"Adding this Tweet for reference: https://twitter.com/jxmnop/status/1716834517909119019.",
"I think the issue is that we set `CUDA_VISIBLE_DEVICES` after pytorch is imported ?\r\n\r\nWe should use `torch.cuda.set_device(...)` instead",
"@lhoestq \r\n> In this case you wouldn't need a multiprocessed map no ?\r\n\r\nYes. But how to load a model to 2 GPU simultaneously without something like accelerate?",
"> @lhoestq\r\n> \r\n> > In this case you wouldn't need a multiprocessed map no ?\r\n> \r\n> Yes. But how to load a model to 2 GPU simultaneously without something like accelerate?\r\n\r\nTake a look at this fix #6550 . Basically, you move the model to each GPU inside of the function to be mapped. \r\n\r\n",
"In case someone also runs into this issue, I wrote a [blog post](https://forrestbao.github.io/2024/01/30/datasets_map_with_rank_multiple_GPUs.html) with a complete working example by compiling information from several PRs and issues here. Hope it can help. This issue cost me a few hours. I hope my blog post can save you time before the official document gets fixed. ",
"Thanks ! I updated the docs in https://github.com/huggingface/datasets/pull/6550",
"hey @forrestbao , i was too struggling with the same issue for weeks hence i checked out your blog. great work on the blog. \r\nhowever i wanted to ask you could we scale up the process by reinitializing the same model on the same GPU multiple times for even more speedups ? \r\n\r\ni mean to say given that on a multi GPU setup where GPU vram is above 40GB each, after intializing the translation model which is barely 1-2GB in VRAM size, the rest of VRAM sits idle, how could i keep creating multiple instances of the same model on the same GPU for all GPUs to maxmize flops ? ",
"You can use one single instance on your GPU and increase the batch size until you fill the VRAM",
"@lhoestq i tried that, but i noticed that after a certain number of batch_size, using a larger batch_size makes the overall process really slow than using a lower batch_size.",
"Hi @lhoestq , could you help with my two questions: \r\n1. You mentioned `if __name__ == \"__main__\"`, why is that? I tried with a toy dataset and didn't put this line, my two GPU usage looks balanced. \r\n2. Is there any difference between \r\n`from multiprocess import set_start_method` and `from multiprocessing import set_start_method`? The latter is Python's built-in library. In [the official doc](https://huggingface.co/docs/datasets/en/process), it uses `from multiprocess import set_start_method`, but it gives me error like \r\n```\r\n[jobuser@f6e2419a0a63d45638da-n0-0 ~]$ python test.py\r\nTraceback (most recent call last):\r\n File \"/home/jobuser/test.py\", line 33, in <module>\r\n updated_dataset = dataset.map(\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 593, in wrapper\r\n out: Union[\"Dataset\", \"DatasetDict\"] = func(self, *args, **kwargs)\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 558, in wrapper\r\n out: Union[\"Dataset\", \"DatasetDict\"] = func(self, *args, **kwargs)\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3189, in map\r\n with Pool(len(kwargs_per_job)) as pool:\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/context.py\", line 119, in Pool\r\n return Pool(processes, initializer, initargs, maxtasksperchild,\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/pool.py\", line 191, in __init__\r\n self._setup_queues()\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/pool.py\", line 343, in _setup_queues\r\n self._inqueue = self._ctx.SimpleQueue()\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/context.py\", line 113, in SimpleQueue\r\n return SimpleQueue(ctx=self.get_context())\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/queues.py\", line 339, in __init__\r\n self._rlock = ctx.Lock()\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/context.py\", line 68, in Lock\r\n return Lock(ctx=self.get_context())\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/synchronize.py\", line 168, in __init__\r\n SemLock.__init__(self, SEMAPHORE, 1, 1, ctx=ctx)\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/synchronize.py\", line 86, in __init__\r\n register(self._semlock.name, \"semaphore\")\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/resource_tracker.py\", line 150, in register\r\n self._send('REGISTER', name, rtype)\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/resource_tracker.py\", line 157, in _send\r\n self.ensure_running()\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/resource_tracker.py\", line 124, in ensure_running\r\n pid = util.spawnv_passfds(exe, args, fds_to_pass)\r\n File \"/home/jobuser/.local/lib/python3.10/site-packages/multiprocess/util.py\", line 452, in spawnv_passfds\r\n return _posixsubprocess.fork_exec(\r\nTypeError: fork_exec() takes exactly 21 arguments (17 given)\r\n```\r\nwhich seems caused by python version. I am using Python 3.10.2. ",
"Hi ! \r\n\r\n> You mentioned if __name__ == \"__main__\", why is that? I tried with a toy dataset and didn't put this line, my two GPU usage looks balanced.\r\n\r\nIt's a good practice when doing multiprocessing in python. Depending on the multiprocessing method and your python version, python could re-run the code in your main.py in subprocesses that you don't want to re-run (e.g. recursively spawning processes and failing). Though some multiprocessing methods don't re-run main.py and it appears to be your case ;)\r\n\r\n> Is there any difference between\r\nfrom multiprocess import set_start_method and from multiprocessing import set_start_method? The latter is Python's built-in library. In [the official doc](https://huggingface.co/docs/datasets/en/process), it uses from multiprocess import set_start_method, but it gives me error like\r\n\r\nYes, `datasets` uses `multiprocess` which is a separate library from the built-in `multiprocessing`.\r\n\r\n`multiprocess` is an extended version of `multiprocessing` which allows e.g. to pass `lambda` functions to subprocesses",
"Thanks @lhoestq for explanation. Is it okay we use `multiprocessing` for set_start_method given the above-mentioned issue for multiprocess? From my run with toy example, it's fine. Just want to check if you foresee any problems. ",
"Not sure whether `multiprocessing.set_start_method` has any effect actually since we use `dill` for multiprocessed `map()`",
"I'm running the [code example of multi-GPU processing](https://huggingface.co/docs/datasets/en/process#multiprocessing) on a Linux 8x A100 instance. The entire python code run time is 30 seconds faster if I add one line to set torch number of threads immediately after the `import torch` statement. It loads faster to the eight GPUs (however the map() progress bars take similar amount of time without/with this additional line).\r\n```\r\nimport torch\r\ntorch.set_num_threads(1) # I added this line.\r\n\r\nfrom multiprocess import set_start_method\r\n```\r\nFWIW: my instance has these versions.\r\n```\r\nCUDA 12.2 driver 535.161.08\r\nPython 3.10.12\r\ntorch '2.2.2'\r\nmultiprocess '0.70.16'\r\ntransformers '4.39.2'\r\ndatasets '2.18.0'\r\n```"
] | ### Feature request
Would be great to add a code example of how to do multi-GPU processing with 🤗 Datasets in the documentation. cc @stevhliu
Currently the docs has a small [section](https://huggingface.co/docs/datasets/v2.3.2/en/process#map) on this saying "your big GPU call goes here", however it didn't work for me out-of-the-box.
Let's say you have a PyTorch model that can do translation, and you have multiple GPUs. In that case, you'd like to duplicate the model on each GPU, each processing (translating) a chunk of the data in parallel.
Here's how I tried to do that:
```
from datasets import load_dataset
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from multiprocess import set_start_method
import torch
import os
dataset = load_dataset("mlfoundations/datacomp_small")
tokenizer = AutoTokenizer.from_pretrained("facebook/nllb-200-distilled-600M")
model = AutoModelForSeq2SeqLM.from_pretrained("facebook/nllb-200-distilled-600M")
# put model on each available GPU
# also, should I do it like this or use nn.DataParallel?
model.to("cuda:0")
model.to("cuda:1")
set_start_method("spawn")
def translate_captions(batch, rank):
os.environ["CUDA_VISIBLE_DEVICES"] = str(rank % torch.cuda.device_count())
texts = batch["text"]
inputs = tokenizer(texts, padding=True, truncation=True, return_tensors="pt").to(model.device)
translated_tokens = model.generate(
**inputs, forced_bos_token_id=tokenizer.lang_code_to_id["eng_Latn"], max_length=30
)
translated_texts = tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)
batch["translated_text"] = translated_texts
return batch
updated_dataset = dataset.map(translate_captions, with_rank=True, num_proc=2, batched=True, batch_size=256)
```
I've personally tried running this script on a machine with 2 A100 GPUs.
## Error 1
Running the code snippet above from the terminal (python script.py) resulted in the following error:
```
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/spawn.py", line 125, in _main
prepare(preparation_data)
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/spawn.py", line 236, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/spawn.py", line 287, in _fixup_main_from_path
main_content = runpy.run_path(main_path,
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/runpy.py", line 289, in run_path
return _run_module_code(code, init_globals, run_name,
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/runpy.py", line 96, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/home/niels/python_projects/datacomp/datasets_multi_gpu.py", line 16, in <module>
set_start_method("spawn")
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/context.py", line 247, in set_start_method
raise RuntimeError('context has already been set')
RuntimeError: context has already been set
```
## Error 2
Then, based on [this Stackoverflow answer](https://stackoverflow.com/a/71616344/7762882), I put the `set_start_method("spawn")` section in a try: catch block. This resulted in the following error:
```
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/datasets/dataset_dict.py", line 817, in <dictcomp>
k: dataset.map(
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/datasets/arrow_dataset.py", line 2926, in map
with Pool(nb_of_missing_shards, initargs=initargs, initializer=initializer) as pool:
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/context.py", line 119, in Pool
return Pool(processes, initializer, initargs, maxtasksperchild,
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/pool.py", line 215, in __init__
self._repopulate_pool()
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/pool.py", line 306, in _repopulate_pool
return self._repopulate_pool_static(self._ctx, self.Process,
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/pool.py", line 329, in _repopulate_pool_static
w.start()
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/process.py", line 121, in start
self._popen = self._Popen(self)
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/context.py", line 288, in _Popen
return Popen(process_obj)
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/popen_spawn_posix.py", line 32, in __init__
super().__init__(process_obj)
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/popen_fork.py", line 19, in __init__
self._launch(process_obj)
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/popen_spawn_posix.py", line 42, in _launch
prep_data = spawn.get_preparation_data(process_obj._name)
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/spawn.py", line 154, in get_preparation_data
_check_not_importing_main()
File "/home/niels/anaconda3/envs/datacomp/lib/python3.10/site-packages/multiprocess/spawn.py", line 134, in _check_not_importing_main
raise RuntimeError('''
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
```
So then I put the last line under a `if __name__ == '__main__':` block. Then the code snippet seemed to work, but it seemed that it's only leveraging a single GPU (based on monitoring `nvidia-smi`):
```
Mon Aug 28 12:19:24 2023
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 515.65.01 Driver Version: 515.65.01 CUDA Version: 11.7 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 NVIDIA A100-SXM... On | 00000000:01:00.0 Off | 0 |
| N/A 55C P0 76W / 275W | 8747MiB / 81920MiB | 0% Default |
| | | Disabled |
+-------------------------------+----------------------+----------------------+
| 1 NVIDIA A100-SXM... On | 00000000:47:00.0 Off | 0 |
| N/A 67C P0 274W / 275W | 59835MiB / 81920MiB | 100% Default |
| | | Disabled |
```
Both GPUs should have equal GPU usage, but I've always noticed that the last GPU has way more usage than the other ones. This made me think that `os.environ["CUDA_VISIBLE_DEVICES"] = str(rank % torch.cuda.device_count())` might not work inside a Python script, especially if done after importing PyTorch?
### Motivation
Would be great to clarify how to do multi-GPU data processing.
### Your contribution
If my code snippet can be fixed, I can contribute it to the docs :) | 6,186 |
https://github.com/huggingface/datasets/issues/6185 | Error in saving the PIL image into *.arrow files using datasets.arrow_writer | [
"You can cast the `input_image` column to the `Image` type to fix the issue:\r\n```python\r\nds.cast_column(\"input_image\", datasets.Image())\r\n```"
] | ### Describe the bug
I am using the ArrowWriter from datasets.arrow_writer to save a json-style file as arrow files. Within the dictionary, it contains a feature called "image" which is a list of PIL.Image objects.
I am saving the json using the following script:
```
def save_to_arrow(path,temp):
with ArrowWriter(path=path,writer_batch_size=20) as writer:
writer.write_batch(temp)
writer.finalize()
```
However, when I attempt to restore the dataset and use the ```Dataset.from_file(path)``` function to load the arrow file, there seems to be an issue with the PIL.Image object in the dataset. The list of PIL.Images appears as follows rather than a normal PIL.Image object:
![1693051705440](https://github.com/huggingface/datasets/assets/14247682/03b204c2-d0fa-4d19-beff-6f4d7b83c848)
### Steps to reproduce the bug
1. Storing the data json into arrow files:
```
def save_to_arrow(path,temp):
with ArrowWriter(path=path,writer_batch_size=20) as writer:
writer.write_batch(temp)
writer.finalize()
save_to_arrow( path, json_file )
```
2. try to load the arrow file into the Dataset object using the ```Dataset.from_file(path)```
### Expected behavior
Except to saving the contained "image" feature as a list PIL.Image objects as the arrow file. And I can restore the dataset from the file.
### Environment info
- `datasets` version: 2.12.0
- Platform: Linux-5.4.0-150-generic-x86_64-with-glibc2.17
- Python version: 3.8.17
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 1.4.4 | 6,185 |
https://github.com/huggingface/datasets/issues/6184 | Map cache does not detect function changes in another module | [
"This issue is a duplicate of https://github.com/huggingface/datasets/issues/3297. This is a limitation of `dill`, a package we use for caching (non-`__main__` module objects are serialized by reference). You can find more info about it here: https://github.com/uqfoundation/dill/issues/424.\r\n\r\nIn your case, moving \r\n```\r\ndata = datasets.load_dataset('json', data_files=['/tmp/test.json'], split='train')\r\ndata = data.map(transform)\r\n``` \r\nto `test.py` and setting `transform.__module__ = None` at the end of `dataset.py` should fix the issue.",
"I understand this may be a limitation of an upstream tool, but for a user for datasets this is very annoying, as when you have dozens of different datasets with different preprocessing functions you can't really move them all into the same file. It may be worth seeing if there is a way to specialize the dependency (eg. subclass it) and enforce behaviors that makes sense for your product.\r\n\r\nI was able to work around this for now by setting `__module__ = None`. If such workarounds are required for now it may be better to document it somewhere than a single obscure issue from a long time ago.\r\n\r\nAs this is a duplicate issue I'm closing it.\r\n\r\nI have another issue with the cache https://github.com/huggingface/datasets/issues/6179 can you take a look?"
] | ```python
# dataset.py
import os
import datasets
if not os.path.exists('/tmp/test.json'):
with open('/tmp/test.json', 'w') as file:
file.write('[{"text": "hello"}]')
def transform(example):
text = example['text']
# text += ' world'
return {'text': text}
data = datasets.load_dataset('json', data_files=['/tmp/test.json'], split='train')
data = data.map(transform)
```
```python
# test.py
import dataset
print(next(iter(dataset.data)))
```
Initialize cache
```
python3 test.py
# {'text': 'hello'}
```
Edit dataset.py and uncomment the commented line, run again
```
python3 test.py
# {'text': 'hello'}
# expected: {'text': 'hello world'}
```
Clear cache and run again
```
rm -rf ~/.cache/huggingface/datasets/*
python3 test.py
# {'text': 'hello world'}
```
If instead the two files are combined, then changes to the function are detected correctly. But it's expected when working on any realistic codebase that things will be modularized into separate files. | 6,184 |
https://github.com/huggingface/datasets/issues/6183 | Load dataset with non-existent file | [
"Same problem",
"This was fixed in https://github.com/huggingface/datasets/pull/6155, which will be included in the next release (or you can install `datasets` from source to use it immediately)."
] | ### Describe the bug
When load a dataset from datasets and pass a wrong path to json with the data, error message does not contain something abount "wrong path" or "file do not exist" -
```SchemaInferenceError: Please pass `features` or at least one example when writing data```
### Steps to reproduce the bug
```python
from datasets import load_dataset
load_dataset('json', data_files='/home/alexey/unreal_file.json')
```
### Expected behavior
Raise os FileNotFound error or custom error with informative message
### Environment info
```
# packages in environment at /home/alexey/.conda/envs/alex_LoRA:
#
# Name Version Build Channel
_libgcc_mutex 0.1 main
_openmp_mutex 5.1 1_gnu
accelerate 0.21.0 pypi_0 pypi
aiohttp 3.8.5 pypi_0 pypi
aiosignal 1.3.1 pypi_0 pypi
antlr4-python3-runtime 4.9.3 pypi_0 pypi
appdirs 1.4.4 pypi_0 pypi
asttokens 2.0.5 pyhd3eb1b0_0
async-timeout 4.0.3 pypi_0 pypi
attrs 23.1.0 pypi_0 pypi
backcall 0.2.0 pyhd3eb1b0_0
bitsandbytes 0.41.1 pypi_0 pypi
bzip2 1.0.8 h7b6447c_0
ca-certificates 2023.05.30 h06a4308_0
certifi 2023.7.22 pypi_0 pypi
charset-normalizer 3.2.0 pypi_0 pypi
click 8.1.6 pypi_0 pypi
cmake 3.27.2 pypi_0 pypi
comm 0.1.2 py310h06a4308_0
contourpy 1.1.0 pypi_0 pypi
cycler 0.11.0 pypi_0 pypi
datasets 2.14.4 pypi_0 pypi
debugpy 1.6.7 py310h6a678d5_0
decorator 5.1.1 pyhd3eb1b0_0
dill 0.3.7 pypi_0 pypi
docker-pycreds 0.4.0 pypi_0 pypi
executing 0.8.3 pyhd3eb1b0_0
filelock 3.12.2 pypi_0 pypi
fire 0.5.0 pypi_0 pypi
fonttools 4.42.0 pypi_0 pypi
frozenlist 1.4.0 pypi_0 pypi
fsspec 2023.6.0 pypi_0 pypi
gitdb 4.0.10 pypi_0 pypi
gitpython 3.1.32 pypi_0 pypi
huggingface-hub 0.16.4 pypi_0 pypi
idna 3.4 pypi_0 pypi
ipykernel 6.25.0 py310h2f386ee_0
ipython 8.12.2 py310h06a4308_0
ipython-genutils 0.2.0 pypi_0 pypi
ipywidgets 8.0.4 py310h06a4308_0
jedi 0.18.1 py310h06a4308_1
jinja2 3.1.2 pypi_0 pypi
jsonschema 4.19.0 pypi_0 pypi
jsonschema-specifications 2023.7.1 pypi_0 pypi
jupyter_client 8.1.0 py310h06a4308_0
jupyter_core 5.3.0 py310h06a4308_0
jupyterlab_widgets 3.0.5 py310h06a4308_0
kiwisolver 1.4.4 pypi_0 pypi
ld_impl_linux-64 2.38 h1181459_1
libffi 3.3 he6710b0_2
libgcc-ng 11.2.0 h1234567_1
libgomp 11.2.0 h1234567_1
libsodium 1.0.18 h7b6447c_0
libstdcxx-ng 11.2.0 h1234567_1
libuuid 1.41.5 h5eee18b_0
lightning-utilities 0.9.0 pypi_0 pypi
lit 16.0.6 pypi_0 pypi
markupsafe 2.1.3 pypi_0 pypi
matplotlib 3.7.2 pypi_0 pypi
matplotlib-inline 0.1.6 py310h06a4308_0
mpmath 1.3.0 pypi_0 pypi
multidict 6.0.4 pypi_0 pypi
multiprocess 0.70.15 pypi_0 pypi
nbformat 4.2.0 pypi_0 pypi
ncurses 6.4 h6a678d5_0
nest-asyncio 1.5.6 py310h06a4308_0
networkx 3.1 pypi_0 pypi
numpy 1.25.2 pypi_0 pypi
nvidia-cublas-cu11 11.10.3.66 pypi_0 pypi
nvidia-cuda-cupti-cu11 11.7.101 pypi_0 pypi
nvidia-cuda-nvrtc-cu11 11.7.99 pypi_0 pypi
nvidia-cuda-runtime-cu11 11.7.99 pypi_0 pypi
nvidia-cudnn-cu11 8.5.0.96 pypi_0 pypi
nvidia-cufft-cu11 10.9.0.58 pypi_0 pypi
nvidia-curand-cu11 10.2.10.91 pypi_0 pypi
nvidia-cusolver-cu11 11.4.0.1 pypi_0 pypi
nvidia-cusparse-cu11 11.7.4.91 pypi_0 pypi
nvidia-nccl-cu11 2.14.3 pypi_0 pypi
nvidia-nvtx-cu11 11.7.91 pypi_0 pypi
omegaconf 2.3.0 pypi_0 pypi
openssl 1.1.1v h7f8727e_0
packaging 23.0 py310h06a4308_0
pandas 2.0.3 pypi_0 pypi
parso 0.8.3 pyhd3eb1b0_0
pathtools 0.1.2 pypi_0 pypi
peft 0.4.0 pypi_0 pypi
pexpect 4.8.0 pyhd3eb1b0_3
pickleshare 0.7.5 pyhd3eb1b0_1003
pillow 10.0.0 pypi_0 pypi
pip 23.2.1 py310h06a4308_0
platformdirs 2.5.2 py310h06a4308_0
plotly 5.16.1 pypi_0 pypi
prompt-toolkit 3.0.36 py310h06a4308_0
protobuf 4.24.0 pypi_0 pypi
psutil 5.9.0 py310h5eee18b_0
ptyprocess 0.7.0 pyhd3eb1b0_2
pure_eval 0.2.2 pyhd3eb1b0_0
pyarrow 12.0.1 pypi_0 pypi
pygments 2.15.1 py310h06a4308_1
pyparsing 3.0.9 pypi_0 pypi
python 3.10.0 h12debd9_5
python-dateutil 2.8.2 pyhd3eb1b0_0
pytorch-lightning 2.0.6 pypi_0 pypi
pytz 2023.3 pypi_0 pypi
pyyaml 6.0.1 pypi_0 pypi
pyzmq 25.1.0 py310h6a678d5_0
readline 8.2 h5eee18b_0
referencing 0.30.2 pypi_0 pypi
regex 2023.8.8 pypi_0 pypi
requests 2.31.0 pypi_0 pypi
rpds-py 0.9.2 pypi_0 pypi
safetensors 0.3.2 pypi_0 pypi
scipy 1.11.1 pypi_0 pypi
sentencepiece 0.1.99 pypi_0 pypi
sentry-sdk 1.29.2 pypi_0 pypi
setproctitle 1.3.2 pypi_0 pypi
setuptools 68.0.0 py310h06a4308_0
six 1.16.0 pyhd3eb1b0_1
smmap 5.0.0 pypi_0 pypi
sqlite 3.41.2 h5eee18b_0
stack_data 0.2.0 pyhd3eb1b0_0
sympy 1.12 pypi_0 pypi
tenacity 8.2.3 pypi_0 pypi
termcolor 2.3.0 pypi_0 pypi
tk 8.6.12 h1ccaba5_0
tokenizers 0.13.3 pypi_0 pypi
torch 2.0.1 pypi_0 pypi
torchmetrics 1.0.3 pypi_0 pypi
tornado 6.3.2 py310h5eee18b_0
tqdm 4.66.1 pypi_0 pypi
traitlets 5.7.1 py310h06a4308_0
transformers 4.31.0 pypi_0 pypi
triton 2.0.0 pypi_0 pypi
typing-extensions 4.7.1 pypi_0 pypi
tzdata 2023.3 pypi_0 pypi
urllib3 2.0.4 pypi_0 pypi
wandb 0.15.8 pypi_0 pypi
wcwidth 0.2.5 pyhd3eb1b0_0
wheel 0.38.4 py310h06a4308_0
widgetsnbextension 4.0.5 py310h06a4308_0
xxhash 3.3.0 pypi_0 pypi
xz 5.4.2 h5eee18b_0
yarl 1.9.2 pypi_0 pypi
zeromq 4.3.4 h2531618_0
zlib 1.2.13 h5eee18b_0
active environment : None
user config file : /home/alexey/.condarc
populated config files :
conda version : 23.1.0
conda-build version : 3.22.0
python version : 3.9.13.final.0
virtual packages : __archspec=1=x86_64
__cuda=12.0=0
__glibc=2.35=0
__linux=5.19.0=0
__unix=0=0
base environment : /opt/anaconda/anaconda3 (read only)
conda av data dir : /opt/anaconda/anaconda3/etc/conda
conda av metadata url : None
channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
https://repo.anaconda.com/pkgs/main/noarch
https://repo.anaconda.com/pkgs/r/linux-64
https://repo.anaconda.com/pkgs/r/noarch
package cache : /opt/anaconda/anaconda3/pkgs
/home/alexey/.conda/pkgs
envs directories : /home/alexey/.conda/envs
/opt/anaconda/anaconda3/envs
platform : linux-64
user-agent : conda/23.1.0 requests/2.31.0 CPython/3.9.13 Linux/5.19.0-46-generic ubuntu/22.04.2 glibc/2.35
UID:GID : 1009:1009
netrc file : /home/alexey/.netrc
offline mode : False
``` | 6,183 |
https://github.com/huggingface/datasets/issues/6182 | Loading Meteor metric in HF evaluate module crashes due to datasets import issue | [
"Our minimal Python version requirement is 3.8, so we dropped `importlib_metadata`. \r\n\r\nFeel free to open a PR in the `evaluate` repo to replace the problematic import with\r\n```python\r\nif PY_VERSION < version.parse(\"3.8\"):\r\n import importlib_metadata\r\nelse:\r\n import importlib.metadata as importlib_metadata\r\n```",
"Any idea when you guys will release the next version which deals with this problem?\r\nI'm still having the same issue with py 3.10 when I install the lib with pip.\r\nI'm assuming that it has not yet been updated since the merge was 3 days ago.",
"Yes, this requires a new `evaluate` release (cc @lvwerra for this). \r\n\r\nIn the meantime, you can get the fixed version by installing `evaluate` from `main`: `pip install git+https://github.com/huggingface/evaluate.git`",
"I'll aim for a release this week!"
] | ### Describe the bug
When using python3.9 and ```evaluate``` module loading Meteor metric crashes at a non-existent import from ```datasets.config``` in ```datasets v2.14```
### Steps to reproduce the bug
```
from evaluate import load
meteor = load("meteor")
```
produces the following error:
```
from datasets.config import importlib_metadata, version
ImportError: cannot import name 'importlib_metadata' from 'datasets.config' (<path_to_project>/venv/lib/python3.9/site-packages/datasets/config.py)
```
### Expected behavior
```datasets``` of v2.10 has the following workaround in ```config.py```:
```
if PY_VERSION < version.parse("3.8"):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
```
However, it's absent in v2.14 which might be the cause of the issue.
### Environment info
- `datasets` version: 2.14.4
- Platform: macOS-13.5-arm64-arm-64bit
- Python version: 3.9.6
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3
- Evaluate version: 0.4.0 | 6,182 |
https://github.com/huggingface/datasets/issues/6179 | Map cache with tokenizer | [
"https://github.com/huggingface/datasets/issues/5147 may be a solution, by passing in the tokenizer in a fn_kwargs and ignoring it in the fingerprint calculations",
"I have a similar issue. I was using a Jupyter Notebook and every time I call the map function it performs tokenization from scratch again although the cache files of last run still exists. \r\n\r\nI ran with 20 processes and now in the cache folder there are two groups of cached results of tokenized dataset:\r\n\r\n```\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 12:56:46 2023 cache-1982fea76aa54a13_00001_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 13:02:08 2023 cache-1982fea76aa54a13_00004_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 12:56:40 2023 cache-1982fea76aa54a13_00005_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 241 MB Sat Aug 26 12:50:59 2023 cache-1982fea76aa54a13_00006_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 12:57:37 2023 cache-1982fea76aa54a13_00007_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 12:57:31 2023 cache-1982fea76aa54a13_00008_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 12:59:47 2023 cache-1982fea76aa54a13_00010_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 241 MB Sat Aug 26 12:59:44 2023 cache-1982fea76aa54a13_00011_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 241 MB Sat Aug 26 12:55:24 2023 cache-1982fea76aa54a13_00012_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 241 MB Sat Aug 26 12:56:21 2023 cache-1982fea76aa54a13_00013_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 12:57:24 2023 cache-1982fea76aa54a13_00014_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 13:00:48 2023 cache-1982fea76aa54a13_00015_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 12:56:56 2023 cache-1982fea76aa54a13_00017_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 12:56:54 2023 cache-1982fea76aa54a13_00018_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Sat Aug 26 12:57:27 2023 cache-1982fea76aa54a13_00019_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:15:40 2023 cache-454431f643cdc5e8_00000_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:16:46 2023 cache-454431f643cdc5e8_00001_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:14:53 2023 cache-454431f643cdc5e8_00002_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:13:10 2023 cache-454431f643cdc5e8_00003_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:13:04 2023 cache-454431f643cdc5e8_00004_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:16:42 2023 cache-454431f643cdc5e8_00005_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 241 MB Wed Aug 23 19:01:29 2023 cache-454431f643cdc5e8_00006_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:16:41 2023 cache-454431f643cdc5e8_00007_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:14:04 2023 cache-454431f643cdc5e8_00008_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:17:41 2023 cache-454431f643cdc5e8_00009_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:17:06 2023 cache-454431f643cdc5e8_00010_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 241 MB Wed Aug 23 19:17:16 2023 cache-454431f643cdc5e8_00011_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 241 MB Wed Aug 23 19:15:13 2023 cache-454431f643cdc5e8_00012_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 241 MB Wed Aug 23 19:16:01 2023 cache-454431f643cdc5e8_00013_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:16:35 2023 cache-454431f643cdc5e8_00014_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:16:20 2023 cache-454431f643cdc5e8_00015_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:14:48 2023 cache-454431f643cdc5e8_00016_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 18:59:32 2023 cache-454431f643cdc5e8_00017_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:17:58 2023 cache-454431f643cdc5e8_00018_of_00020.arrow\r\n.rw-r--r-- fad3ew bii_dsc_community 240 MB Wed Aug 23 19:15:25 2023 cache-454431f643cdc5e8_00019_of_00020.arrow\r\n```\r\n\r\ncan we specify the cache file for map so that it won't redo everything again?",
"@Luosuu [map](https://huggingface.co/docs/datasets/v2.14.4/en/package_reference/main_classes#datasets.Dataset.map) has cache_file_name parameter\r\n\r\nIn my case, I do want the cache to detect when the map function changes, so I can't pass a constant cache file name.",
"Implementing a proper hashing function for the (fast) tokenizers is currently impossible for the reasons mentioned in the referenced issues. So the only alternative to the `cache_file_name` (or `new_fingerprint`) parameter is a custom serializer (e.g., that deserializes the tokenizer from a local save path) defined using `copyreg` or a class that wraps the tokenizer object and has `__reduce__`(`__setstate__`/`__getstate__`) "
] | Similar issue to https://github.com/huggingface/datasets/issues/5985, but across different sessions rather than two calls in the same session.
Unlike that issue, explicitly calling tokenizer(my_args) before the map() doesn't help, because the tokenizer was created with a different hash to begin with...
setup
```
from transformers import AutoTokenizer
AutoTokenizer.from_pretrained('bert-base-uncased').save_pretrained("tok")
```
this prints different value each time
```
from transformers import AutoTokenizer
from datasets.utils.py_utils import dumps # Huggingface datasets
print(hash(dumps(AutoTokenizer.from_pretrained("tok"))))
``` | 6,179 |
https://github.com/huggingface/datasets/issues/6178 | 'import datasets' throws "invalid syntax error" | [
"This seems to be related to your environment and not the `datasets` code (e.g., this could happen when exposing the Python 3.9 site packages to a lower Python version (interpreter))"
] | ### Describe the bug
Hi,
I have been trying to import the datasets library but I keep gtting this error.
`Traceback (most recent call last):
File /opt/local/jupyterhub/lib64/python3.9/site-packages/IPython/core/interactiveshell.py:3508 in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
Cell In[2], line 1
import datasets
File /opt/local/jupyterhub/lib64/python3.9/site-packages/datasets/__init__.py:22
from .arrow_dataset import Dataset
File /opt/local/jupyterhub/lib64/python3.9/site-packages/datasets/arrow_dataset.py:67
from .arrow_writer import ArrowWriter, OptimizedTypedSequence
File /opt/local/jupyterhub/lib64/python3.9/site-packages/datasets/arrow_writer.py:27
from .features import Features, Image, Value
File /opt/local/jupyterhub/lib64/python3.9/site-packages/datasets/features/__init__.py:17
from .audio import Audio
File /opt/local/jupyterhub/lib64/python3.9/site-packages/datasets/features/audio.py:11
from ..download.streaming_download_manager import xopen, xsplitext
File /opt/local/jupyterhub/lib64/python3.9/site-packages/datasets/download/__init__.py:10
from .streaming_download_manager import StreamingDownloadManager
File /opt/local/jupyterhub/lib64/python3.9/site-packages/datasets/download/streaming_download_manager.py:18
from aiohttp.client_exceptions import ClientError
File /opt/local/jupyterhub/lib64/python3.9/site-packages/aiohttp/__init__.py:7
from .connector import * # noqa
File /opt/local/jupyterhub/lib64/python3.9/site-packages/aiohttp/connector.py:12
from .client import ClientRequest
File /opt/local/jupyterhub/lib64/python3.9/site-packages/aiohttp/client.py:144
yield from asyncio.async(resp.release(), loop=loop)
^
SyntaxError: invalid syntax`
I have simply used these commands:
`import datasets`
and
`from datasets import load_dataset`
### Environment info
The library has been installed a virtual machine on JupyterHub. Although I have used this library multiple times (on the same VM) before, to train/test an ASR or other ML models, I had never encountered this error. | 6,178 |
https://github.com/huggingface/datasets/issues/6176 | how to limit the size of memory mapped file? | [
"Hi! Can you share the error this reproducer throws in your environment? `streaming=True` streams the dataset as it's iterated over without creating a memory-map file.",
"The trace of the error. Streaming works but is slower.\r\n```\r\nRoot Cause (first observed failure):\r\n[0]:\r\n time : 2023-08-24_06:06:01\r\n host : compute-126.cm.cluster\r\n rank : 0 (local_rank: 0)\r\n exitcode : 1 (pid: 48442)\r\n error_file: /tmp/torchelastic_4fqzcuuz/none_rx2470jl/attempt_0/0/error.json\r\n traceback : Traceback (most recent call last):\r\n File \"/users/yli7/.conda/envs/pytorch2.0/lib/python3.8/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py\", line 346, in wrapper\r\n return f(*args, **kwargs)\r\n File \"Pretrain.py\", line 214, in main\r\n pair_dataset, c4_dataset = create_dataset('pretrain', config)\r\n File \"/dcs05/qiao/data/william/project/DaVinci/dataset/__init__.py\", line 109, in create_dataset\r\n c4_dataset = load_dataset(\"c4\", \"en\", split=\"train\").to_iterable_dataset(num_shards=1024).map(pre_caption_huggingface)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/load.py\", line 1810, in load_dataset\r\n ds = builder_instance.as_dataset(split=split, verification_mode=verification_mode, in_memory=keep_in_memory)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/builder.py\", line 1145, in as_dataset\r\n datasets = map_nested(\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/utils/py_utils.py\", line 436, in map_nested\r\n return function(data_struct)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/builder.py\", line 1175, in _build_single_dataset\r\n ds = self._as_dataset(\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/builder.py\", line 1246, in _as_dataset\r\n dataset_kwargs = ArrowReader(cache_dir, self.info).read(\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 244, in read\r\n return self.read_files(files=files, original_instructions=instructions, in_memory=in_memory)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 265, in read_files\r\n pa_table = self._read_files(files, in_memory=in_memory)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 200, in _read_files\r\n pa_table: Table = self._get_table_from_filename(f_dict, in_memory=in_memory)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 336, in _get_table_from_filename\r\n table = ArrowReader.read_table(filename, in_memory=in_memory)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 357, in read_table\r\n return table_cls.from_file(filename)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/table.py\", line 1059, in from_file\r\n table = _memory_mapped_arrow_table_from_file(filename)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/table.py\", line 65, in _memory_mapped_arrow_table_from_file\r\n opened_stream = _memory_mapped_record_batch_reader_from_file(filename)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/table.py\", line 50, in _memory_mapped_record_batch_reader_from_file\r\n memory_mapped_stream = pa.memory_map(filename)\r\n File \"pyarrow/io.pxi\", line 1009, in pyarrow.lib.memory_map\r\n File \"pyarrow/io.pxi\", line 956, in pyarrow.lib.MemoryMappedFile._open\r\n File \"pyarrow/error.pxi\", line 144, in pyarrow.lib.pyarrow_internal_check_status\r\n File \"pyarrow/error.pxi\", line 115, in pyarrow.lib.check_status\r\n OSError: Memory mapping file failed: Cannot allocate memory\r\n```",
"This issue has previously been reported here: https://github.com/huggingface/datasets/issues/5710. Reporting it in the Arrow repo makes more sense as they have control over memory mapping.\r\n\r\nPS: this is the API to reduce the size of the generated Arrow file:\r\n```python\r\nfrom datasets import load_dataset\r\nbuilder = load_dataset_builder(\"c4\", \"en\")\r\nbuilder.download_and_prepare(max_shard_size=\"5GB\")\r\ndataset = builder.as_dataset()\r\n```\r\n\r\nIf this resolves the issue, we can consider exposing `max_shard_size` in `load_dataset`.",
"Thanks for the response. The problem seems not resolved. The memory I allocated to the environment is 64G and the following error still occurs\r\n`Python 3.8.16 (default, Jun 12 2023, 18:09:05) \r\n[GCC 11.2.0] :: Anaconda, Inc. on linux\r\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\r\n>>> from datasets import load_dataset_builder\r\n>>> builder = load_dataset_builder(\"c4\", \"en\")\r\n>>> builder.download_and_prepare(max_shard_size=\"5GB\")\r\nFound cached dataset c4 (/users/yli7/.cache/huggingface/datasets/c4/en/0.0.0/df532b158939272d032cc63ef19cd5b83e9b4d00c922b833e4cb18b2e9869b01)\r\n>>> dataset = builder.as_dataset()\r\n 0%| | 0/2 [00:00<?, ?it/s]Traceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/builder.py\", line 1145, in as_dataset\r\n datasets = map_nested(\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/utils/py_utils.py\", line 444, in map_nested\r\n mapped = [\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/utils/py_utils.py\", line 445, in <listcomp>\r\n _single_map_nested((function, obj, types, None, True, None))\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/utils/py_utils.py\", line 347, in _single_map_nested\r\n return function(data_struct)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/builder.py\", line 1175, in _build_single_dataset\r\n ds = self._as_dataset(\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/builder.py\", line 1246, in _as_dataset\r\n dataset_kwargs = ArrowReader(cache_dir, self.info).read(\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 244, in read\r\n return self.read_files(files=files, original_instructions=instructions, in_memory=in_memory)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 265, in read_files\r\n pa_table = self._read_files(files, in_memory=in_memory)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 200, in _read_files\r\n pa_table: Table = self._get_table_from_filename(f_dict, in_memory=in_memory)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 336, in _get_table_from_filename\r\n table = ArrowReader.read_table(filename, in_memory=in_memory)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/arrow_reader.py\", line 357, in read_table\r\n return table_cls.from_file(filename)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/table.py\", line 1059, in from_file\r\n table = _memory_mapped_arrow_table_from_file(filename)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/table.py\", line 65, in _memory_mapped_arrow_table_from_file\r\n opened_stream = _memory_mapped_record_batch_reader_from_file(filename)\r\n File \"/users/yli7/.local/lib/python3.8/site-packages/datasets/table.py\", line 50, in _memory_mapped_record_batch_reader_from_file\r\n memory_mapped_stream = pa.memory_map(filename)\r\n File \"pyarrow/io.pxi\", line 1009, in pyarrow.lib.memory_map\r\n File \"pyarrow/io.pxi\", line 956, in pyarrow.lib.MemoryMappedFile._open\r\n File \"pyarrow/error.pxi\", line 144, in pyarrow.lib.pyarrow_internal_check_status\r\n File \"pyarrow/error.pxi\", line 115, in pyarrow.lib.check_status\r\nOSError: Memory mapping file failed: Cannot allocate memory`",
"Have you solved the problem?",
"Nope. Streaming works but is slower."
] | ### Describe the bug
Huggingface datasets use memory-mapped file to map large datasets in memory for fast access.
However, it seems like huggingface will occupy all the memory for memory-mapped files, which makes a troublesome situation since we cluster will distribute a small portion of memory to me (once it's over the limit, memory cannot be allocated), however, when the dataset checks the total memory, all of the memory will be taken into account which makes huggingface dataset try to allocate more memory than allowed.
So is there a way to explicitly limit the size of memory mapped file?
### Steps to reproduce the bug
python
>>> from datasets import load_dataset
>>> dataset = load_dataset("c4", "en", streaming=True)
### Expected behavior
In a normal environment, this will not have any problem.
However, when the system allocates a portion of the memory to the program and when the dataset checks the total memory, all of the memory will be taken into account which makes huggingface dataset try to allocate more memory than allowed.
### Environment info
linux cluster with SGE(Sun Grid Engine) | 6,176 |
https://github.com/huggingface/datasets/issues/6173 | Fix CI for pyarrow 13.0.0 | [] | pyarrow 13.0.0 just came out
```
FAILED tests/test_formatting.py::ArrowExtractorTest::test_pandas_extractor - AssertionError: Attributes of Series are different
Attribute "dtype" are different
[left]: datetime64[us, UTC]
[right]: datetime64[ns, UTC]
```
```
FAILED tests/test_table.py::test_cast_sliced_fixed_size_array_to_features - TypeError: Couldn't cast array of type
fixed_size_list<item: int32>[3]
to
Sequence(feature=Value(dtype='int64', id=None), length=3, id=None)
```
e.g. in https://github.com/huggingface/datasets/actions/runs/5952253963/job/16143847230
first error may be related to https://github.com/apache/arrow/issues/33321
second one maybe because `feature.length * len(array) == len(array_values)` is not satisfied anymore somehow ? | 6,173 |
https://github.com/huggingface/datasets/issues/6172 | Make Dataset streaming queries retryable | [
"Hi! The streaming mode also retries requests - `datasets.config.STREAMING_READ_MAX_RETRIES` (20 sec by default) controls the number of retries and `datasets.config.STREAMING_READ_RETRY_INTERVAL` (5 sec) the sleep time between retries.\r\n\r\n> At step 1800 I got a 504 HTTP status code error from Huggingface hub for my pytorch dataloader\r\n\r\nA minor Hub outage that we experienced yesterday could be the cause.",
"I wanted something similar. I have a huge dataset I want to process (laion-2b), but after processing several batches, it sometimes fails with this error: `HTTP 502 Bad Gateway for url`. I had the following code to handle it but this way I believe it restarts processing the data from the first batch? How can I set the attribute values you mention above?\r\n\r\n```\r\niterable_dataset = load_dataset(\"laion/laion2B-multi\", streaming=True, split='train')\r\ndataloader = DataLoader(iterable_dataset, batch_size=131072, collate_fn=custom_collate_fn, num_workers=8)\r\n\r\nMAX_RETRIES = 5\r\nRETRY_WAIT = 10 # wait 10 seconds before retry\r\n\r\n for retry in range(MAX_RETRIES):\r\n try:\r\n for j, batch in enumerate(dataloader):\r\n < process batch>\r\n\r\n except HfHubHTTPError as e:\r\n if \"502\" in str(e) and retry < MAX_RETRIES - 1:\r\n logging.warning(f\"Encountered a 502 error on batch {j}. Waiting for {RETRY_WAIT} seconds before retrying.\")\r\n time.sleep(RETRY_WAIT)\r\n continue\r\n else:\r\n raise",
"Hey all! Wondering if there's a way of making Datasets streaming mode somewhat robust to Hub outages? Over the weekend, I got two quite cryptic errors, which I reckon were probably from Hub issues:\r\n\r\n<details>\r\n<summary> Stack Trace 1 </summary>\r\n\r\n```\r\n File \"/home/sanchitgandhi/small-12-4-tpu-timestamped-prob-0.2/run_distillation.py\", line 2119, in <module>\r\n main()\r\n File \"/home/sanchitgandhi/small-12-4-tpu-timestamped-prob-0.2/run_distillation.py\", line 1954, in main\r\n for batch in train_loader:\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/dataloader.py\", line 630, in __next__\r\n data = self._next_data()\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/dataloader.py\", line 1325, in _next_data\r\n return self._process_data(data)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/dataloader.py\", line 1371, in _process_data\r\n data.reraise()\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/_utils.py\", line 694, in reraise\r\n raise exception\r\nConnectionError: Caught ConnectionError in DataLoader worker process 8.\r\nOriginal Traceback (most recent call last):\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/aiohttp/connector.py\", line 1155, in _create_direct_connection\r\n hosts = await asyncio.shield(host_resolved)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/aiohttp/connector.py\", line 874, in _resolve_host\r\n addrs = await self._resolver.resolve(host, port, family=self._family)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/aiohttp/resolver.py\", line 33, in resolve\r\n infos = await self._loop.getaddrinfo(\r\n File \"/usr/lib/python3.10/asyncio/base_events.py\", line 863, in getaddrinfo\r\n return await self.run_in_executor(\r\n File \"/usr/lib/python3.10/concurrent/futures/thread.py\", line 58, in run\r\n result = self.fn(*self.args, **self.kwargs)\r\n File \"/usr/lib/python3.10/socket.py\", line 955, in getaddrinfo\r\n for res in _socket.getaddrinfo(host, port, family, type, proto, flags):\r\nsocket.gaierror: [Errno -3] Temporary failure in name resolution\r\nThe above exception was the direct cause of the following exception:\r\nTraceback (most recent call last):\r\n File \"/home/sanchitgandhi/datasets/src/datasets/download/streaming_download_manager.py\", line 333, in read_with_retries\r\n out = read(*args, **kwargs)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/fsspec/implementations/http.py\", line 612, in read\r\n return super().read(length)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/fsspec/spec.py\", line 1856, in read\r\n out = self.cache._fetch(self.loc, self.loc + length)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/fsspec/caching.py\", line 439, in _fetch\r\n new = self.fetcher(self.end, bend)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/fsspec/asyn.py\", line 118, in wrapper\r\n return sync(self.loop, func, *args, **kwargs)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/fsspec/asyn.py\", line 103, in sync\r\n raise return_result\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/fsspec/asyn.py\", line 56, in _runner\r\n result[0] = await coro\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/fsspec/implementations/http.py\", line 660, in async_fetch_range\r\n r = await self.session.get(\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/aiohttp/client.py\", line 562, in _request\r\n conn = await self._connector.connect(\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/aiohttp/connector.py\", line 540, in connect\r\n proto = await self._create_connection(req, traces, timeout)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/aiohttp/connector.py\", line 901, in _create_connection\r\n _, proto = await self._create_direct_connection(req, traces, timeout)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/aiohttp/connector.py\", line 1169, in _create_direct_connection\r\n raise ClientConnectorError(req.connection_key, exc) from exc\r\naiohttp.client_exceptions.ClientConnectorError: Cannot connect to host huggingface.co:443 ssl:default [Temporary failure in name resolution]\r\nThe above exception was the direct cause of the following exception:\r\nTraceback (most recent call last):\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/_utils/worker.py\", line 308, in _worker_loop\r\n data = fetcher.fetch(index)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py\", line 32, in fetch\r\n data.append(next(self.dataset_iter))\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 1358, in __iter__\r\n yield from self._iter_pytorch()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 1293, in _iter_pytorch\r\n for key, example in ex_iterable:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 982, in __iter__\r\n for x in self.ex_iterable:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 862, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 899, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 862, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 899, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 678, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 740, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 862, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 899, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 1114, in __iter__\r\n for key, example in self.ex_iterable:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 429, in __iter__\r\n if not iterators[i].hasnext():\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 106, in hasnext\r\n self._thenext = next(self.it)\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 678, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 740, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 1114, in __iter__\r\n for key, example in self.ex_iterable:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 281, in __iter__\r\n for key, pa_table in self.generate_tables_fn(**self.kwargs):\r\n File \"/home/sanchitgandhi/.cache/huggingface/modules/datasets_modules/datasets/distil-whisper--switchboard-data/9472ee64cca0e1a7e11909c7033c2354511fa62805f81a2e07616980c765abfe/switchboard-data.py\", line 247, in _generate_tables\r\n for record_batch in pf.iter_batches():\r\n File \"pyarrow/_parquet.pyx\", line 1327, in iter_batches\r\n File \"/home/sanchitgandhi/datasets/src/datasets/download/streaming_download_manager.py\", line 342, in read_with_retries\r\n raise ConnectionError(\"Server Disconnected\") from disconnect_err\r\nConnectionError: Server Disconnected\r\n```\r\n\r\n</details>\r\n\r\n<details>\r\n<summary> Stack Trace 2 </summary>\r\n\r\n```\r\n File \"/home/sanchitgandhi/small-12-2-tpu-v3-timestamped-prob-0.2-bs-512/run_distillation.py\", line 2119, in <module>\r\n main()\r\n File \"/home/sanchitgandhi/small-12-2-tpu-v3-timestamped-prob-0.2-bs-512/run_distillation.py\", line 1954, in main\r\n for batch in train_loader:\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/dataloader.py\", line 630, in __next__\r\n data = self._next_data()\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/dataloader.py\", line 1325, in _next_data\r\n return self._process_data(data)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/dataloader.py\", line 1371, in _process_data\r\n data.reraise()\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/_utils.py\", line 694, in reraise\r\n raise exception\r\nrequests.exceptions.ConnectionError: Caught ConnectionError in DataLoader worker process 13.\r\nOriginal Traceback (most recent call last):\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/urllib3/connectionpool.py\", line 791, in urlopen\r\n response = self._make_request(\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/urllib3/connectionpool.py\", line 537, in _make_request\r\n response = conn.getresponse()\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/urllib3/connection.py\", line 461, in getresponse\r\n httplib_response = super().getresponse()\r\n File \"/usr/lib/python3.10/http/client.py\", line 1375, in getresponse\r\n response.begin()\r\n File \"/usr/lib/python3.10/http/client.py\", line 318, in begin\r\n version, status, reason = self._read_status()\r\n File \"/usr/lib/python3.10/http/client.py\", line 287, in _read_status\r\n raise RemoteDisconnected(\"Remote end closed connection without\"\r\nhttp.client.RemoteDisconnected: Remote end closed connection without response\r\nDuring handling of the above exception, another exception occurred:\r\nTraceback (most recent call last):\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/requests/adapters.py\", line 486, in send\r\n resp = conn.urlopen(\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/urllib3/connectionpool.py\", line 845, in urlopen\r\n retries = retries.increment(\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/urllib3/util/retry.py\", line 470, in increment\r\n raise reraise(type(error), error, _stacktrace)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/urllib3/util/util.py\", line 38, in reraise\r\n raise value.with_traceback(tb)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/urllib3/connectionpool.py\", line 791, in urlopen\r\n response = self._make_request(\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/urllib3/connectionpool.py\", line 537, in _make_request\r\n response = conn.getresponse()\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/urllib3/connection.py\", line 461, in getresponse\r\n httplib_response = super().getresponse()\r\n File \"/usr/lib/python3.10/http/client.py\", line 1375, in getresponse\r\n response.begin()\r\n File \"/usr/lib/python3.10/http/client.py\", line 318, in begin\r\n version, status, reason = self._read_status()\r\n File \"/usr/lib/python3.10/http/client.py\", line 287, in _read_status\r\n raise RemoteDisconnected(\"Remote end closed connection without\"\r\nurllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))\r\nDuring handling of the above exception, another exception occurred:\r\nTraceback (most recent call last):\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/_utils/worker.py\", line 308, in _worker_loop\r\n data = fetcher.fetch(index)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py\", line 32, in fetch\r\n data.append(next(self.dataset_iter))\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 1358, in __iter__\r\n yield from self._iter_pytorch()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 1293, in _iter_pytorch\r\n for key, example in ex_iterable:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 982, in __iter__\r\n for x in self.ex_iterable:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 862, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 899, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 862, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 899, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 678, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 740, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 862, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 899, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 1114, in __iter__\r\n for key, example in self.ex_iterable:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 429, in __iter__\r\n if not iterators[i].hasnext():\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 106, in hasnext\r\n self._thenext = next(self.it)\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 678, in __iter__\r\n yield from self._iter()\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 740, in _iter\r\n for key, example in iterator:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 1114, in __iter__\r\n for key, example in self.ex_iterable:\r\n File \"/home/sanchitgandhi/datasets/src/datasets/iterable_dataset.py\", line 281, in __iter__\r\n for key, pa_table in self.generate_tables_fn(**self.kwargs):\r\n File \"/home/sanchitgandhi/datasets/src/datasets/packaged_modules/parquet/parquet.py\", line 87, in _generate_tables\r\n for batch_idx, record_batch in enumerate(\r\n File \"pyarrow/_parquet.pyx\", line 1327, in iter_batches\r\n File \"/home/sanchitgandhi/datasets/src/datasets/download/streaming_download_manager.py\", line 333, in read_with_retries\r\n out = read(*args, **kwargs)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/fsspec/spec.py\", line 1856, in read\r\n out = self.cache._fetch(self.loc, self.loc + length)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/fsspec/caching.py\", line 189, in _fetch\r\n self.cache = self.fetcher(start, end) # new block replaces old\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/huggingface_hub/hf_file_system.py\", line 410, in _fetch_range\r\n r = http_backoff(\"GET\", url, headers=headers)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/huggingface_hub/utils/_http.py\", line 258, in http_backoff\r\n response = session.request(method=method, url=url, **kwargs)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/requests/sessions.py\", line 589, in request\r\n resp = self.send(prep, **send_kwargs)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/requests/sessions.py\", line 703, in send\r\n r = adapter.send(request, **kwargs)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/huggingface_hub/utils/_http.py\", line 63, in send\r\n return super().send(request, *args, **kwargs)\r\n File \"/home/sanchitgandhi/hf/lib/python3.10/site-packages/requests/adapters.py\", line 501, in send\r\n raise ConnectionError(err, request=request)\r\nrequests.exceptions.ConnectionError: (ProtocolError('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')), '(Request ID: 5fce9fc2-e22f-41c2-91af-529f13f1d611)')\r\n```\r\n\r\n</details>\r\n\r\nHaving streaming mode fail when the Hub goes down makes using it problematic for long training runs where large amounts of data is involved. However, this is the precise situation for which streaming mode is so appealing!\r\n\r\nWondering if there were a 'common' set of Hub errors that we could catch in `iterable_datasets` and prevent from crashing the script?\r\n\r\ncc @lhoestq @mariosasko ",
"Errors are already caught and requests are already retried.\r\n\r\nWhat you can do is increase the number of retries before an error is raised.\r\n\r\n```python\r\nimport datasets\r\n\r\ndatasets.config.STREAMING_READ_MAX_RETRIES = 20 # default\r\ndatasets.config.STREAMING_READ_RETRY_INTERVAL = 5 # default\r\n```"
] | ### Feature request
Streaming datasets, as intended, do not load the entire dataset in memory or disk. However, while querying the next data chunk from the remote, sometimes it is possible that the service is down or there might be other issues that may cause the query to fail. In such a scenario, it would be nice to make these queries retryable (perhaps with a backoff strategy).
### Motivation
I was working on a model and the model checkpoints after every 1000 steps. At step 1800 I got a 504 HTTP status code error from Huggingface hub for my pytorch `dataloader`. Given the size of my model and data, it took around 2 hours to reach 1800 steps and now it will take about an hour to recover the lost 800. It would be better to get a retryable querying strategy.
### Your contribution
It would be better if someone having experience in this area takes this up as this would require some testing. | 6,172 |
https://github.com/huggingface/datasets/issues/6169 | Configurations in yaml not working | [
"Unfortunately, I cannot reproduce this behavior on my machine or Colab - the reproducer returns `['main_data', 'additional_data']` as expected.",
"Thank you for looking into this, Mario. Is this on [my repository](https://huggingface.co/datasets/tsor13/test), or on another one that you have reproduced? Would you mind pointing me to it if so?",
"Whoa, in colab I received the correct behavior using my dataset. It must have something to do with my local copy of `datasets` (which again just failed).\r\n\r\nI've tried uninstalling/reinstnalling to no avail",
"hi @tsor13 , I haven't been able to reproduce your issue on `tsor13/test` dataset locally either. reinstalling doesn't help?"
] | ### Dataset configurations cannot be created in YAML/README
Hello! I'm trying to follow the docs here in order to create structure in my dataset as added from here (#5331): https://github.com/huggingface/datasets/blob/8b8e6ee067eb74e7965ca2a6768f15f9398cb7c8/docs/source/repository_structure.mdx#L110-L118
I have the exact example in my config file for [my data repo](https://huggingface.co/datasets/tsor13/test):
```
configs:
- config_name: main_data
data_files: "main_data.csv"
- config_name: additional_data
data_files: "additional_data.csv"
```
Yet, I'm unable to load different configurations:
```
from datasets import get_dataset_config_names
get_dataset_config_names('tsor13/test', use_auth_token=True)
```
returns a single split, `['tsor13--test']`
Does anyone have any insights?
@polinaeterna thank you for adding this feature, it is super useful. Do you happen to have any ideas?
### Steps to reproduce the bug
from datasets import get_dataset_config_names
get_dataset_config_names('tsor13/test')
### Expected behavior
I would expect there to be two splits, `main_data` and `additional_data`. However, only `['tsor13--test']` test is returned.
### Environment info
- `datasets` version: 2.14.4
- Platform: macOS-13.4-arm64-arm-64bit
- Python version: 3.11.4
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 1.5.1 | 6,169 |
https://github.com/huggingface/datasets/issues/6163 | Error type: ArrowInvalid Details: Failed to parse string: '[254,254]' as a scalar of type int32 | [
"Answered on the forum [here](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Ferror-type-arrowinvalid-details-failed-to-parse-string-254-254-as-a-scalar-of-type-int32%2F51323)."
] | ### Describe the bug
I am getting the following error while I am trying to upload the CSV sheet to train a model. My CSV sheet content is exactly same as shown in the example CSV file in the Auto Train page. Attaching screenshot of error for reference. I have also tried converting the index of the answer that are integer into string by placing inverted commas and also without inverted commas.
Can anyone please help me out?
FYI : I am using Chrome browser.
Error type: ArrowInvalid
Details: Failed to parse string: '[254,254]' as a scalar of type int32
![Screenshot 2023-08-19 165827](https://github.com/huggingface/datasets/assets/90616801/95fad96e-7dce-4bb5-9f83-9f1659a32891)
### Steps to reproduce the bug
Kindly let me know how to fix this?
### Expected behavior
Kindly let me know how to fix this?
### Environment info
Kindly let me know how to fix this? | 6,163 |
https://github.com/huggingface/datasets/issues/6162 | load_dataset('json',...) from togethercomputer/RedPajama-Data-1T errors when jsonl rows contains different data fields | [
"Hi ! Feel free to open a discussion at https://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T/discussions to ask the file to be fixed (or directly open a PR with the fixed file)\r\n\r\n`datasets` expects all the examples to have the same fields",
"@lhoestq I think the problem is caused by the fact that hugging face datasets writes a copy of data to the local cache using pyarrow. And the data scheme is inferred from the first few data blocks as can be seen [here](https://github.com/huggingface/datasets/blob/main/src/datasets/arrow_writer.py#L570). Maybe setting `streaming=True` can workaround this problem. Would you agree with my statement? ",
"> @lhoestq I think the problem is caused by the fact that hugging face datasets writes a copy of data to the local cache using pyarrow. And the data scheme is inferred from the first few data blocks as can be seen [here](https://github.com/huggingface/datasets/blob/main/src/datasets/arrow_writer.py#L570).\r\n\r\nCorrect. Therefore any example that doesn't follow the inferred schema will make the code fail.\r\n\r\n> Maybe setting streaming=True can workaround this problem. Would you agree with my statement?\r\n\r\nYou'll meet the same problem but later - when streaming and arriving at the problematic example",
"@lhoestq I just run below test with streaming=True and is not failing at the problematic example\r\n```python\r\nds = load_dataset('json', data_files='/path_to_local_RedPajamaData/filtered_27f05c041a1c401783f90b9415e40e4b.sampled.jsonl', streaming=True)\r\ncount = 0\r\nfor i in ds['train']:\r\n count += 1\r\n print(count)\r\n```\r\n\r\nand completes the 262241 samples successfully. It does error our when streaming is not used "
] | ### Describe the bug
When loading some jsonl from redpajama-data-1T github source [togethercomputer/RedPajama-Data-1T](https://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T) fails due to one row of the file containing an extra field called **symlink_target: string>**.
When deleting that line the loading is successful.
We also tried loading this file with the discrepancy using this function and it is successful
```python
os.environ["RED_PAJAMA_DATA_DIR"] ="/path_to_local_copy_of_RedPajama-Data-1T"
ds = load_dataset('togethercomputer/RedPajama-Data-1T', 'github',cache_dir="/path_to_folder_with_jsonl",streaming=True)['train']
```
### Steps to reproduce the bug
Steps to reproduce the behavior:
1. Load one jsonl from the redpajama-data-1T
```bash
wget https://data.together.xyz/redpajama-data-1T/v1.0.0/github/filtered_27f05c041a1c401783f90b9415e40e4b.sampled.jsonl
```
2.Load dataset will give error:
```python
from datasets import load_dataset
ds = load_dataset('json', data_files='/path_to/filtered_27f05c041a1c401783f90b9415e40e4b.sampled.jsonl')
```
_TypeError: Couldn't cast array of type
Struct
<content_hash: string,
timestamp: string,
source: string,
line_count: int64,
max_line_length: int64,
avg_line_length: double,
alnum_prop: double,
repo_name: string,
id: string,
size: string,
binary: bool,
copies: string,
ref: string,
path: string,
mode: string,
license: string,
language: list<item: struct<name: string, bytes: string>>, **symlink_target: string>**
to
{'content_hash': Value(dtype='string', id=None),
'timestamp': Value(dtype='string', id=None),
'source': Value(dtype='string', id=None),
'line_count': Value(dtype='int64', id=None),
'max_line_length': Value(dtype='int64', id=None),
'avg_line_length': Value(dtype='float64', id=None),
'alnum_prop': Value(dtype='float64', id=None),
'repo_name': Value(dtype='string', id=None),
'id': Value(dtype='string', id=None),
'size': Value(dtype='string', id=None),
'binary': Value(dtype='bool', id=None),
'copies': Value(dtype='string', id=None),
'ref': Value(dtype='string', id=None),
'path': Value(dtype='string', id=None),
'mode': Value(dtype='string', id=None),
'license': Value(dtype='string', id=None),
'language': [{'name': Value(dtype='string', id=None), 'bytes': Value(dtype='string', id=None)}]}_
3. To remove the line causing the problem that includes the **symlink_target: string>** do:
```bash
sed -i '112252d' filtered_27f05c041a1c401783f90b9415e40e4b.sampled.jsonl
```
4. Rerun the loading function now is succesful:
```python
from datasets import load_dataset
ds = load_dataset('json', data_files='/path_to/filtered_27f05c041a1c401783f90b9415e40e4b.sampled.jsonl')
```
### Expected behavior
Have a clean dataset without discrepancies on the jsonl fields or have the load_dataset('json',...) method not error out.
### Environment info
- `datasets` version: 2.14.1
- Platform: Linux-4.18.0-425.13.1.el8_7.x86_64-x86_64-with-glibc2.28
- Python version: 3.9.17
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3 | 6,162 |
https://github.com/huggingface/datasets/issues/6159 | Add `BoundingBox` feature | [] | ... to make working with object detection datasets easier. Currently, `Sequence(int_or_float, length=4)` can be used to represent this feature optimally (in the storage backend), so I only see this feature being useful if we make it work with the viewer. Also, bounding boxes usually come in 4 different formats (explained [here](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/)), so we need to decide which one to support (or maybe all of them).
cc @NielsRogge @severo | 6,159 |
https://github.com/huggingface/datasets/issues/6157 | DatasetInfo.__init__() got an unexpected keyword argument '_column_requires_decoding' | [
"Thanks for reporting, but we can only fix this issue if you can provide a reproducer that consistently reproduces it.",
"@mariosasko Ok. What exactly does it mean to provide a reproducer",
"To provide a code that reproduces the issue :)",
"@mariosasko I complete the above code, is it enough?",
"@mariosasko That's all the code, I'm using locally stored data",
"Does this error occur even if you change the cache directory (the `cache_dir` parameter in `load_dataset`)?",
"@mariosasko I didn't add any parameters for catch. Nor did any cache configuration change.",
"@mariosasko And I changed the data file, but executing load_dataset is always the previous result. I had to change something in images.py to use the new results. Using 'cleanup_cache_files' is invalid! Help me.",
"@mariosasko I added a comprehensive error message. Check that _column_requires_decoding is being passed where it shouldn't be. DatasetInfo.__init__() Whether this parameter is required",
"I can see the issue now... \r\n\r\nYou can fix it by returning a `DatasetInfo` object in the `_info` method as follows:\r\n```python\r\n def _info(self):\r\n if self.config.name == \"similar_pairs\":\r\n features = datasets.Features(\r\n {\r\n \"image1\": datasets.features.Image(),\r\n \"prompt1\": datasets.Value(\"string\"),\r\n \"image2\": datasets.features.Image(),\r\n \"prompt2\": datasets.Value(\"string\"),\r\n \"similarity\": datasets.Value(\"float32\"),\r\n }\r\n )\r\n elif self.config.name == \"image_prompt_pairs\":\r\n features = datasets.Features(\r\n {\"image\": datasets.features.Image(), \"prompt\": datasets.Value(\"string\")}\r\n )\r\n return datasets.DatasetInfo(features=features)\r\n```",
"@mariosasko Oh, that's the problem. Thank you very much. Returned the wrong object and it actually works? I've been training with it for a long time",
"@mariosasko The original code can still see progress. emmm, I can't see how many examples is generated so far, so I don't know if we should wait",
"The original issue has been addressed, so I'm closing it. \r\n\r\nPlease open a new issue if you encounter more errors."
] | ### Describe the bug
When I was in load_dataset, it said "DatasetInfo.__init__() got an unexpected keyword argument '_column_requires_decoding'". The second time I ran it, there was no error and the dataset object worked
```python
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[3], line 1
----> 1 dataset = load_dataset(
2 "/home/aihao/workspace/DeepLearningContent/datasets/manga",
3 data_dir="/home/aihao/workspace/DeepLearningContent/datasets/manga",
4 split="train",
5 )
File [~/miniconda3/envs/torch/lib/python3.11/site-packages/datasets/load.py:2146](https://vscode-remote+ssh-002dremote-002bhome.vscode-resource.vscode-cdn.net/home/aihao/workspace/DeepLearningContent/datasets/~/miniconda3/envs/torch/lib/python3.11/site-packages/datasets/load.py:2146), in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, verification_mode, ignore_verifications, keep_in_memory, save_infos, revision, token, use_auth_token, task, streaming, num_proc, storage_options, **config_kwargs)
2142 # Build dataset for splits
2143 keep_in_memory = (
2144 keep_in_memory if keep_in_memory is not None else is_small_dataset(builder_instance.info.dataset_size)
2145 )
-> 2146 ds = builder_instance.as_dataset(split=split, verification_mode=verification_mode, in_memory=keep_in_memory)
2147 # Rename and cast features to match task schema
2148 if task is not None:
2149 # To avoid issuing the same warning twice
File [~/miniconda3/envs/torch/lib/python3.11/site-packages/datasets/builder.py:1190](https://vscode-remote+ssh-002dremote-002bhome.vscode-resource.vscode-cdn.net/home/aihao/workspace/DeepLearningContent/datasets/~/miniconda3/envs/torch/lib/python3.11/site-packages/datasets/builder.py:1190), in DatasetBuilder.as_dataset(self, split, run_post_process, verification_mode, ignore_verifications, in_memory)
1187 verification_mode = VerificationMode(verification_mode or VerificationMode.BASIC_CHECKS)
1189 # Create a dataset for each of the given splits
-> 1190 datasets = map_nested(
1191 partial(
1192 self._build_single_dataset,
...
File [~/miniconda3/envs/torch/lib/python3.11/site-packages/datasets/info.py:379](https://vscode-remote+ssh-002dremote-002bhome.vscode-resource.vscode-cdn.net/home/aihao/workspace/DeepLearningContent/datasets/~/miniconda3/envs/torch/lib/python3.11/site-packages/datasets/info.py:379), in DatasetInfo.copy(self)
378 def copy(self) -> "DatasetInfo":
--> 379 return self.__class__(**{k: copy.deepcopy(v) for k, v in self.__dict__.items()})
TypeError: DatasetInfo.__init__() got an unexpected keyword argument '_column_requires_decoding'
```
### Steps to reproduce the bug
/home/aihao/workspace/DeepLearningContent/datasets/images/images.py
```python
from logging import config
import datasets
import os
from PIL import Image
import csv
import json
class ImagesConfig(datasets.BuilderConfig):
def __init__(self, **kwargs):
super(ImagesConfig, self).__init__(**kwargs)
class Images(datasets.GeneratorBasedBuilder):
def _split_generators(self, dl_manager: datasets.DownloadManager):
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"split": datasets.Split.TRAIN},
)
]
BUILDER_CONFIGS = [
ImagesConfig(
name="similar_pairs",
description="simliar pair dataset,item is a pair of similar images",
),
ImagesConfig(
name="image_prompt_pairs",
description="image prompt pairs",
),
]
def _info(self):
if self.config.name == "similar_pairs":
return datasets.Features(
{
"image1": datasets.features.Image(),
"image2": datasets.features.Image(),
"similarity": datasets.Value("float32"),
}
)
elif self.config.name == "image_prompt_pairs":
return datasets.Features(
{"image": datasets.features.Image(), "prompt": datasets.Value("string")}
)
def _generate_examples(self, split):
data_path = os.path.join(self.config.data_dir, "data")
if self.config.name == "similar_pairs":
prompts = {}
with open(os.path.join(data_path ,"prompts.json"), "r") as f:
prompts = json.load(f)
with open(os.path.join(data_path, "similar_pairs.csv"), "r") as f:
reader = csv.reader(f)
for row in reader:
image1_path, image2_path, similarity = row
yield image1_path + ":" + image2_path + ":", {
"image1": Image.open(image1_path),
"prompt1": prompts[image1_path],
"image2": Image.open(image2_path),
"prompt2": prompts[image2_path],
"similarity": float(similarity),
}
```
Code that indicates an error:
```python
from datasets import load_dataset
import json
import csv
import ast
import torch
data_dir = "/home/aihao/workspace/DeepLearningContent/datasets/images"
dataset = load_dataset(data_dir, data_dir=data_dir, name="similar_pairs")
```
### Expected behavior
The first execution gives an error, but it works fine
### Environment info
- `datasets` version: 2.14.3
- Platform: Linux-6.2.0-26-generic-x86_64-with-glibc2.35
- Python version: 3.11.4
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3 | 6,157 |
https://github.com/huggingface/datasets/issues/6156 | Why not use self._epoch as seed to shuffle in distributed training with IterableDataset | [
"@lhoestq ",
"`_effective_generator` returns a RNG that takes into account `self._epoch` and the current dataset's base shuffling RNG (which can be set by specifying `seed=` in `.shuffle() for example`).\r\n\r\nTo fix your error you can pass `seed=` to `.shuffle()`. And the shuffling will depend on both this seed and `self._epoch`",
"Thanks for the reply"
] | ### Describe the bug
Currently, distributed training with `IterableDataset` needs to pass fixed seed to shuffle to keep each node use the same seed to avoid overlapping.
https://github.com/huggingface/datasets/blob/a7f8d9019e7cb104eac4106bdc6ec0292f0dc61a/src/datasets/iterable_dataset.py#L1174-L1177
My question is why not directly use `self._epoch` which is set by `set_epoch` as seed? It's almost the same across nodes.
https://github.com/huggingface/datasets/blob/a7f8d9019e7cb104eac4106bdc6ec0292f0dc61a/src/datasets/iterable_dataset.py#L1790-L1801
If not using `self._epoch` as shuffling seed, what does this method do to prepare an epoch seeded generator?
https://github.com/huggingface/datasets/blob/a7f8d9019e7cb104eac4106bdc6ec0292f0dc61a/src/datasets/iterable_dataset.py#L1206
### Steps to reproduce the bug
As mentioned above.
### Expected behavior
As mentioned above.
### Environment info
Not related | 6,156 |
https://github.com/huggingface/datasets/issues/6152 | FolderBase Dataset automatically resolves under current directory when data_dir is not specified | [
"@lhoestq ",
"Makes sense, I guess this can be fixed in the load_dataset_builder method.\r\nIt concerns every packaged builder I think (see values in `_PACKAGED_DATASETS_MODULES`)",
"I think the behavior is related to these lines, which short circuited the error handling.\r\nhttps://github.com/huggingface/datasets/blob/664a1cb72ea1e6ef7c47e671e2686ca4a35e8d63/src/datasets/load.py#L946-L952\r\n\r\nSo should data_dir be checked here or still delegating to actual `DatasetModule`? In that case, how to properly set `data_files` here.",
"This is location in PackagedDatasetModuleFactory.get_module seems the be the right place to check if at least data_dir or data_files are passed",
"@mariosasko can you please assign this issue to me,I want to work on this",
"#self-assign",
"@mariosasko is this issue still open? i would love to kickstart my journey to open source with this issue!\r\nRegards\r\nzutarich",
"@zutarich It is unless @debrupf2946 is working on it.",
"#self-assign",
"I am working and will open a pull request soon @Etelis \r\n",
"@mariosasko can i take this up? ",
"#self-assign",
"Yes, feel free to work on this :)",
"i think its working as expected . Heres the log i get for the same line -\r\n\r\n![image](https://github.com/huggingface/datasets/assets/63234112/8a857ec5-8dd0-4b01-b3a7-7c93444b9558)\r\n"
] | ### Describe the bug
FolderBase Dataset automatically resolves under current directory when data_dir is not specified.
For example:
```
load_dataset("audiofolder")
```
takes long time to resolve and collect data_files from current directory. But I think it should reach out to this line for error handling https://github.com/huggingface/datasets/blob/cb8c5de5145c7e7eee65391cb7f4d92f0d565d62/src/datasets/packaged_modules/folder_based_builder/folder_based_builder.py#L58-L59
### Steps to reproduce the bug
```
load_dataset("audiofolder")
```
### Expected behavior
Error report
### Environment info
- `datasets` version: 2.14.4
- Platform: Linux-5.15.0-78-generic-x86_64-with-glibc2.17
- Python version: 3.8.15
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 1.5.3 | 6,152 |
https://github.com/huggingface/datasets/issues/6151 | Faster sorting for single key items | [
"`Dataset.sort` essentially does the same thing except it uses `pyarrow.compute.sort_indices` which doesn't involve copying the data into python objects (saving memory)\r\n\r\n```python\r\nsort_keys = [(col, \"ascending\") for col in column_names]\r\nindices = pc.sort_indices(self.data, sort_keys=sort_keys)\r\nreturn self.select(indices)\r\n```",
"Ok interesting, I'll continue debugging to see what is going wrong on my end."
] | ### Feature request
A faster way to sort a dataset which contains a large number of rows.
### Motivation
The current sorting implementations took significantly longer than expected when I was running on a dataset trying to sort by timestamps.
**Code snippet:**
```python
ds = datasets.load_dataset( "json", **{"data_files": {"train": "path-to-jsonlines"}, "split": "train"}, num_proc=os.cpu_count(), keep_in_memory=True)
sorted_ds = ds.sort("pubDate", keep_in_memory=True)
```
However, once I switched to a different method which
1. unpacked to a list of tuples
2. sorted tuples by key
3. run `.select` with the sorted list of indices
It was significantly faster (orders of magnitude, especially with M's of rows)
### Your contribution
I'd be happy to implement a crude single key sorting algorithm so that other users can benefit from this trick. Broadly, this would take a `Dataset` and perform;
```python
# ds is a Dataset object
# key_name is the sorting key
class Dataset:
...
def _sort(key_name: str) -> Dataset:
index_keys = [(i,x) for i,x in enumerate(self[key_name])]
sorted_rows = sorted(row_pubdate, key=lambda x: x[1])
sorted_indicies = [x[0] for x in sorted_rows]
return self.select(sorted_indicies)
``` | 6,151 |
https://github.com/huggingface/datasets/issues/6150 | Allow dataset implement .take | [
"```\r\n dataset = IterableDataset(dataset) if type(dataset) != IterableDataset else dataset # to force dataset.take(batch_size) to work in non-streaming mode\r\n ```\r\n",
"hf discuss: /static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-does-one-make-dataset-take-512-work-with-streaming-false-with-hugging-face-data-set%2F50770",
"so: https://stackoverflow.com/questions/76902824/how-does-one-make-dataset-take512-work-with-streaming-false-with-hugging-fac",
"Feel free to work on this. In addition, `IterableDataset` supports `skip`, so we should also add this method to `Dataset`."
] | ### Feature request
I want to do:
```
dataset.take(512)
```
but it only works with streaming = True
### Motivation
uniform interface to data sets. Really surprising the above only works with streaming = True.
### Your contribution
Should be trivial to copy paste the IterableDataset .take to use the local path in the data (when streaming = False) | 6,150 |
https://github.com/huggingface/datasets/issues/6149 | Dataset.from_parquet cannot load subset of columns | [
"Looks like this regression was introduced in `datasets==2.13.0` (`2.12.0` could load a subset of columns)\r\n\r\nThis does not appear to be fixed by https://github.com/huggingface/datasets/pull/6045 (bug still exists on `main`)"
] | ### Describe the bug
When using `Dataset.from_parquet(path_or_paths, columns=[...])` and a subset of columns, loading fails with a variant of the following
```
ValueError: Couldn't cast
a: int64
-- schema metadata --
pandas: '{"index_columns": [], "column_indexes": [], "columns": [{"name":' + 273
to
{'a': Value(dtype='int64', id=None), 'b': Value(dtype='int64', id=None)}
because column names don't match
The above exception was the direct cause of the following exception:
```
Looks to be triggered by https://github.com/huggingface/datasets/blob/c02a44715c036b5261686669727394b1308a3a4b/src/datasets/table.py#L2285-L2286
### Steps to reproduce the bug
```
import pandas as pd
from datasets import Dataset
pd.DataFrame([{"a": 1, "b": 2}]).to_parquet("test.pq")
Dataset.from_parquet("test.pq", columns=["a"])
```
### Expected behavior
A subset of columns should be loaded without error
### Environment info
- `datasets` version: 2.14.4
- Platform: Linux-5.10.0-23-cloud-amd64-x86_64-with-glibc2.2.5
- Python version: 3.8.16
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3 | 6,149 |
https://github.com/huggingface/datasets/issues/6147 | ValueError when running BeamBasedBuilder with GCS path in cache_dir | [
"The cause of the error seems to be that `datasets` adds \"gcs://\" as a schema, while `beam` checks only \"gs://\".\r\n\r\ndatasets: https://github.com/huggingface/datasets/blob/c02a44715c036b5261686669727394b1308a3a4b/src/datasets/builder.py#L822\r\n\r\nbeam: [link](https://github.com/apache/beam/blob/25e1a64641b1c8a3c0a6c75c6e86031b87307f22/sdks/python/apache_beam/io/filesystems.py#L98-L101)\r\n```\r\n systems = [\r\n fs for fs in FileSystem.get_all_subclasses()\r\n if fs.scheme() == path_scheme\r\n ]\r\n```",
"Hi! We've deprecated the Beam API, as we don't have the bandwidth to support it properly..."
] | ### Describe the bug
When running the BeamBasedBuilder with a GCS path specified in the cache_dir, the following ValueError occurs:
```
ValueError: Unable to get filesystem from specified path, please use the correct path or ensure the required dependency is installed, e.g., pip install apache-beam[gcp]. Path specified: gcs://my-bucket/huggingface_datasets/my_beam_dataset/default/0.0.0/my_beam_dataset-train [while running 'train/Save to parquet/Write/WriteImpl/InitializeWrite']
```
Same error occurs after running `pip install apache-beam[gcp]` as instructed.
### Steps to reproduce the bug
Put `my_beam_dataset.py`:
```python
import datasets
class MyBeamDataset(datasets.BeamBasedBuilder):
def _info(self):
features = datasets.Features({"value": datasets.Value("int64")})
return datasets.DatasetInfo(features=features)
def _split_generators(self, dl_manager, pipeline):
return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={})]
def _build_pcollection(self, pipeline):
import apache_beam as beam
return pipeline | beam.Create([{"value": i} for i in range(10)])
```
Run:
```bash
datasets-cli run_beam my_beam_dataset.py --cache_dir=gs://my-bucket/huggingface_datasets/ --beam_pipeline_options="runner=DirectRunner"
```
### Expected behavior
Running the BeamBasedBuilder with a GCS cache path without any errors.
### Environment info
- `datasets` version: 2.14.4
- Platform: macOS-13.4-arm64-arm-64bit
- Python version: 3.9.17
- Huggingface_hub version: 0.16.4
- PyArrow version: 9.0.0
- Pandas version: 2.0.3 | 6,147 |
https://github.com/huggingface/datasets/issues/6146 | DatasetGenerationError when load glue benchmark datasets from `load_dataset` | [
"I've tried clear the .cache file, doesn't work.",
"This issue happens on AWS sagemaker",
"This issue can happen if there is a directory named \"glue\" relative to the Python script with the `load_dataset` call (similar issue to this one: https://github.com/huggingface/datasets/issues/5228). Is this the case?",
"> This issue can happen if there is a directory named \"glue\" relative to the Python script with the `load_dataset` call (similar issue to this one: #5228). Is this the case?\r\n\r\nThats correct!\r\nSorry for my late response."
] | ### Describe the bug
Package version: datasets-2.14.4
When I run the codes:
```
from datasets import load_dataset
dataset = load_dataset("glue", "ax")
```
I got the following errors:
---------------------------------------------------------------------------
SchemaInferenceError Traceback (most recent call last)
File ~/anaconda3/envs/python3/lib/python3.10/site-packages/datasets/builder.py:1949, in ArrowBasedBuilder._prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, job_id)
1948 num_shards = shard_id + 1
-> 1949 num_examples, num_bytes = writer.finalize()
1950 writer.close()
File ~/anaconda3/envs/python3/lib/python3.10/site-packages/datasets/arrow_writer.py:598, in ArrowWriter.finalize(self, close_stream)
597 self.stream.close()
--> 598 raise SchemaInferenceError("Please pass `features` or at least one example when writing data")
599 logger.debug(
600 f"Done writing {self._num_examples} {self.unit} in {self._num_bytes} bytes {self._path if self._path else ''}."
601 )
SchemaInferenceError: Please pass `features` or at least one example when writing data
The above exception was the direct cause of the following exception:
DatasetGenerationError Traceback (most recent call last)
Cell In[5], line 3
1 from datasets import load_dataset
----> 3 dataset = load_dataset("glue", "ax")
File ~/anaconda3/envs/python3/lib/python3.10/site-packages/datasets/load.py:2136, in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, verification_mode, ignore_verifications, keep_in_memory, save_infos, revision, token, use_auth_token, task, streaming, num_proc, storage_options, **config_kwargs)
2133 try_from_hf_gcs = path not in _PACKAGED_DATASETS_MODULES
2135 # Download and prepare data
-> 2136 builder_instance.download_and_prepare(
2137 download_config=download_config,
2138 download_mode=download_mode,
2139 verification_mode=verification_mode,
2140 try_from_hf_gcs=try_from_hf_gcs,
2141 num_proc=num_proc,
2142 storage_options=storage_options,
2143 )
2145 # Build dataset for splits
2146 keep_in_memory = (
2147 keep_in_memory if keep_in_memory is not None else is_small_dataset(builder_instance.info.dataset_size)
2148 )
File ~/anaconda3/envs/python3/lib/python3.10/site-packages/datasets/builder.py:954, 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)
952 if num_proc is not None:
953 prepare_split_kwargs["num_proc"] = num_proc
--> 954 self._download_and_prepare(
955 dl_manager=dl_manager,
956 verification_mode=verification_mode,
957 **prepare_split_kwargs,
958 **download_and_prepare_kwargs,
959 )
960 # Sync info
961 self.info.dataset_size = sum(split.num_bytes for split in self.info.splits.values())
File ~/anaconda3/envs/python3/lib/python3.10/site-packages/datasets/builder.py:1049, in DatasetBuilder._download_and_prepare(self, dl_manager, verification_mode, **prepare_split_kwargs)
1045 split_dict.add(split_generator.split_info)
1047 try:
1048 # Prepare split will record examples associated to the split
-> 1049 self._prepare_split(split_generator, **prepare_split_kwargs)
1050 except OSError as e:
1051 raise OSError(
1052 "Cannot find data file. "
1053 + (self.manual_download_instructions or "")
1054 + "\nOriginal error:\n"
1055 + str(e)
1056 ) from None
File ~/anaconda3/envs/python3/lib/python3.10/site-packages/datasets/builder.py:1813, in ArrowBasedBuilder._prepare_split(self, split_generator, file_format, num_proc, max_shard_size)
1811 job_id = 0
1812 with pbar:
-> 1813 for job_id, done, content in self._prepare_split_single(
1814 gen_kwargs=gen_kwargs, job_id=job_id, **_prepare_split_args
1815 ):
1816 if done:
1817 result = content
File ~/anaconda3/envs/python3/lib/python3.10/site-packages/datasets/builder.py:1958, in ArrowBasedBuilder._prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, job_id)
1956 if isinstance(e, SchemaInferenceError) and e.__context__ is not None:
1957 e = e.__context__
-> 1958 raise DatasetGenerationError("An error occurred while generating the dataset") from e
1960 yield job_id, True, (total_num_examples, total_num_bytes, writer._features, num_shards, shard_lengths)
DatasetGenerationError: An error occurred while generating the dataset
### Steps to reproduce the bug
from datasets import load_dataset
dataset = load_dataset("glue", "ax")
### Expected behavior
When generating the train split:
Generating train split:
0/0 [00:00<?, ? examples/s]
It raise the error:
DatasetGenerationError: An error occurred while generating the dataset
### Environment info
datasets-2.14.4.
Python 3.10 | 6,146 |
https://github.com/huggingface/datasets/issues/6153 | custom load dataset to hub | [
"This is an issue for the [Datasets repo](https://github.com/huggingface/datasets).",
"> This is an issue for the [Datasets repo](https://github.com/huggingface/datasets).\r\n\r\nThanks @sgugger , I guess I will wait for them to address the issue . Looking forward to hearing from them ",
"You can use `.push_to_hub(\"<username>/<repo>\")` to push a `Dataset` to the Hub.",
"> You can use `.push_to_hub(\"<username>/<repo>\")` to push a `Dataset` to the Hub.\r\n\r\nhow about subset? like `.load_dataset(\"<username>/<repo>\", \"<subset>\")`, how can I upload multi-dataset in one repo? thanks a lot ! ",
"> > You can use `.push_to_hub(\"<username>/<repo>\")` to push a `Dataset` to the Hub.\r\n> \r\n> how about subset? like `.load_dataset(\"<username>/<repo>\", \"<subset>\")`, how can I upload multi-dataset in one repo? thanks a lot !\r\n\r\nI solved it by upgrading `Datasets` version to 2.15.0"
] | ### System Info
kaggle notebook
i transformed dataset:
```
dataset = load_dataset("Dahoas/first-instruct-human-assistant-prompt")
```
to
formatted_dataset:
```
Dataset({
features: ['message_tree_id', 'message_tree_text'],
num_rows: 33143
})
```
but would like to know how to upload to hub
### Who can help?
@ArthurZucker @younesbelkada
### Information
- [ ] The official example scripts
- [ ] My own modified scripts
### Tasks
- [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [ ] My own task or dataset (give details below)
### Reproduction
shared above
### Expected behavior
load dataset to hub | 6,153 |
https://github.com/huggingface/datasets/issues/6144 | NIH exporter file not found | [
"related: https://github.com/huggingface/datasets/issues/3504",
"another file not found:\r\n```\r\nTraceback (most recent call last):\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/implementations/http.py\", line 417, in _info\r\n await _file_info(\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/implementations/http.py\", line 837, in _file_info\r\n r.raise_for_status()\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/aiohttp/client_reqrep.py\", line 1005, in raise_for_status\r\n raise ClientResponseError(\r\naiohttp.client_exceptions.ClientResponseError: 404, message='Not Found', url=URL('https://the-eye.eu/public/AI/pile_preliminary_components/pile_uspto.tar')\r\n\r\nThe above exception was the direct cause of the following exception:\r\n\r\nTraceback (most recent call last):\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/runpy.py\", line 196, in _run_module_as_main\r\n return _run_code(code, main_globals, None,\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/runpy.py\", line 86, in _run_code\r\n exec(code, run_globals)\r\n File \"/lfs/ampere1/0/brando9/.vscode-server-insiders/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/__main__.py\", line 39, in <module>\r\n cli.main()\r\n File \"/lfs/ampere1/0/brando9/.vscode-server-insiders/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py\", line 430, in main\r\n run()\r\n File \"/lfs/ampere1/0/brando9/.vscode-server-insiders/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py\", line 284, in run_file\r\n runpy.run_path(target, run_name=\"__main__\")\r\n File \"/lfs/ampere1/0/brando9/.vscode-server-insiders/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py\", line 321, in run_path\r\n return _run_module_code(code, init_globals, run_name,\r\n File \"/lfs/ampere1/0/brando9/.vscode-server-insiders/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py\", line 135, in _run_module_code\r\n _run_code(code, mod_globals, init_globals,\r\n File \"/lfs/ampere1/0/brando9/.vscode-server-insiders/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py\", line 124, in _run_code\r\n exec(code, run_globals)\r\n File \"/lfs/ampere1/0/brando9/beyond-scale-language-data-diversity/src/diversity/div_coeff.py\", line 526, in <module>\r\n experiment_compute_diveristy_coeff_single_dataset_then_combined_datasets_with_domain_weights()\r\n File \"/lfs/ampere1/0/brando9/beyond-scale-language-data-diversity/src/diversity/div_coeff.py\", line 475, in experiment_compute_diveristy_coeff_single_dataset_then_combined_datasets_with_domain_weights\r\n column_names = next(iter(dataset)).keys()\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/datasets/iterable_dataset.py\", line 1353, in __iter__\r\n for key, example in ex_iterable:\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/datasets/iterable_dataset.py\", line 207, in __iter__\r\n yield from self.generate_examples_fn(**self.kwargs)\r\n File \"/lfs/ampere1/0/brando9/.cache/huggingface/modules/datasets_modules/datasets/EleutherAI--pile/ebea56d358e91cf4d37b0fde361d563bed1472fbd8221a21b38fc8bb4ba554fb/pile.py\", line 257, in _generate_examples\r\n for path, file in files[subset]:\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/datasets/download/streaming_download_manager.py\", line 840, in __iter__\r\n yield from self.generator(*self.args, **self.kwargs)\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/datasets/download/streaming_download_manager.py\", line 891, in _iter_from_urlpath\r\n with xopen(urlpath, \"rb\", download_config=download_config) as f:\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/datasets/download/streaming_download_manager.py\", line 496, in xopen\r\n file_obj = fsspec.open(file, mode=mode, *args, **kwargs).open()\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/core.py\", line 134, in open\r\n return self.__enter__()\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/core.py\", line 102, in __enter__\r\n f = self.fs.open(self.path, mode=mode)\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/spec.py\", line 1241, in open\r\n f = self._open(\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/implementations/http.py\", line 356, in _open\r\n size = size or self.info(path, **kwargs)[\"size\"]\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/asyn.py\", line 121, in wrapper\r\n return sync(self.loop, func, *args, **kwargs)\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/asyn.py\", line 106, in sync\r\n raise return_result\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/asyn.py\", line 61, in _runner\r\n result[0] = await coro\r\n File \"/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/implementations/http.py\", line 430, in _info\r\n raise FileNotFoundError(url) from exc\r\nFileNotFoundError: https://the-eye.eu/public/AI/pile_preliminary_components/pile_uspto.tar\r\n```",
"```\r\nFileNotFoundError: https://the-eye.eu/public/AI/pile_preliminary_components/pile_uspto.tar\r\n```\r\nmost relevant line I think.",
"link to tweet: https://twitter.com/BrandoHablando/status/1690081313519489024?s=20 about issue",
"so: https://stackoverflow.com/questions/76891189/how-to-download-data-from-hugging-face-that-is-visible-on-the-data-viewer-but-th",
"this seems to work but it's rather annoying.\r\n\r\nSummary of how to make it work:\r\n1. get urls to parquet files into a list\r\n2. load list to load_dataset via `load_dataset('parquet', data_files=urls)` (note api names to hf are really confusing sometimes)\r\n3. then it should work, print a batch of text.\r\n\r\npresudo code\r\n```python\r\nurls_hacker_news = [\r\n \"https://huggingface.co/datasets/EleutherAI/pile/resolve/refs%2Fconvert%2Fparquet/hacker_news/pile-train-00000-of-00004.parquet\",\r\n \"https://huggingface.co/datasets/EleutherAI/pile/resolve/refs%2Fconvert%2Fparquet/hacker_news/pile-train-00001-of-00004.parquet\",\r\n \"https://huggingface.co/datasets/EleutherAI/pile/resolve/refs%2Fconvert%2Fparquet/hacker_news/pile-train-00002-of-00004.parquet\",\r\n \"https://huggingface.co/datasets/EleutherAI/pile/resolve/refs%2Fconvert%2Fparquet/hacker_news/pile-train-00003-of-00004.parquet\"\r\n]\r\n\r\n...\r\n\r\n\r\n # streaming = False\r\n from diversity.pile_subset_urls import urls_hacker_news\r\n path, name, data_files = 'parquet', 'hacker_news', urls_hacker_news\r\n # not changing\r\n batch_size = 512\r\n today = datetime.datetime.now().strftime('%Y-m%m-d%d-t%Hh_%Mm_%Ss')\r\n run_name = f'{path} div_coeff_{num_batches=} ({today=} ({name=}) {data_mixture_name=} {probabilities=})'\r\n print(f'{run_name=}')\r\n\r\n # - Init wandb\r\n debug: bool = mode == 'dryrun'\r\n run = wandb.init(mode=mode, project=\"beyond-scale\", name=run_name, save_code=True)\r\n wandb.config.update({\"num_batches\": num_batches, \"path\": path, \"name\": name, \"today\": today, 'probabilities': probabilities, 'batch_size': batch_size, 'debug': debug, 'data_mixture_name': data_mixture_name, 'streaming': streaming, 'data_files': data_files})\r\n # run.notify_on_failure() # https://community.wandb.ai/t/how-do-i-set-the-wandb-alert-programatically-for-my-current-run/4891\r\n print(f'{debug=}')\r\n print(f'{wandb.config=}')\r\n\r\n # -- Get probe network\r\n from datasets import load_dataset\r\n import torch\r\n from transformers import GPT2Tokenizer, GPT2LMHeadModel\r\n\r\n tokenizer = GPT2Tokenizer.from_pretrained(\"gpt2\")\r\n if tokenizer.pad_token_id is None:\r\n tokenizer.pad_token = tokenizer.eos_token\r\n probe_network = GPT2LMHeadModel.from_pretrained(\"gpt2\")\r\n device = torch.device(f\"cuda:{0}\" if torch.cuda.is_available() else \"cpu\")\r\n probe_network = probe_network.to(device)\r\n\r\n # -- Get data set\r\n def my_load_dataset(path, name):\r\n print(f'{path=} {name=} {streaming=}')\r\n if path == 'json' or path == 'bin' or path == 'csv':\r\n print(f'{data_files_prefix+name=}')\r\n return load_dataset(path, data_files=data_files_prefix+name, streaming=streaming, split=\"train\").with_format(\"torch\")\r\n elif path == 'parquet':\r\n print(f'{data_files=}')\r\n return load_dataset(path, data_files=data_files, streaming=streaming, split=\"train\").with_format(\"torch\")\r\n else:\r\n return load_dataset(path, name, streaming=streaming, split=\"train\").with_format(\"torch\")\r\n # - get data set for real now\r\n if isinstance(path, str):\r\n dataset = my_load_dataset(path, name)\r\n else:\r\n print('-- interleaving datasets')\r\n datasets = [my_load_dataset(path, name).with_format(\"torch\") for path, name in zip(path, name)]\r\n [print(f'{dataset.description=}') for dataset in datasets]\r\n dataset = interleave_datasets(datasets, probabilities)\r\n print(f'{dataset=}')\r\n batch = dataset.take(batch_size)\r\n print(f'{next(iter(batch))=}')\r\n column_names = next(iter(batch)).keys()\r\n print(f'{column_names=}')\r\n\r\n # - Prepare functions to tokenize batch\r\n def preprocess(examples):\r\n return tokenizer(examples[\"text\"], padding=\"max_length\", max_length=128, truncation=True, return_tensors=\"pt\")\r\n remove_columns = column_names # remove all keys that are not tensors to avoid bugs in collate function in task2vec's pytorch data loader\r\n def map(batch):\r\n return batch.map(preprocess, batched=True, remove_columns=remove_columns)\r\n tokenized_batch = map(batch)\r\n print(f'{next(iter(tokenized_batch))=}')\r\n```\r\n\r\nhttps://stackoverflow.com/questions/76891189/how-to-download-data-from-hugging-face-that-is-visible-on-the-data-viewer-but-th/76902681#76902681\r\n\r\n/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-download-data-from-hugging-face-that-is-visible-on-the-data-viewer-but-the-files-are-not-available%2F50555%2F5%3Fu%3Dsevero"
] | ### Describe the bug
can't use or download the nih exporter pile data.
```
15 experiment_compute_diveristy_coeff_single_dataset_then_combined_datasets_with_domain_weights()
16 File "/lfs/ampere1/0/brando9/beyond-scale-language-data-diversity/src/diversity/div_coeff.py", line 474, in experiment_compute_diveristy_coeff_single_dataset_then_combined_datasets_with_domain_weights
17 column_names = next(iter(dataset)).keys()
18 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/datasets/iterable_dataset.py", line 1353, in __iter__
19 for key, example in ex_iterable:
20 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/datasets/iterable_dataset.py", line 207, in __iter__
21 yield from self.generate_examples_fn(**self.kwargs)
22 File "/lfs/ampere1/0/brando9/.cache/huggingface/modules/datasets_modules/datasets/EleutherAI--pile/ebea56d358e91cf4d37b0fde361d563bed1472fbd8221a21b38fc8bb4ba554fb/pile.py", line 236, in _generate_examples
23 with zstd.open(open(files[subset], "rb"), "rt", encoding="utf-8") as f:
24 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/datasets/streaming.py", line 74, in wrapper
25 return function(*args, download_config=download_config, **kwargs)
26 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/datasets/download/streaming_download_manager.py", line 496, in xopen
27 file_obj = fsspec.open(file, mode=mode, *args, **kwargs).open()
28 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/core.py", line 134, in open
29 return self.__enter__()
30 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/core.py", line 102, in __enter__
31 f = self.fs.open(self.path, mode=mode)
32 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/spec.py", line 1241, in open
33 f = self._open(
34 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/implementations/http.py", line 356, in _open
35 size = size or self.info(path, **kwargs)["size"]
36 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/asyn.py", line 121, in wrapper
37 return sync(self.loop, func, *args, **kwargs)
38 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/asyn.py", line 106, in sync
39 raise return_result
40 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/asyn.py", line 61, in _runner
41 result[0] = await coro
42 File "/lfs/ampere1/0/brando9/miniconda/envs/beyond_scale/lib/python3.10/site-packages/fsspec/implementations/http.py", line 430, in _info
43 raise FileNotFoundError(url) from exc
44 FileNotFoundError: https://the-eye.eu/public/AI/pile_preliminary_components/NIH_ExPORTER_awarded_grant_text.jsonl.zst
```
### Steps to reproduce the bug
run this:
```
from datasets import load_dataset
path, name = 'EleutherAI/pile', 'nih_exporter'
# -- Get data set
dataset = load_dataset(path, name, streaming=True, split="train").with_format("torch")
batch = dataset.take(512)
print(f'{batch=}')
```
### Expected behavior
print the batch
### Environment info
```
(beyond_scale) brando9@ampere1:~/beyond-scale-language-data-diversity$ datasets-cli env
Copy-and-paste the text below in your GitHub issue.
- `datasets` version: 2.14.4
- Platform: Linux-5.4.0-122-generic-x86_64-with-glibc2.31
- Python version: 3.10.11
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3
``` | 6,144 |
https://github.com/huggingface/datasets/issues/6142 | the-stack-dedup fails to generate | [
"@severo ",
"It seems that some parquet files have additional columns.\r\n\r\nI ran a scan and found that two files have the additional `__id__` column:\r\n\r\n1. `hf://datasets/bigcode/the-stack-dedup/data/numpy/data-00000-of-00001.parquet`\r\n2. `hf://datasets/bigcode/the-stack-dedup/data/omgrofl/data-00000-of-00001.parquet`\r\n\r\nWe should open a PR to fix those two files",
"I opened https://huggingface.co/datasets/bigcode/the-stack-dedup/discussions/31",
"The files have been fixed ! I'm closing this one but feel free to re-open if you still have the issue"
] | ### Describe the bug
I'm getting an error generating the-stack-dedup with datasets 2.13.1, and with 2.14.4 nothing happens.
### Steps to reproduce the bug
My code:
```
import os
import datasets as ds
MY_CACHE_DIR = "/home/ubuntu/the-stack-dedup-local"
MY_TOKEN="my-token"
the_stack_ds = ds.load_dataset("bigcode/the-stack-dedup", split="train", download_mode="reuse_cache_if_exists", cache_dir=MY_CACHE_DIR, use_auth_token=MY_TOKEN, num_proc=64)
```
The exception:
```
Generating train split: 233248251 examples [54:31, 57280.00 examples/s]
multiprocess.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/build
er.py", line 1879, in _prepare_split_single
for _, table in generator:
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/packa
ged_modules/parquet/parquet.py", line 82, in _generate_tables
yield f"{file_idx}_{batch_idx}", self._cast_table(pa_table)
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/packa
ged_modules/parquet/parquet.py", line 61, in _cast_table
pa_table = table_cast(pa_table, self.info.features.arrow_schema)
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/table
.py", line 2324, in table_cast
return cast_table_to_schema(table, schema)
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/table
.py", line 2282, in cast_table_to_schema
raise ValueError(f"Couldn't cast\n{table.schema}\nto\n{features}\nb
ecause column names don't match")
ValueError: Couldn't cast
hexsha: string
size: int64
ext: string
lang: string
max_stars_repo_path: string
max_stars_repo_name: string
max_stars_repo_head_hexsha: string
max_stars_repo_licenses: list<item: string>
child 0, item: string
max_stars_count: int64
max_stars_repo_stars_event_min_datetime: string
max_stars_repo_stars_event_max_datetime: string
max_issues_repo_path: string
max_issues_repo_name: string
max_issues_repo_head_hexsha: string
max_issues_repo_licenses: list<item: string>
child 0, item: string
max_issues_count: int64
max_issues_repo_issues_event_min_datetime: string
max_issues_repo_issues_event_max_datetime: string
max_forks_repo_path: string
max_forks_repo_name: string
max_forks_repo_head_hexsha: string
max_forks_repo_licenses: list<item: string>
child 0, item: string
max_forks_count: int64
max_forks_repo_forks_event_min_datetime: string
max_forks_repo_forks_event_max_datetime: string
content: string
avg_line_length: double
max_line_length: int64
alphanum_fraction: double
__id__: int64
-- schema metadata --
huggingface: '{"info": {"features": {"hexsha": {"dtype": "string", "_type' + 1979
to
{'hexsha': Value(dtype='string', id=None), 'size': Value(dtype='int64', id=None), 'ext': Value(dtype='string', id=None), 'lang': Value(dtype='string', id=None), 'max_stars_repo_path': Value(dtype='string', id=None), 'max_stars_repo_name': Value(dtype='string', id=None), 'max_stars_repo_head_hexsha': Value(dtype='string', id=None), 'max_stars_repo_licenses': Sequence(feature=Value(dtype='string', id=None), length=-1, id=None), 'max_stars_count': Value(dtype='int64', id=None), 'max_stars_repo_stars_event_min_datetime': Value(dtype='string', id=None), 'max_stars_repo_stars_event_max_datetime': Value(dtype='string', id=None), 'max_issues_repo_path': Value(dtype='string', id=None), 'max_issues_repo_name': Value(dtype='string', id=None), 'max_issues_repo_head_hexsha': Value(dtype='string', id=None), 'max_issues_repo_licenses': Sequence(feature=Value(dtype='string', id=None), length=-1, id=None), 'max_issues_count': Value(dtype='int64', id=None), 'max_issues_repo_issues_event_min_datetime': Value(dtype='string', id=None), 'max_issues_repo_issues_event_max_datetime': Value(dtype='string', id=None), 'max_forks_repo_path': Value(dtype='string', id=None), 'max_forks_repo_name': Value(dtype='string', id=None), 'max_forks_repo_head_hexsha': Value(dtype='string', id=None), 'max_forks_repo_licenses': Sequence(feature=Value(dtype='string', id=None), length=-1, id=None), 'max_forks_count': Value(dtype='int64', id=None), 'max_forks_repo_forks_event_min_datetime': Value(dtype='string', id=None), 'max_forks_repo_forks_event_max_datetime': Value(dtype='string', id=None), 'content': Value(dtype='string', id=None), 'avg_line_length': Value(dtype='float64', id=None), 'max_line_length': Value(dtype='int64', id=None), 'alphanum_fraction': Value(dtype='float64', id=None)}
because column names don't match
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.10/site-packages/multiprocess/p
ool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/utils
/py_utils.py", line 1328, in _write_generator_to_queue
for i, result in enumerate(func(**kwargs)):
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/build
er.py", line 1912, in _prepare_split_single
raise DatasetGenerationError("An error occurred while generating th
e dataset") from e
datasets.builder.DatasetGenerationError: An error occurred while genera
ting the dataset
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ubuntu/download_the_stack.py", line 7, in <module>
the_stack_ds = ds.load_dataset("bigcode/the-stack-dedup", split="tr
ain", download_mode="reuse_cache_if_exists", cache_dir=MY_CACHE_DIR, us
e_auth_token=MY_TOKEN, num_proc=64)
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/load.
py", line 1809, in load_dataset
builder_instance.download_and_prepare(
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/build
er.py", line 909, in download_and_prepare
self._download_and_prepare(
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/build
er.py", line 1004, in _download_and_prepare
self._prepare_split(split_generator, **prepare_split_kwargs)
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/build
er.py", line 1796, in _prepare_split
for job_id, done, content in iflatmap_unordered(
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/utils
/py_utils.py", line 1354, in iflatmap_unordered
[async_result.get(timeout=0.05) for async_result in async_results]
File "/home/ubuntu/.local/lib/python3.10/site-packages/datasets/utils
/py_utils.py", line 1354, in <listcomp>
[async_result.get(timeout=0.05) for async_result in async_results]
File "/home/ubuntu/.local/lib/python3.10/site-packages/multiprocess/p
ool.py", line 774, in get
raise self._value
datasets.builder.DatasetGenerationError: An error occurred while generating the dataset
```
### Expected behavior
The dataset downloads properly. @lhoestq @loub
### Environment info
Datasets 2.13.1, large VM with 2TB RAM, Ubuntu 20.04 | 6,142 |
https://github.com/huggingface/datasets/issues/6141 | TypeError: ClientSession._request() got an unexpected keyword argument 'https' | [
"Hi! I cannot reproduce this error on my machine or in Colab. Which version of `fsspec` do you have installed?"
] | ### Describe the bug
Hello, when I ran the [code snippet](https://huggingface.co/docs/datasets/v2.14.4/en/loading#json) on the document, I encountered the following problem:
```
Python 3.10.9 (main, Mar 1 2023, 18:23:06) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datasets import load_dataset
>>> base_url = "https://rajpurkar.github.io/SQuAD-explorer/dataset/"
>>> dataset = load_dataset("json", data_files={"train": base_url + "train-v1.1.json", "validation": base_url + "dev-v1.1.json"}, field="data")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/datasets/load.py", line 2112, in load_dataset
builder_instance = load_dataset_builder(
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/datasets/load.py", line 1798, in load_dataset_builder
dataset_module = dataset_module_factory(
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/datasets/load.py", line 1413, in dataset_module_factory
).get_module()
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/datasets/load.py", line 949, in get_module
data_files = DataFilesDict.from_patterns(
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/datasets/data_files.py", line 672, in from_patterns
DataFilesList.from_patterns(
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/datasets/data_files.py", line 578, in from_patterns
resolve_pattern(
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/datasets/data_files.py", line 340, in resolve_pattern
for filepath, info in fs.glob(pattern, detail=True).items()
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/fsspec/asyn.py", line 113, in wrapper
return sync(self.loop, func, *args, **kwargs)
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/fsspec/asyn.py", line 98, in sync
raise return_result
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/fsspec/asyn.py", line 53, in _runner
result[0] = await coro
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/fsspec/implementations/http.py", line 449, in _glob
elif await self._exists(path):
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/fsspec/implementations/http.py", line 306, in _exists
r = await session.get(self.encode_url(path), **kw)
File "/home/liushuai/anaconda3/lib/python3.10/site-packages/aiohttp/client.py", line 922, in get
self._request(hdrs.METH_GET, url, allow_redirects=allow_redirects, **kwargs)
TypeError: ClientSession._request() got an unexpected keyword argument 'https'
```
### Steps to reproduce the bug
```
from datasets import load_dataset
base_url = "https://rajpurkar.github.io/SQuAD-explorer/dataset/"
dataset = load_dataset("json", data_files={"train": base_url + "train-v1.1.json", "validation": base_url + "dev-v1.1.json"}, field="data")
```
### Expected behavior
able to load normally
### Environment info
- `datasets` version: 2.14.4
- Platform: Linux-5.4.54-2-x86_64-with-glibc2.27
- Python version: 3.10.9
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 1.5.3 | 6,141 |
https://github.com/huggingface/datasets/issues/6140 | Misalignment between file format specified in configs metadata YAML and the inferred builder | [] | There is a misalignment between the format of the `data_files` specified in the configs metadata YAML (CSV):
```yaml
configs:
- config_name: default
data_files:
- split: train
path: data.csv
```
and the inferred builder (JSON). Note there are multiple JSON files in the repo, but they do not appear in the configs metadata YAML.
See: https://huggingface.co/datasets/freddyaboulton/chatinterface_with_image_csv/discussions/1
CC: @freddyaboulton @polinaeterna | 6,140 |
https://github.com/huggingface/datasets/issues/6139 | Offline dataset viewer | [
"Hi, thanks for the suggestion. It's not possible at the moment. The viewer is part of the Hub codebase and only works on public datasets. Also, it relies on [Datasets Server](https://github.com/huggingface/datasets-server/), which prepares the data and provides an API to access the rows, size, etc.\r\n\r\nIf you're interested in hosting your data as a private dataset on the Hub, you might want to look at https://github.com/huggingface/datasets-server/issues/39.",
"Hi, we are building an offline dataset viewer: https://github.com/Renumics/spotlight\r\nIt supports many HF datasets, but currently you have to use it via Pandas:\r\ndf=ds.to_pandas()\r\nspotlight.show(df)\r\n\r\nWould love to hear from you if that works for your use case. If not, feel free to open an issue on the repo: https://github.com/Renumics/spotlight/issues",
"@ssuwelack thank you! I will definitely try it out.",
"Related issues:\r\n- https://github.com/huggingface/datasets-server/issues/213\r\n- https://github.com/huggingface/datasets-server/issues/441\r\n- https://github.com/huggingface/datasets/issues/6014",
"Closing for now, as developing and maintaining an offline viewer is not planned.",
"@yuvalkirstain the dataset viewer is now available on private datasets for [PRO users](https://huggingface.co/pricing#pro) and [Enterprise Hub orgs](https://huggingface.co/enterprise). Would it fit your needs?"
] | ### Feature request
The dataset viewer feature is very nice. It enables to the user to easily view the dataset. However, when working for private companies we cannot always upload the dataset to the hub. Is there a way to create dataset viewer offline? I.e. to run a code that will open some kind of html or something that makes it easy to view the dataset.
### Motivation
I want to easily view my dataset even when it is hosted locally.
### Your contribution
N.A. | 6,139 |
https://github.com/huggingface/datasets/issues/6137 | (`from_spark()`) Unable to connect HDFS in pyspark YARN setting | [] | ### Describe the bug
related issue: https://github.com/apache/arrow/issues/37057#issue-1841013613
---
Hello. I'm trying to interact with HDFS storage from a driver and workers of pyspark YARN cluster. Precisely I'm using **huggingface's `datasets`** ([link](https://github.com/huggingface/datasets)) library that relies on pyarrow to communicate with HDFS. The `from_spark()` ([link](https://huggingface.co/docs/datasets/use_with_spark#load-from-spark)) is what I'm invoking in my script.
Below is the error I'm encountering. Note that I've masked sensitive paths. My code is sent to worker containers (docker) from driver container then executed. I confirmed that in both driver and worker images I can connect to HDFS using pyarrow since the envs and required jars are properly set, but strangely that becomes impossible when the same image runs as remote worker process.
These are some peculiarities in my environment that might caused this issue.
* **Cluster requires kerberos authentication**
* But I think the error message implies that's not the problem in this case
* **The user that runs the worker process is different from that built the docker image**
* To avoid permission-related issues I made all directories that are accessed from the script accessible to everyone
* **Pyspark-part of my code has no problem interacting with HDFS.**
* Even pyarrow doesn't experience problem when I run the code in interactive session of the same docker images (driver, worker)
* The problem occurs only when it runs as cluster's worker runtime
Hope I could get some help. Thanks.
```bash
2023-08-08 18:51:19,638 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
2023-08-08 18:51:20,280 WARN shortcircuit.DomainSocketFactory: The short-circuit local reads feature cannot be used because libhadoop cannot be loaded.
23/08/08 18:51:22 WARN TaskSetManager: Lost task 0.0 in stage 142.0 (TID 9732) (ac3bax2062.bdp.bdata.ai executor 1): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "<MASKED>/application_1682476586273_25865777/container_e143_1682476586273_25865777_01_000003/pyspark.zip/pyspark/worker.py", line 830, in main
process()
File "<MASKED>/application_1682476586273_25865777/container_e143_1682476586273_25865777_01_000003/pyspark.zip/pyspark/worker.py", line 820, in process
out_iter = func(split_index, iterator)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/spark/python/pyspark/rdd.py", line 5405, in pipeline_func
File "/root/spark/python/pyspark/rdd.py", line 828, in func
File "/opt/conda/lib/python3.11/site-packages/datasets/packaged_modules/spark/spark.py", line 130, in create_cache_and_write_probe
open(probe_file, "a")
File "/opt/conda/lib/python3.11/site-packages/datasets/streaming.py", line 74, in wrapper
return function(*args, download_config=download_config, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/datasets/download/streaming_download_manager.py", line 496, in xopen
file_obj = fsspec.open(file, mode=mode, *args, **kwargs).open()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/core.py", line 439, in open
out = open_files(
^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/core.py", line 282, in open_files
fs, fs_token, paths = get_fs_token_paths(
^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/core.py", line 609, in get_fs_token_paths
fs = filesystem(protocol, **inkwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/registry.py", line 267, in filesystem
return cls(**storage_options)
^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/spec.py", line 79, in __call__
obj = super().__call__(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/implementations/arrow.py", line 278, in __init__
fs = HadoopFileSystem(
^^^^^^^^^^^^^^^^^
File "pyarrow/_hdfs.pyx", line 96, in pyarrow._hdfs.HadoopFileSystem.__init__
File "pyarrow/error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
File "pyarrow/error.pxi", line 115, in pyarrow.lib.check_status
OSError: HDFS connection failed
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:561)
at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:767)
at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:749)
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:514)
at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
at scala.collection.Iterator.foreach(Iterator.scala:943)
at scala.collection.Iterator.foreach$(Iterator.scala:943)
at org.apache.spark.InterruptibleIterator.foreach(InterruptibleIterator.scala:28)
at scala.collection.generic.Growable.$plus$plus$eq(Growable.scala:62)
at scala.collection.generic.Growable.$plus$plus$eq$(Growable.scala:53)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:105)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:49)
at scala.collection.TraversableOnce.to(TraversableOnce.scala:366)
at scala.collection.TraversableOnce.to$(TraversableOnce.scala:364)
at org.apache.spark.InterruptibleIterator.to(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce.toBuffer(TraversableOnce.scala:358)
at scala.collection.TraversableOnce.toBuffer$(TraversableOnce.scala:358)
at org.apache.spark.InterruptibleIterator.toBuffer(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce.toArray(TraversableOnce.scala:345)
at scala.collection.TraversableOnce.toArray$(TraversableOnce.scala:339)
at org.apache.spark.InterruptibleIterator.toArray(InterruptibleIterator.scala:28)
at org.apache.spark.rdd.RDD.$anonfun$collect$2(RDD.scala:1019)
at org.apache.spark.SparkContext.$anonfun$runJob$5(SparkContext.scala:2303)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:92)
at org.apache.spark.TaskContext.runTaskWithListeners(TaskContext.scala:161)
at org.apache.spark.scheduler.Task.run(Task.scala:139)
at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:554)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1529)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:557)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
23/08/08 18:51:24 WARN TaskSetManager: Lost task 0.1 in stage 142.0 (TID 9733) (ac3iax2079.bdp.bdata.ai executor 2): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "<MASKED>/application_1682476586273_25865777/container_e143_1682476586273_25865777_01_000005/pyspark.zip/pyspark/worker.py", line 830, in main
process()
File "<MASKED>/application_1682476586273_25865777/container_e143_1682476586273_25865777_01_000005/pyspark.zip/pyspark/worker.py", line 820, in process
out_iter = func(split_index, iterator)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/spark/python/pyspark/rdd.py", line 5405, in pipeline_func
File "/root/spark/python/pyspark/rdd.py", line 828, in func
File "/opt/conda/lib/python3.11/site-packages/datasets/packaged_modules/spark/spark.py", line 130, in create_cache_and_write_probe
open(probe_file, "a")
File "/opt/conda/lib/python3.11/site-packages/datasets/streaming.py", line 74, in wrapper
return function(*args, download_config=download_config, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/datasets/download/streaming_download_manager.py", line 496, in xopen
file_obj = fsspec.open(file, mode=mode, *args, **kwargs).open()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/core.py", line 439, in open
out = open_files(
^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/core.py", line 282, in open_files
fs, fs_token, paths = get_fs_token_paths(
^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/core.py", line 609, in get_fs_token_paths
fs = filesystem(protocol, **inkwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/registry.py", line 267, in filesystem
return cls(**storage_options)
^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/spec.py", line 79, in __call__
obj = super().__call__(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/implementations/arrow.py", line 278, in __init__
fs = HadoopFileSystem(
^^^^^^^^^^^^^^^^^
File "pyarrow/_hdfs.pyx", line 96, in pyarrow._hdfs.HadoopFileSystem.__init__
File "pyarrow/error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
File "pyarrow/error.pxi", line 115, in pyarrow.lib.check_status
OSError: HDFS connection failed
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:561)
at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:767)
at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:749)
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:514)
at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
at scala.collection.Iterator.foreach(Iterator.scala:943)
at scala.collection.Iterator.foreach$(Iterator.scala:943)
at org.apache.spark.InterruptibleIterator.foreach(InterruptibleIterator.scala:28)
at scala.collection.generic.Growable.$plus$plus$eq(Growable.scala:62)
at scala.collection.generic.Growable.$plus$plus$eq$(Growable.scala:53)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:105)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:49)
at scala.collection.TraversableOnce.to(TraversableOnce.scala:366)
at scala.collection.TraversableOnce.to$(TraversableOnce.scala:364)
at org.apache.spark.InterruptibleIterator.to(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce.toBuffer(TraversableOnce.scala:358)
at scala.collection.TraversableOnce.toBuffer$(TraversableOnce.scala:358)
at org.apache.spark.InterruptibleIterator.toBuffer(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce.toArray(TraversableOnce.scala:345)
at scala.collection.TraversableOnce.toArray$(TraversableOnce.scala:339)
at org.apache.spark.InterruptibleIterator.toArray(InterruptibleIterator.scala:28)
at org.apache.spark.rdd.RDD.$anonfun$collect$2(RDD.scala:1019)
at org.apache.spark.SparkContext.$anonfun$runJob$5(SparkContext.scala:2303)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:92)
at org.apache.spark.TaskContext.runTaskWithListeners(TaskContext.scala:161)
at org.apache.spark.scheduler.Task.run(Task.scala:139)
at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:554)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1529)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:557)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
23/08/08 18:51:38 WARN TaskSetManager: Lost task 0.2 in stage 142.0 (TID 9734) (<MASKED> executor 4): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "<MASKED>/application_1682476586273_25865777/container_e143_1682476586273_25865777_01_000008/pyspark.zip/pyspark/worker.py", line 830, in main
process()
File "<MASKED>/application_1682476586273_25865777/container_e143_1682476586273_25865777_01_000008/pyspark.zip/pyspark/worker.py", line 820, in process
out_iter = func(split_index, iterator)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/spark/python/pyspark/rdd.py", line 5405, in pipeline_func
File "/root/spark/python/pyspark/rdd.py", line 828, in func
File "/opt/conda/lib/python3.11/site-packages/datasets/packaged_modules/spark/spark.py", line 130, in create_cache_and_write_probe
open(probe_file, "a")
File "/opt/conda/lib/python3.11/site-packages/datasets/streaming.py", line 74, in wrapper
return function(*args, download_config=download_config, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/datasets/download/streaming_download_manager.py", line 496, in xopen
file_obj = fsspec.open(file, mode=mode, *args, **kwargs).open()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/core.py", line 439, in open
out = open_files(
^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/core.py", line 282, in open_files
fs, fs_token, paths = get_fs_token_paths(
^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/core.py", line 609, in get_fs_token_paths
fs = filesystem(protocol, **inkwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/registry.py", line 267, in filesystem
return cls(**storage_options)
^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/spec.py", line 79, in __call__
obj = super().__call__(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/conda/lib/python3.11/site-packages/fsspec/implementations/arrow.py", line 278, in __init__
fs = HadoopFileSystem(
^^^^^^^^^^^^^^^^^
File "pyarrow/_hdfs.pyx", line 96, in pyarrow._hdfs.HadoopFileSystem.__init__
File "pyarrow/error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
File "pyarrow/error.pxi", line 115, in pyarrow.lib.check_status
OSError: HDFS connection failed
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:561)
at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:767)
at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:749)
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:514)
at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
at scala.collection.Iterator.foreach(Iterator.scala:943)
at scala.collection.Iterator.foreach$(Iterator.scala:943)
at org.apache.spark.InterruptibleIterator.foreach(InterruptibleIterator.scala:28)
at scala.collection.generic.Growable.$plus$plus$eq(Growable.scala:62)
at scala.collection.generic.Growable.$plus$plus$eq$(Growable.scala:53)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:105)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:49)
at scala.collection.TraversableOnce.to(TraversableOnce.scala:366)
at scala.collection.TraversableOnce.to$(TraversableOnce.scala:364)
at org.apache.spark.InterruptibleIterator.to(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce.toBuffer(TraversableOnce.scala:358)
at scala.collection.TraversableOnce.toBuffer$(TraversableOnce.scala:358)
at org.apache.spark.InterruptibleIterator.toBuffer(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce.toArray(TraversableOnce.scala:345)
at scala.collection.TraversableOnce.toArray$(TraversableOnce.scala:339)
at org.apache.spark.InterruptibleIterator.toArray(InterruptibleIterator.scala:28)
at org.apache.spark.rdd.RDD.$anonfun$collect$2(RDD.scala:1019)
at org.apache.spark.SparkContext.$anonfun$runJob$5(SparkContext.scala:2303)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:92)
at org.apache.spark.TaskContext.runTaskWithListeners(TaskContext.scala:161)
at org.apache.spark.scheduler.Task.run(Task.scala:139)
at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:554)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1529)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:557)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
```
### Steps to reproduce the bug
Use `from_spark()` function in pyspark YARN setting. I set `cache_dir` to HDFS path.
### Expected behavior
Work as described in document
### Environment info
- `datasets` version: 2.14.4
- Platform: Linux-4.18.0-425.19.2.el8_7.x86_64-x86_64-with-glibc2.17
- Python version: 3.11.4
- Huggingface_hub version: 0.16.4
- PyArrow version: 10.0.1
- Pandas version: 1.5.3 | 6,137 |
https://github.com/huggingface/datasets/issues/6136 | CI check_code_quality error: E721 Do not compare types, use `isinstance()` | [] | After latest release of `ruff` (https://pypi.org/project/ruff/0.0.284/), we get the following CI error:
```
src/datasets/utils/py_utils.py:689:12: E721 Do not compare types, use `isinstance()`
``` | 6,136 |
https://github.com/huggingface/datasets/issues/6134 | `datasets` cannot be installed alongside `apache-beam` | [
"I noticed that this is actually covered by issue #5613, which for some reason I didn't see when I searched the issues in this repo the first time."
] | ### Describe the bug
If one installs `apache-beam` alongside `datasets` (which is required for the [wikipedia](https://huggingface.co/datasets/wikipedia#dataset-summary) dataset) in certain environments (such as a Google Colab notebook), they appear to install successfully, however, actually trying to do something such as importing the `load_dataset` method from `datasets` results in a crashing error.
I think the problem is that `apache-beam` version 2.49.0 requires `dill>=0.3.1.1,<0.3.2`, but the latest version of `multiprocess` (0.70.15) (on which `datasets` depends) requires `dill>=0.3.7,`, so this is causing the dependency resolver to use an older version of `multiprocess` which leads to the `datasets` crashing since it doesn't actually appear to be compatible with older versions.
### Steps to reproduce the bug
See this [Google Colab notebook](https://colab.research.google.com/drive/1PTeGlshamFcJZix_GiS3vMXX_YzAhGv0?usp=sharing) to easily reproduce the bug.
In some environments, I have been able to reproduce the bug by running the following in Bash:
```bash
$ pip install datasets apache-beam
```
then the following in a Python shell:
```python
from datasets import load_dataset
```
Here is my stacktrace from running on Google Colab:
<details>
<summary>stacktrace</summary>
```
[/usr/local/lib/python3.10/dist-packages/datasets/__init__.py](https://localhost:8080/#) in <module>
20 __version__ = "2.14.4"
21
---> 22 from .arrow_dataset import Dataset
23 from .arrow_reader import ReadInstruction
24 from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder
[/usr/local/lib/python3.10/dist-packages/datasets/arrow_dataset.py](https://localhost:8080/#) in <module>
64
65 from . import config
---> 66 from .arrow_reader import ArrowReader
67 from .arrow_writer import ArrowWriter, OptimizedTypedSequence
68 from .data_files import sanitize_patterns
[/usr/local/lib/python3.10/dist-packages/datasets/arrow_reader.py](https://localhost:8080/#) in <module>
28 import pyarrow.parquet as pq
29
---> 30 from .download.download_config import DownloadConfig
31 from .naming import _split_re, filenames_for_dataset_split
32 from .table import InMemoryTable, MemoryMappedTable, Table, concat_tables
[/usr/local/lib/python3.10/dist-packages/datasets/download/__init__.py](https://localhost:8080/#) in <module>
7
8 from .download_config import DownloadConfig
----> 9 from .download_manager import DownloadManager, DownloadMode
10 from .streaming_download_manager import StreamingDownloadManager
[/usr/local/lib/python3.10/dist-packages/datasets/download/download_manager.py](https://localhost:8080/#) in <module>
33 from ..utils.info_utils import get_size_checksum_dict
34 from ..utils.logging import get_logger, is_progress_bar_enabled, tqdm
---> 35 from ..utils.py_utils import NestedDataStructure, map_nested, size_str
36 from .download_config import DownloadConfig
37
[/usr/local/lib/python3.10/dist-packages/datasets/utils/py_utils.py](https://localhost:8080/#) in <module>
38 import dill
39 import multiprocess
---> 40 import multiprocess.pool
41 import numpy as np
42 from packaging import version
[/usr/local/lib/python3.10/dist-packages/multiprocess/pool.py](https://localhost:8080/#) in <module>
607 #
608
--> 609 class ThreadPool(Pool):
610
611 from .dummy import Process
[/usr/local/lib/python3.10/dist-packages/multiprocess/pool.py](https://localhost:8080/#) in ThreadPool()
609 class ThreadPool(Pool):
610
--> 611 from .dummy import Process
612
613 def __init__(self, processes=None, initializer=None, initargs=()):
[/usr/local/lib/python3.10/dist-packages/multiprocess/dummy/__init__.py](https://localhost:8080/#) in <module>
85 #
86
---> 87 class Condition(threading._Condition):
88 # XXX
89 if sys.version_info < (3, 0):
AttributeError: module 'threading' has no attribute '_Condition'
```
</details>
I've also found that attempting to install these `datasets` and `apache-beam` in certain environments (e.g. via pip inside a conda env) simply causes pip to hang indefinitely.
### Expected behavior
I would expect to be able to import methods from `datasets` without crashing. I have tested that this is possible as long as I do not attempt to install `apache-beam`.
### Environment info
Google Colab | 6,134 |
https://github.com/huggingface/datasets/issues/6133 | Dataset is slower after calling `to_iterable_dataset` | [
"@lhoestq ",
"It's roughly the same code between the two so we can expected roughly the same speed, could you share a benchmark ?"
] | ### Describe the bug
Can anyone explain why looping over a dataset becomes slower after calling `to_iterable_dataset` to convert to `IterableDataset`
### Steps to reproduce the bug
Any dataset after converting to `IterableDataset`
### Expected behavior
Maybe it should be faster on big dataset? I only test on small dataset
### Environment info
- `datasets` version: 2.14.4
- Platform: Linux-5.15.0-76-generic-x86_64-with-glibc2.17
- Python version: 3.8.15
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 1.5.3 | 6,133 |
https://github.com/huggingface/datasets/issues/6132 | to_iterable_dataset is missing in document | [
"Fixed with PR"
] | ### Describe the bug
to_iterable_dataset is missing in document
### Steps to reproduce the bug
to_iterable_dataset is missing in document
### Expected behavior
document enhancement
### Environment info
unrelated | 6,132 |
https://github.com/huggingface/datasets/issues/6130 | default config name doesn't work when config kwargs are specified. | [
"@lhoestq ",
"What should be the behavior in this case ? Should it override the default config with the added parameter ?",
"I know why it should be treated as a new config if overriding parameters are passed. But in some case, I just pass in some common fields like `data_dir`.\r\n\r\nFor example, I want to extend the FolderBasedBuilder as a multi-config version, the `data_dir` or `data_files` are always passed by user and should not be considered as overriding the default config. In current state, I cannot leverage the feature of default config since passing `data_dir` will disable the default config.",
"Thinking more about it I think the current behavior is the right one.\r\n\r\nProvided parameters should be passed to instantiate a new BuilderConfig.\r\n\r\nWhat's the error you're getting ?",
"For example, this works to use default config with name '_all_':\r\n```python\r\ndatasets.load_dataset(\"indonesian-nlp/librivox-indonesia\", split=\"train\")\r\n```\r\nwhile this failed to use default config\r\n```python\r\ndatasets.load_dataset(\"indonesian-nlp/librivox-indonesia\", split=\"train\", data_dir='.')\r\n```\r\nAfter manually specifying it, it works again.\r\n```python\r\ndatasets.load_dataset(\"indonesian-nlp/librivox-indonesia\", \"_all_\", split=\"train\", data_dir='.')\r\n```",
"@lhoestq ",
"It should work if you explicitly ask for the config you want to override\r\n\r\n```python\r\nload_dataset('/dataset/with/multiple/config', 'name_of_the_default_config', some_field_in_config='some')\r\n```\r\n\r\nAlternatively you can have a BuilderConfig class that when instantiated returns a config with the right default values. In this case this code would instantiate this config with the default values except for the parameter to override:\r\n\r\n```python\r\nload_dataset('/dataset/with/multiple/config', some_field_in_config='some')\r\n```",
"@lhoestq Yes. But it doesn't work for me.\r\n\r\nHere's my dataset for example.\r\n```\r\nlass MyDatasetConfig(datasets.BuilderConfig):\r\n def __init__(self, name: str, version: str, **kwargs):\r\n self.option1 = kwargs.pop(\"option1\", False)\r\n self.option2 = kwargs.pop(\"option2\", 5)\r\n\r\n super().__init__(\r\n name=name,\r\n version=datasets.Version(version),\r\n **kwargs)\r\n\r\n\r\nclass MyDataset(datasets.GeneratorBasedBuilder):\r\n DEFAULT_CONFIG_NAME = \"v1\"\r\n\r\n BUILDER_CONFIGS = [\r\n UnifiedTtsDatasetConfig(\r\n name=\"v1\",\r\n version=\"1.0.0\",\r\n description=\"Initial version of the dataset\"\r\n ),\r\n ]\r\n\r\n def _info(self) -> DatasetInfo:\r\n _ = self.option1\r\n ....\r\n```\r\n\r\nHere it's okay to use `load_dataset('my_dataset.py')` for loading the default config `v1`.\r\n\r\nBut if I want to override the default values in config with `load_dataset('my_dataset.py', option2=3)`, it failed to find my default config `v1.\r\n\r\nUnless I use `load_dataset('my_dataset.py', 'v1', option2=3)`\r\n\r\nSo according to your advice, how can I modify my dataset to be able to override default config without manually specifying it.",
"What's the error ? It should try to instantiate `MyDatasetConfig` with `option2=3`",
"@lhoestq The error is\r\n```\r\ndef _info(self) -> DatasetInfo:\r\n _ = self.option1 <-\r\n ....\r\nAttributeError: 'BuilderConfig' object has no attribute 'option1'\r\n```\r\nwhich seems to find another unknown config.\r\n\r\nYou can try this line `datasets.load_dataset(\"indonesian-nlp/librivox-indonesia\", split=\"train\", data_dir='.')`, it's a multi-config dataset on HF hub and the error is the same.\r\n\r\nMy insights:\r\nhttps://github.com/huggingface/datasets/blob/12cfc1196e62847e2e8239fbd727a02cbc86ddec/src/datasets/builder.py#L518\r\nif `config_kwargs` is provided here, the if branch is skipped.",
"I see, you just have to set this class attribute to your builder class :)\r\n\r\n```python\r\nBUILDER_CONFIG_CLASS = MyDatasetConfig\r\n```",
"So what does this attribute do? In most cases it's not used and the [documents for multi-config dataset](https://huggingface.co/docs/datasets/main/en/image_dataset#multiple-configurations) never mentioned that.",
"It tells which builder config class to instantiate if additional config parameters are passed to load_dataset",
"@lhoestq maybe we can enhance the document to say something about the common attributes of `DatasetBuilder`",
"Ah indeed it's missing in the docs, thanks for reporting. I'm opening a PR"
] | ### Describe the bug
https://github.com/huggingface/datasets/blob/12cfc1196e62847e2e8239fbd727a02cbc86ddec/src/datasets/builder.py#L518-L522
If `config_name` is `None`, `DEFAULT_CONFIG_NAME` should be select. But once users pass `config_kwargs` to their customized `BuilderConfig`, the logic is ignored, and dataset cannot select the default config from multiple configs.
### Steps to reproduce the bug
```python
import datasets
datasets.load_dataset('/dataset/with/multiple/config'') # Ok
datasets.load_dataset('/dataset/with/multiple/config', some_field_in_config='some') # Err
```
### Expected behavior
Default config behavior should be consistent.
### Environment info
- `datasets` version: 2.14.3
- Platform: Linux-5.15.0-76-generic-x86_64-with-glibc2.17
- Python version: 3.8.15
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 1.5.3 | 6,130 |
https://github.com/huggingface/datasets/issues/6128 | IndexError: Invalid key: 88 is out of bounds for size 0 | [
"Hi @TomasAndersonFang,\r\n\r\nHave you tried instead to use `torch_compile` in `transformers.TrainingArguments`? https://huggingface.co/docs/transformers/v4.31.0/en/main_classes/trainer#transformers.TrainingArguments.torch_compile",
"> \r\n\r\nI tried this and got the following error:\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py\", line 324, in _compile\r\n out_code = transform_code_object(code, transform)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/bytecode_transformation.py\", line 445, in transform_code_object\r\n transformations(instructions, code_options)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py\", line 311, in transform\r\n tracer.run()\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py\", line 1726, in run\r\n super().run()\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py\", line 576, in run\r\n and self.step()\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py\", line 540, in step\r\n getattr(self, inst.opname)(inst)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py\", line 1030, in LOAD_ATTR\r\n result = BuiltinVariable(getattr).call_function(\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/variables/builtin.py\", line 566, in call_function\r\n result = handler(tx, *args, **kwargs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/variables/builtin.py\", line 931, in call_getattr\r\n return obj.var_getattr(tx, name).add_options(options)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/variables/nn_module.py\", line 124, in var_getattr\r\n subobj = inspect.getattr_static(base, name)\r\n File \"/apps/Arch/software/Python/3.10.8-GCCcore-12.2.0/lib/python3.10/inspect.py\", line 1777, in getattr_static\r\n raise AttributeError(attr)\r\nAttributeError: config\r\n\r\nfrom user code:\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/peft/peft_model.py\", line 909, in forward\r\n if self.base_model.config.model_type == \"mpt\":\r\n\r\nSet torch._dynamo.config.verbose=True for more information\r\n\r\n\r\nYou can suppress this exception and fall back to eager by setting:\r\n torch._dynamo.config.suppress_errors = True\r\n\r\n\r\nThe above exception was the direct cause of the following exception:\r\n\r\nTraceback (most recent call last):\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/llm-copt/fine-tune/falcon/falcon_sft.py\", line 228, in <module>\r\n main()\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/llm-copt/fine-tune/falcon/falcon_sft.py\", line 221, in main\r\n trainer.train()\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/transformers/trainer.py\", line 1539, in train\r\n return inner_training_loop(\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/transformers/trainer.py\", line 1809, in _inner_training_loop\r\n tr_loss_step = self.training_step(model, inputs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/transformers/trainer.py\", line 2654, in training_step\r\n loss = self.compute_loss(model, inputs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/transformers/trainer.py\", line 2679, in compute_loss\r\n outputs = model(**inputs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1501, in _call_impl\r\n return forward_call(*args, **kwargs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py\", line 82, in forward\r\n return self.dynamo_ctx(self._orig_mod.forward)(*args, **kwargs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py\", line 209, in _fn\r\n return fn(*args, **kwargs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/accelerate/utils/operations.py\", line 581, in forward\r\n return model_forward(*args, **kwargs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/accelerate/utils/operations.py\", line 569, in __call__\r\n return convert_to_fp32(self.model_forward(*args, **kwargs))\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/amp/autocast_mode.py\", line 14, in decorate_autocast\r\n return func(*args, **kwargs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py\", line 337, in catch_errors\r\n return callback(frame, cache_size, hooks)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py\", line 404, in _convert_frame\r\n result = inner_convert(frame, cache_size, hooks)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py\", line 104, in _fn\r\n return fn(*args, **kwargs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py\", line 262, in _convert_frame_assert\r\n return _compile(\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/utils.py\", line 163, in time_wrapper\r\n r = func(*args, **kwargs)\r\n File \"/cephyr/NOBACKUP/groups/snic2021-23-24/LLM4-CodeOpt/env/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py\", line 394, in _compile\r\n raise InternalTorchDynamoError() from e\r\ntorch._dynamo.exc.InternalTorchDynamoError\r\n```",
"Hi @TomasAndersonFang,\r\n\r\nI guess in this case it may be an issue with `transformers` (or `PyTorch`). I would recommend you open an issue on their repo.",
"@albertvillanova Thanks for your recommendation. I'll do it",
"@TomasAndersonFang were you able to find a solution to this issue? I would highly appreciate any help. \r\n\r\nThanks!"
] | ### Describe the bug
This bug generates when I use torch.compile(model) in my code, which seems to raise an error in datasets lib.
### Steps to reproduce the bug
I use the following code to fine-tune Falcon on my private dataset.
```python
import transformers
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
AutoConfig,
DataCollatorForSeq2Seq,
Trainer,
Seq2SeqTrainer,
HfArgumentParser,
Seq2SeqTrainingArguments,
BitsAndBytesConfig,
)
from peft import (
LoraConfig,
get_peft_model,
get_peft_model_state_dict,
prepare_model_for_int8_training,
set_peft_model_state_dict,
)
import torch
import os
import evaluate
import functools
from datasets import load_dataset
import bitsandbytes as bnb
import logging
import json
import copy
from typing import Dict, Optional, Sequence
from dataclasses import dataclass, field
# Lora settings
LORA_R = 8
LORA_ALPHA = 16
LORA_DROPOUT= 0.05
LORA_TARGET_MODULES = ["query_key_value"]
@dataclass
class ModelArguments:
model_name_or_path: Optional[str] = field(default="Salesforce/codegen2-7B")
@dataclass
class DataArguments:
data_path: str = field(default=None, metadata={"help": "Path to the training data."})
train_file: str = field(default=None, metadata={"help": "Path to the evaluation data."})
eval_file: str = field(default=None, metadata={"help": "Path to the evaluation data."})
cache_path: str = field(default=None, metadata={"help": "Path to the cache directory."})
num_proc: int = field(default=4, metadata={"help": "Number of processes to use for data preprocessing."})
@dataclass
class TrainingArguments(transformers.TrainingArguments):
# cache_dir: Optional[str] = field(default=None)
optim: str = field(default="adamw_torch")
model_max_length: int = field(
default=512,
metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
)
is_lora: bool = field(default=True, metadata={"help": "Whether to use LORA."})
def tokenize(text, tokenizer, max_seq_len=512, add_eos_token=True):
result = tokenizer(
text,
truncation=True,
max_length=max_seq_len,
padding=False,
return_tensors=None,
)
if (
result["input_ids"][-1] != tokenizer.eos_token_id
and len(result["input_ids"]) < max_seq_len
and add_eos_token
):
result["input_ids"].append(tokenizer.eos_token_id)
result["attention_mask"].append(1)
if add_eos_token and len(result["input_ids"]) >= max_seq_len:
result["input_ids"][max_seq_len - 1] = tokenizer.eos_token_id
result["attention_mask"][max_seq_len - 1] = 1
result["labels"] = result["input_ids"].copy()
return result
def main():
parser = HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
config = AutoConfig.from_pretrained(
model_args.model_name_or_path,
cache_dir=data_args.cache_path,
trust_remote_code=True,
)
if training_args.is_lora:
model = AutoModelForCausalLM.from_pretrained(
model_args.model_name_or_path,
cache_dir=data_args.cache_path,
torch_dtype=torch.float16,
trust_remote_code=True,
load_in_8bit=True,
quantization_config=BitsAndBytesConfig(
load_in_8bit=True,
llm_int8_threshold=6.0
),
)
model = prepare_model_for_int8_training(model)
config = LoraConfig(
r=LORA_R,
lora_alpha=LORA_ALPHA,
target_modules=LORA_TARGET_MODULES,
lora_dropout=LORA_DROPOUT,
bias="none",
task_type="CAUSAL_LM",
)
model = get_peft_model(model, config)
else:
model = AutoModelForCausalLM.from_pretrained(
model_args.model_name_or_path,
torch_dtype=torch.float16,
cache_dir=data_args.cache_path,
trust_remote_code=True,
)
model.config.use_cache = False
def print_trainable_parameters(model):
"""
Prints the number of trainable parameters in the model.
"""
trainable_params = 0
all_param = 0
for _, param in model.named_parameters():
all_param += param.numel()
if param.requires_grad:
trainable_params += param.numel()
print(
f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}"
)
print_trainable_parameters(model)
tokenizer = AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
cache_dir=data_args.cache_path,
model_max_length=training_args.model_max_length,
padding_side="left",
use_fast=True,
trust_remote_code=True,
)
tokenizer.pad_token = tokenizer.eos_token
# Load dataset
def generate_and_tokenize_prompt(sample):
input_text = sample["input"]
target_text = sample["output"] + tokenizer.eos_token
full_text = input_text + target_text
tokenized_full_text = tokenize(full_text, tokenizer, max_seq_len=512)
tokenized_input_text = tokenize(input_text, tokenizer, max_seq_len=512)
input_len = len(tokenized_input_text["input_ids"]) - 1 # -1 for eos token
tokenized_full_text["labels"] = [-100] * input_len + tokenized_full_text["labels"][input_len:]
return tokenized_full_text
data_files = {}
if data_args.train_file is not None:
data_files["train"] = data_args.train_file
if data_args.eval_file is not None:
data_files["eval"] = data_args.eval_file
dataset = load_dataset(data_args.data_path, data_files=data_files)
train_dataset = dataset["train"]
eval_dataset = dataset["eval"]
train_dataset = train_dataset.map(generate_and_tokenize_prompt, num_proc=data_args.num_proc)
eval_dataset = eval_dataset.map(generate_and_tokenize_prompt, num_proc=data_args.num_proc)
data_collator = DataCollatorForSeq2Seq(tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True)
# Evaluation metrics
def compute_metrics(eval_preds, tokenizer):
metric = evaluate.load('exact_match')
preds, labels = eval_preds
# In case the model returns more than the prediction logits
if isinstance(preds, tuple):
preds = preds[0]
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True, clean_up_tokenization_spaces=False)
# Replace -100s in the labels as we can't decode them
labels[labels == -100] = tokenizer.pad_token_id
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True, clean_up_tokenization_spaces=False)
# Some simple post-processing
decoded_preds = [pred.strip() for pred in decoded_preds]
decoded_labels = [label.strip() for label in decoded_labels]
result = metric.compute(predictions=decoded_preds, references=decoded_labels)
return {'exact_match': result['exact_match']}
compute_metrics_fn = functools.partial(compute_metrics, tokenizer=tokenizer)
model = torch.compile(model)
# Training
trainer = Trainer(
model=model,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
args=training_args,
data_collator=data_collator,
compute_metrics=compute_metrics_fn,
)
trainer.train()
trainer.save_state()
trainer.save_model(output_dir=training_args.output_dir)
tokenizer.save_pretrained(save_directory=training_args.output_dir)
if __name__ == "__main__":
main()
```
When I didn't use `torch.cpmpile(model)`, my code worked well. But when I added this line to my code, It produced the following error:
```
Traceback (most recent call last):
File "falcon_sft.py", line 230, in <module>
main()
File "falcon_sft.py", line 223, in main
trainer.train()
File "python3.10/site-packages/transformers/trainer.py", line 1539, in train
return inner_training_loop(
File "python3.10/site-packages/transformers/trainer.py", line 1787, in _inner_training_loop
for step, inputs in enumerate(epoch_iterator):
File "python3.10/site-packages/accelerate/data_loader.py", line 384, in __iter__
current_batch = next(dataloader_iter)
File "python3.10/site-packages/torch/utils/data/dataloader.py", line 633, in __next__
data = self._next_data()
File "python3.10/site-packages/torch/utils/data/dataloader.py", line 677, in _next_data
data = self._dataset_fetcher.fetch(index) # may raise StopIteration
File "python3.10/site-packages/torch/utils/data/_utils/fetch.py", line 49, in fetch
data = self.dataset.__getitems__(possibly_batched_index)
File "python3.10/site-packages/datasets/arrow_dataset.py", line 2807, in __getitems__
batch = self.__getitem__(keys)
File "python3.10/site-packages/datasets/arrow_dataset.py", line 2803, in __getitem__
return self._getitem(key)
File "python3.10/site-packages/datasets/arrow_dataset.py", line 2787, in _getitem
pa_subtable = query_table(self._data, key, indices=self._indices if self._indices is not None else None)
File "python3.10/site-packages/datasets/formatting/formatting.py", line 583, in query_table
_check_valid_index_key(key, size)
File "python3.10/site-packages/datasets/formatting/formatting.py", line 536, in _check_valid_index_key
_check_valid_index_key(int(max(key)), size=size)
File "python3.10/site-packages/datasets/formatting/formatting.py", line 526, in _check_valid_index_key
raise IndexError(f"Invalid key: {key} is out of bounds for size {size}")
IndexError: Invalid key: 88 is out of bounds for size 0
```
So I'm confused about why this error was generated, and how to fix it. Is this error produced by datasets or `torch.compile`?
### Expected behavior
I want to use `torch.compile` in my code.
### Environment info
- `datasets` version: 2.14.3
- Platform: Linux-4.18.0-425.19.2.el8_7.x86_64-x86_64-with-glibc2.28
- Python version: 3.10.8
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3 | 6,128 |
https://github.com/huggingface/datasets/issues/6126 | Private datasets do not load when passing token | [
"Our CI did not catch this issue because with current implementation, stored token in `HfFolder` (which always exists) is used by default.",
"I can confirm this and have the same problem (and just went almost crazy because I couldn't figure out the source of this problem because on another computer everything worked well even with `DownloadMode.FORCE_REDOWNLOAD`).",
"We are planning to do a patch release today, after the merge of the fix:\r\n- #6127\r\n\r\nIn the meantime, the problem can be circumvented by passing `download_config` instead:\r\n```python\r\nfrom datasets import DownloadConfig, load_dataset\r\n\r\nload_dataset(\"<DATASET-NAME>\", split=\"train\", download_config=DownloadConfig(token=\"<TOKEN>\"))\r\n``` ",
"> We are planning to do a patch release today, after the merge of the fix:\r\n> \r\n> * [Fix authentication issues #6127](https://github.com/huggingface/datasets/pull/6127)\r\n> \r\n> \r\n> In the meantime, the problem can be circumvented by passing `download_config` instead:\r\n> \r\n> ```python\r\n> from datasets import DownloadConfig, load_dataset\r\n> \r\n> load_dataset(\"<DATASET-NAME>\", split=\"train\", download_config=DownloadConfig(token=\"<TOKEN>\"))\r\n> ```\r\n\r\nThis did not work for me (there was some other error with the split being an unexpected size 0). Downgrading to 2.13 fixed it...."
] | ### Describe the bug
Since the release of `datasets` 2.14, private/gated datasets do not load when passing `token`: they raise `EmptyDatasetError`.
This is a non-planned backward incompatible breaking change.
Note that private datasets do load if instead `download_config` is passed:
```python
from datasets import DownloadConfig, load_dataset
ds = load_dataset("albertvillanova/tmp-private", split="train", download_config=DownloadConfig(token="<MY-TOKEN>"))
ds
```
gives
```
Dataset({
features: ['text'],
num_rows: 4
})
```
### Steps to reproduce the bug
```python
from datasets import load_dataset
ds = load_dataset("albertvillanova/tmp-private", split="train", token="<MY-TOKEN>")
```
gives
```
---------------------------------------------------------------------------
EmptyDatasetError Traceback (most recent call last)
[<ipython-input-2-25b48732107a>](https://localhost:8080/#) in <cell line: 3>()
1 from datasets import load_dataset
2
----> 3 ds = load_dataset("albertvillanova/tmp-private", split="train", token="<MY-TOKEN>")
5 frames
[/usr/local/lib/python3.10/dist-packages/datasets/load.py](https://localhost:8080/#) in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, verification_mode, ignore_verifications, keep_in_memory, save_infos, revision, token, use_auth_token, task, streaming, num_proc, storage_options, **config_kwargs)
2107
2108 # Create a dataset builder
-> 2109 builder_instance = load_dataset_builder(
2110 path=path,
2111 name=name,
[/usr/local/lib/python3.10/dist-packages/datasets/load.py](https://localhost:8080/#) in load_dataset_builder(path, name, data_dir, data_files, cache_dir, features, download_config, download_mode, revision, token, use_auth_token, storage_options, **config_kwargs)
1793 download_config = download_config.copy() if download_config else DownloadConfig()
1794 download_config.storage_options.update(storage_options)
-> 1795 dataset_module = dataset_module_factory(
1796 path,
1797 revision=revision,
[/usr/local/lib/python3.10/dist-packages/datasets/load.py](https://localhost:8080/#) in dataset_module_factory(path, revision, download_config, download_mode, dynamic_modules_path, data_dir, data_files, **download_kwargs)
1484 raise ConnectionError(f"Couldn't reach the Hugging Face Hub for dataset '{path}': {e1}") from None
1485 if isinstance(e1, EmptyDatasetError):
-> 1486 raise e1 from None
1487 if isinstance(e1, FileNotFoundError):
1488 raise FileNotFoundError(
[/usr/local/lib/python3.10/dist-packages/datasets/load.py](https://localhost:8080/#) in dataset_module_factory(path, revision, download_config, download_mode, dynamic_modules_path, data_dir, data_files, **download_kwargs)
1474 download_config=download_config,
1475 download_mode=download_mode,
-> 1476 ).get_module()
1477 except (
1478 Exception
[/usr/local/lib/python3.10/dist-packages/datasets/load.py](https://localhost:8080/#) in get_module(self)
1030 sanitize_patterns(self.data_files)
1031 if self.data_files is not None
-> 1032 else get_data_patterns(base_path, download_config=self.download_config)
1033 )
1034 data_files = DataFilesDict.from_patterns(
[/usr/local/lib/python3.10/dist-packages/datasets/data_files.py](https://localhost:8080/#) in get_data_patterns(base_path, download_config)
457 return _get_data_files_patterns(resolver)
458 except FileNotFoundError:
--> 459 raise EmptyDatasetError(f"The directory at {base_path} doesn't contain any data files") from None
460
461
EmptyDatasetError: The directory at hf://datasets/albertvillanova/tmp-private@79b9e4fe79670a9a050d6ebc385464891915a71d doesn't contain any data files
```
### Expected behavior
The dataset should load.
### Environment info
- `datasets` version: 2.14.3
- Platform: Linux-5.15.109+-x86_64-with-glibc2.35
- Python version: 3.10.12
- Huggingface_hub version: 0.16.4
- PyArrow version: 9.0.0
- Pandas version: 1.5.3 | 6,126 |
https://github.com/huggingface/datasets/issues/6125 | Reinforcement Learning and Robotics are not task categories in HF datasets metadata | [] | ### Describe the bug
In https://huggingface.co/models there are task categories for RL and robotics but none in https://huggingface.co/datasets
Our lab is currently moving our datasets over to hugging face and would like to be able to add those 2 tags
Moreover we see some older datasets that do have that tag, but we can't seem to add it ourselves.
### Steps to reproduce the bug
1. Create a new dataset on Hugging face
2. Try to type reinforcemement-learning or robotics into the tasks categories, it does not allow you to commit
### Expected behavior
Expected to be able to add RL and robotics as task categories as some previous datasets have these tags
### Environment info
N/A | 6,125 |
https://github.com/huggingface/datasets/issues/6124 | Datasets crashing runs due to KeyError | [
"i once had the same error and I could fix that by pushing a fake or a dummy commit on my hugging face dataset repo",
"Hi! We need a reproducer to fix this. Can you provide a link to the dataset (if it's public)?",
"> Hi! We need a reproducer to fix this. Can you provide a link to the dataset (if it's public)?\r\n\r\nHi Mario,\r\n\r\nUnfortunately, the dataset in question is currently private until the model is trained and released.\r\n\r\nThis is not happening with one dataset but numerous hosted private datasets.\r\n\r\nI am only loading the dataset and doing nothing else currently. It seems to happen completely sporadically.\r\n\r\nThank you,\r\n\r\nEnrico",
"Hi,\r\n\r\nI have the same error in the dataset viewer with my dataset\r\nhttps://huggingface.co/datasets/elsaEU/ELSA10M_track1\r\n\r\nHas anyone solved this issue?\r\n\r\nEdit: After a dummy commit the error changed in ConfigNamesError",
"@rs9000 The problem seems to be the (large) number of commits, as explained in https://huggingface.co/docs/hub/repositories-recommendations. This can be fixed by running:\r\n```python\r\nimport huggingface_hub\r\nhuggingface_hub.super_squash_history(repo_id=\"elsaEU/ELSA10M_track1\")\r\n``` \r\n\r\nThe issue stems from `push_to_hub` creating one commit per shard - https://github.com/huggingface/datasets/pull/6269 should fix this issue (will create one commit per 50 uploaded shards by default). The linked PR will be included in the next `datasets` release.\r\n\r\n\r\ncc @lhoestq @severo for visibility",
"Thank you @mariosasko it works.",
"#6269 has been merged, so I'm closing this issue"
] | ### Describe the bug
Hi all,
I have been running into a pretty persistent issue recently when trying to load datasets.
```python
train_dataset = load_dataset(
'llama-2-7b-tokenized',
split = 'train'
)
```
I receive a KeyError which crashes the runs.
```
Traceback (most recent call last):
main()
train_dataset = load_dataset(
^^^^^^^^^^^^^
builder_instance = load_dataset_builder(
^^^^^^^^^^^^^^^^^^^^^
dataset_module = dataset_module_factory(
^^^^^^^^^^^^^^^^^^^^^^^
raise e1 from None
).get_module()
^^^^^^^^^^^^
else get_data_patterns(base_path, download_config=self.download_config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return _get_data_files_patterns(resolver)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
data_files = pattern_resolver(pattern)
^^^^^^^^^^^^^^^^^^^^^^^^^
fs, _, _ = get_fs_token_paths(pattern, storage_options=storage_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
paths = [f for f in sorted(fs.glob(paths)) if not fs.isdir(f)]
^^^^^^^^^^^^^^
allpaths = self.find(root, maxdepth=depth, withdirs=True, detail=True, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
for _, dirs, files in self.walk(path, maxdepth, detail=True, **kwargs):
listing = self.ls(path, detail=True, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"last_modified": parse_datetime(tree_item["lastCommit"]["date"]),
~~~~~~~~~^^^^^^^^^^^^^^
KeyError: 'lastCommit'
```
Any help would be greatly appreciated.
Thank you,
Enrico
### Steps to reproduce the bug
Load the dataset from the Huggingface hub.
```python
train_dataset = load_dataset(
'llama-2-7b-tokenized',
split = 'train'
)
```
### Expected behavior
Loads the dataset.
### Environment info
datasets-2.14.3
CUDA 11.8
Python 3.11 | 6,124 |
https://github.com/huggingface/datasets/issues/6123 | Inaccurate Bounding Boxes in "wildreceipt" Dataset | [
"Hi! Thanks for the investigation, but we are not the authors of these datasets, so please report this on the Hub instead so that the actual authors can fix it."
] | ### Describe the bug
I would like to bring to your attention an issue related to the accuracy of bounding boxes within the "wildreceipt" dataset, which is made available through the Hugging Face API. Specifically, I have identified a discrepancy between the bounding boxes generated by the dataset loading commands, namely `load_dataset("Theivaprakasham/wildreceipt")` and `load_dataset("jinhybr/WildReceipt")`, and the actual labels and corresponding bounding boxes present in the dataset.
To illustrate this divergence, I've provided two examples in the form of screenshots. These screenshots highlight the contrasting outcomes between my personal implementation of the dataloader and the implementation offered by Hugging Face:
**Example 1:**
![image](https://github.com/huggingface/datasets/assets/50714796/7a6604d2-899d-4102-a008-1a28c90698f1)
![image](https://github.com/huggingface/datasets/assets/50714796/eba458c7-d3af-4868-a520-8b683aa96f66)
![image](https://github.com/huggingface/datasets/assets/50714796/9f394891-5f5b-46f7-8e52-071b724aedab)
**Example 2:**
![image](https://github.com/huggingface/datasets/assets/50714796/a2b2a8d3-124e-4990-b64a-5133cf4be2fe)
![image](https://github.com/huggingface/datasets/assets/50714796/6ee25642-35aa-40ad-ac1e-899d33be90df)
![image](https://github.com/huggingface/datasets/assets/50714796/5e42ff91-9fc4-4520-8803-0e225656f96c)
It's important to note that my dataloader implementation is based on the same dataset files as utilized in the Hugging Face implementation. For your reference, you can access the dataset files through this link: [wildreceipt dataset files](https://download.openmmlab.com/mmocr/data/wildreceipt.tar).
This inconsistency in bounding box accuracy warrants investigation and rectification for maintaining the integrity of the "wildreceipt" dataset. Your attention and assistance in addressing this matter would be greatly appreciated.
### Steps to reproduce the bug
```python
import matplotlib.pyplot as plt
from datasets import load_dataset
# Define functions to convert bounding box formats
def convert_format1(box):
x, y, w, h = box
x2, y2 = x + w, y + h
return [x, y, x2, y2]
def convert_format2(box):
x1, y1, x2, y2 = box
return [x1, y1, x2, y2]
def plot_cropped_image(image, box, title):
cropped_image = image.crop(box)
plt.imshow(cropped_image)
plt.title(title)
plt.axis('off')
plt.savefig(title+'.png')
plt.show()
doc_index = 1
word_index = 3
dataset = load_dataset("Theivaprakasham/wildreceipt")['train']
bbox_hugging_face = dataset[doc_index]['bboxes'][word_index]
text_unit_face = dataset[doc_index]['words'][word_index]
common_box_hugface_1 = convert_format1(bbox_hugging_face)
common_box_hugface_2 = convert_format2(bbox_hugging_face)
plot_cropped_image(image_hugging, common_box_hugface_1,
f'Hugging Face Bouding boxes (x,y,w,h format) \n its associated text unit: {text_unit_face}')
plot_cropped_image(image_hugging, common_box_hugface_2,
f'Hugging Face Bouding boxes (x1,y1,x2, y2 format) \n its associated text unit: {text_unit_face}')
```
### Expected behavior
The bounding boxes generated by the "wildreceipt" dataset in HuggingFace implementation loading commands should accurately match the actual labels and bounding boxes of the dataset.
### Environment info
- Python version: 3.8
- Hugging Face datasets version: 2.14.2
- Dataset file taken from this link: https://download.openmmlab.com/mmocr/data/wildreceipt.tar | 6,123 |
https://github.com/huggingface/datasets/issues/6122 | Upload README via `push_to_hub` | [
"You can use `huggingface_hub`'s [Card API](https://huggingface.co/docs/huggingface_hub/package_reference/cards) to programmatically push a dataset card to the Hub."
] | ### Feature request
`push_to_hub` now allows users to upload datasets programmatically. However, based on the latest doc, we still need to open the dataset page to add readme file manually.
However, I do discover snippets to intialize a README for every `push_to_hub`:
```
dataset_card = (
DatasetCard(
"---\n"
+ str(dataset_card_data)
+ "\n---\n"
+ f'# Dataset Card for "{repo_id.split("/")[-1]}"\n\n[More Information needed](https://github.com/huggingface/datasets/blob/main/CONTRIBUTING.md#how-to-contribute-to-the-dataset-cards)'
)
if dataset_card is None
else dataset_card
)
HfApi(endpoint=config.HF_ENDPOINT).upload_file(
path_or_fileobj=str(dataset_card).encode(),
path_in_repo="README.md",
repo_id=repo_id,
token=token,
repo_type="dataset",
revision=branch,
)
```
So, if we can enable `push_to_hub` to upload a readme file by ourselves instead of using the auto generated ones, it can save ton of time, and will definitely alleviate the current "lack-of-dataset-card" situation.
### Motivation
as elabrated above.
### Your contribution
I might be able to make a pr. | 6,122 |
https://github.com/huggingface/datasets/issues/6120 | Lookahead streaming support? | [
"In which format is your dataset? We could expose the `pre_buffer` flag for Parquet to use PyArrow's background thread pool to speed up loading. "
] | ### Feature request
From what I understand, streaming dataset currently pulls the data, and process the data as it is requested.
This can introduce significant latency delays when data is loaded into the training process, needing to wait for each segment.
While the delays might be dataset specific (or even mapping instruction/tokenizer specific)
Is it possible to introduce a `streaming_lookahead` parameter, which is used for predictable workloads (even shuffled dataset with fixed seed). As we can predict in advance what the next few datasamples will be. And fetch them while the current set is being trained.
With enough CPU & bandwidth to keep up with the training process, and a sufficiently large lookahead, this will reduce the various latency involved while waiting for the dataset to be ready between batches.
### Motivation
Faster streaming performance, while training over extra large TB sized datasets
### Your contribution
I currently use HF dataset, with pytorch lightning trainer for RWKV project, and would be able to help test this feature if supported. | 6,120 |
https://github.com/huggingface/datasets/issues/6118 | IterableDataset.from_generator() fails with pickle error when provided a generator or iterator | [
"Hi! `IterableDataset.from_generator` expects a generator function, not the object (to be consistent with `Dataset.from_generator`).\r\n\r\nYou can fix the above snippet as follows:\r\n```python\r\ntrain_dataset = IterableDataset.from_generator(line_generator, fn_kwargs={\"files\": model_training_files})\r\n```",
"to anyone reaching this issue, the argument is `gen_kwargs`:\r\n```py\r\ntrain_dataset = IterableDataset.from_generator(line_generator, gen_kwargs={\"files\": model_training_files})\r\n```"
] | ### Describe the bug
**Description**
Providing a generator in an instantiation of IterableDataset.from_generator() fails with `TypeError: cannot pickle 'generator' object` when the generator argument is supplied with a generator.
**Code example**
```
def line_generator(files: List[Path]):
if isinstance(files, str):
files = [Path(files)]
for file in files:
if isinstance(file, str):
file = Path(file)
yield from open(file,'r').readlines()
...
model_training_files = ['file1.txt', 'file2.txt', 'file3.txt']
train_dataset = IterableDataset.from_generator(generator=line_generator(model_training_files))
```
**Traceback**
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/contextlib.py", line 135, in __exit__
self.gen.throw(type, value, traceback)
File "/Users/d3p692/code/clem_bert/venv/lib/python3.9/site-packages/datasets/utils/py_utils.py", line 691, in _no_cache_fields
yield
File "/Users/d3p692/code/clem_bert/venv/lib/python3.9/site-packages/datasets/utils/py_utils.py", line 701, in dumps
dump(obj, file)
File "/Users/d3p692/code/clem_bert/venv/lib/python3.9/site-packages/datasets/utils/py_utils.py", line 676, in dump
Pickler(file, recurse=True).dump(obj)
File "/Users/d3p692/code/clem_bert/venv/lib/python3.9/site-packages/dill/_dill.py", line 394, in dump
StockPickler.dump(self, obj)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/pickle.py", line 487, in dump
self.save(obj)
File "/Users/d3p692/code/clem_bert/venv/lib/python3.9/site-packages/datasets/utils/py_utils.py", line 666, in save
dill.Pickler.save(self, obj, save_persistent_id=save_persistent_id)
File "/Users/d3p692/code/clem_bert/venv/lib/python3.9/site-packages/dill/_dill.py", line 388, in save
StockPickler.save(self, obj, save_persistent_id)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/pickle.py", line 560, in save
f(self, obj) # Call unbound method with explicit self
File "/Users/d3p692/code/clem_bert/venv/lib/python3.9/site-packages/dill/_dill.py", line 1186, in save_module_dict
StockPickler.save_dict(pickler, obj)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/pickle.py", line 971, in save_dict
self._batch_setitems(obj.items())
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/pickle.py", line 997, in _batch_setitems
save(v)
File "/Users/d3p692/code/clem_bert/venv/lib/python3.9/site-packages/datasets/utils/py_utils.py", line 666, in save
dill.Pickler.save(self, obj, save_persistent_id=save_persistent_id)
File "/Users/d3p692/code/clem_bert/venv/lib/python3.9/site-packages/dill/_dill.py", line 388, in save
StockPickler.save(self, obj, save_persistent_id)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/pickle.py", line 578, in save
rv = reduce(self.proto)
TypeError: cannot pickle 'generator' object
### Steps to reproduce the bug
1. Create a set of text files to iterate over.
2. Create a generator that returns the lines in each file until all files are exhausted.
3. Instantiate the dataset over the generator by instantiating an IterableDataset.from_generator().
4. Wait for the explosion.
### Expected behavior
I would expect that since the function claims to accept a generator that there would be no crash. Instead, I would expect the dataset to return all the lines in the files as queued up in the `line_generator()` function.
### Environment info
datasets.__version__ == '2.13.1'
Python 3.9.6
Platform: Darwin WE35261 22.5.0 Darwin Kernel Version 22.5.0: Thu Jun 8 22:22:22 PDT 2023; root:xnu-8796.121.3~7/RELEASE_X86_64 x86_64
| 6,118 |
https://github.com/huggingface/datasets/issues/6116 | [Docs] The "Process" how-to guide lacks description of `select_columns` function | [
"Great idea, feel free to open a PR! :)"
] | ### Feature request
The [how to process dataset guide](https://huggingface.co/docs/datasets/main/en/process) currently does not mention the [`select_columns`](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.select_columns) function. It would be nice to include it in the guide.
### Motivation
This function is a commonly requested feature (see this [forum thread](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-create-a-new-dataset-from-another-dataset-and-select-specific-columns-and-the-data-along-with-the-column%2F15120) and #5468 #5474). However, it has not been included in the guide since its implementation by PR #5480.
Mentioning it in the guide would help future users discover this added feature.
### Your contribution
I could submit a PR to add a brief description of the function to said guide. | 6,116 |
https://github.com/huggingface/datasets/issues/6114 | Cache not being used when loading commonvoice 8.0.0 | [
"You can avoid this by using the `revision` parameter in `load_dataset` to always force downloading a specific commit (if not specified it defaults to HEAD, hence the redownload).",
"Thanks @mariosasko this works well, looks like I should have read the documentation a bit more carefully. \r\n\r\nIt is still a bit confusing which hash I should provide: passing `revision = c8fd66e85f086e3abb11eeee55b1737a3d1e8487` from https://huggingface.co/datasets/mozilla-foundation/common_voice_8_0/commits/main caused the cached version at `~/.cache/huggingface/datasets/mozilla-foundation___common_voice_8_0/en/8.0.0/b2f8b72f8f30b2e98c41ccf855954d9e35a5fa498c43332df198534ff9797a4a` to be loaded, so I had to know that it was the previous commit unless I've missed something else."
] | ### Describe the bug
I have commonvoice 8.0.0 downloaded in `~/.cache/huggingface/datasets/mozilla-foundation___common_voice_8_0/en/8.0.0/b2f8b72f8f30b2e98c41ccf855954d9e35a5fa498c43332df198534ff9797a4a`. The folder contains all the arrow files etc, and was used as the cached version last time I touched the ec2 instance I'm working on. Now, with the same command that downloaded it initially:
```
dataset = load_dataset("mozilla-foundation/common_voice_8_0", "en", use_auth_token="<mytoken>")
```
it tries to redownload the dataset to `~/.cache/huggingface/datasets/mozilla-foundation___common_voice_8_0/en/8.0.0/05bdc7940b0a336ceeaeef13470c89522c29a8e4494cbeece64fb472a87acb32`
### Steps to reproduce the bug
Steps to reproduce the behavior:
1. ```dataset = load_dataset("mozilla-foundation/common_voice_8_0", "en", use_auth_token="<mytoken>")```
2. dataset is updated by maintainers
3. ```dataset = load_dataset("mozilla-foundation/common_voice_8_0", "en", use_auth_token="<mytoken>")```
### Expected behavior
I expect that it uses the already downloaded data in `~/.cache/huggingface/datasets/mozilla-foundation___common_voice_8_0/en/8.0.0/b2f8b72f8f30b2e98c41ccf855954d9e35a5fa498c43332df198534ff9797a4a`.
Not sure what's happening in 2. but if, say it's an issue with the dataset referenced by "mozilla-foundation/common_voice_8_0" being modified by the maintainers, how would I force datasets to point to the original version I downloaded?
EDIT: It was indeed that the maintainers had updated the dataset (v 8.0.0). However I still cant load the dataset from disk instead of redownloading, with for example:
```
load_dataset(".cache/huggingface/datasets/downloads/extracted/<hash>/cv-corpus-8.0-2022-01-19/en/", "en")
> ...
> File [~/miniconda3/envs/aa_torch2/lib/python3.10/site-packages/datasets/table.py:1938](.../ python3.10/site-packages/datasets/table.py:1938), in cast_array_to_feature(array, feature, allow_number_to_str)
1937 elif not isinstance(feature, (Sequence, dict, list, tuple)):
-> 1938 return array_cast(array, feature(), allow_number_to_str=allow_number_to_str)
...
1794 e = e.__context__
-> 1795 raise DatasetGenerationError("An error occurred while generating the dataset") from e
1797 yield job_id, True, (total_num_examples, total_num_bytes, writer._features, num_shards, shard_lengths)
DatasetGenerationError: An error occurred while generating the dataset
```
### Environment info
datasets==2.7.0
python==3.10.8
OS: AWS Linux | 6,114 |
https://github.com/huggingface/datasets/issues/6113 | load_dataset() fails with streamlit caching inside docker | [
"Hi! This should be fixed in the latest (patch) release (run `pip install -U datasets` to install it). This behavior was due to a bug in our authentication logic."
] | ### Describe the bug
When calling `load_dataset` in a streamlit application running within a docker container, get a failure with the error message:
EmptyDatasetError: The directory at hf://datasets/fetch-rewards/inc-rings-2000@bea27cf60842b3641eae418f38864a2ec4cde684 doesn't contain any data files
Traceback:
File "/opt/conda/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 552, in _run_script
exec(code, module.__dict__)
File "/home/user/app/app.py", line 62, in <module>
dashboard()
File "/home/user/app/app.py", line 47, in dashboard
feat_dict, path_gml = load_data(hf_repo, model_gml_dict[selected_model], hf_token)
File "/opt/conda/lib/python3.10/site-packages/streamlit/runtime/caching/cache_utils.py", line 211, in wrapper
return cached_func(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/streamlit/runtime/caching/cache_utils.py", line 240, in __call__
return self._get_or_create_cached_value(args, kwargs)
File "/opt/conda/lib/python3.10/site-packages/streamlit/runtime/caching/cache_utils.py", line 266, in _get_or_create_cached_value
return self._handle_cache_miss(cache, value_key, func_args, func_kwargs)
File "/opt/conda/lib/python3.10/site-packages/streamlit/runtime/caching/cache_utils.py", line 320, in _handle_cache_miss
computed_value = self._info.func(*func_args, **func_kwargs)
File "/home/user/app/hf_interface.py", line 16, in load_data
hf_dataset = load_dataset(repo_id, use_auth_token=hf_token)
File "/opt/conda/lib/python3.10/site-packages/datasets/load.py", line 2109, in load_dataset
builder_instance = load_dataset_builder(
File "/opt/conda/lib/python3.10/site-packages/datasets/load.py", line 1795, in load_dataset_builder
dataset_module = dataset_module_factory(
File "/opt/conda/lib/python3.10/site-packages/datasets/load.py", line 1486, in dataset_module_factory
raise e1 from None
File "/opt/conda/lib/python3.10/site-packages/datasets/load.py", line 1476, in dataset_module_factory
).get_module()
File "/opt/conda/lib/python3.10/site-packages/datasets/load.py", line 1032, in get_module
else get_data_patterns(base_path, download_config=self.download_config)
File "/opt/conda/lib/python3.10/site-packages/datasets/data_files.py", line 458, in get_data_patterns
raise EmptyDatasetError(f"The directory at {base_path} doesn't contain any data files") from None
### Steps to reproduce the bug
```python
@st.cache_resource
def load_data(repo_id: str, hf_token=None):
"""Load data from HuggingFace Hub
"""
hf_dataset = load_dataset(repo_id, use_auth_token=hf_token)
hf_dataset = hf_dataset.map(lambda x: json.loads(x["ground_truth"]), remove_columns=["ground_truth"])
return hf_dataset
```
### Expected behavior
Expect to load.
Note: works fine with datasets==2.13.1
### Environment info
datasets==2.14.2,
Ubuntu bionic-based Docker container. | 6,113 |
https://github.com/huggingface/datasets/issues/6112 | yaml error using push_to_hub with generated README.md | [
"Thanks for reporting! This is a bug in converting the `ArrayXD` types to YAML. It will be fixed soon."
] | ### Describe the bug
When I construct a dataset with the following features:
```
features = Features(
{
"pixel_values": Array3D(dtype="float64", shape=(3, 224, 224)),
"input_ids": Sequence(feature=Value(dtype="int64")),
"attention_mask": Sequence(Value(dtype="int64")),
"tokens": Sequence(Value(dtype="string")),
"bbox": Array2D(dtype="int64", shape=(512, 4)),
}
)
```
and run `push_to_hub`, the individual `*.parquet` files are pushed, but when trying to upload the auto-generated README, I run into the following error:
```
Traceback (most recent call last):
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/huggingface_hub/utils/_errors.py", line 261, in hf_raise_for_status
response.raise_for_status()
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/requests/models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://huggingface.co/api/datasets/looppayments/multitask_document_classification_dataset/commit/main
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/kevintee/loop-payments/ml/src/ml/data_scripts/build_document_classification_training_data.py", line 297, in <module>
build_dataset()
File "/Users/kevintee/loop-payments/ml/src/ml/data_scripts/build_document_classification_training_data.py", line 290, in build_dataset
push_to_hub(dataset, "multitask_document_classification_dataset")
File "/Users/kevintee/loop-payments/ml/src/ml/data_scripts/build_document_classification_training_data.py", line 135, in push_to_hub
dataset.push_to_hub(f"looppayments/{dataset_name}", private=True)
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/datasets/arrow_dataset.py", line 5577, in push_to_hub
HfApi(endpoint=config.HF_ENDPOINT).upload_file(
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py", line 118, in _inner_fn
return fn(*args, **kwargs)
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/huggingface_hub/hf_api.py", line 828, in _inner
return fn(self, *args, **kwargs)
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/huggingface_hub/hf_api.py", line 3221, in upload_file
commit_info = self.create_commit(
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py", line 118, in _inner_fn
return fn(*args, **kwargs)
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/huggingface_hub/hf_api.py", line 828, in _inner
return fn(self, *args, **kwargs)
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/huggingface_hub/hf_api.py", line 2728, in create_commit
hf_raise_for_status(commit_resp, endpoint_name="commit")
File "/Users/kevintee/.pyenv/versions/dev2/lib/python3.10/site-packages/huggingface_hub/utils/_errors.py", line 299, in hf_raise_for_status
raise BadRequestError(message, response=response) from e
huggingface_hub.utils._errors.BadRequestError: (Request ID: Root=1-64ca9c3d-2d2bbef354e102482a9a168e;bc00371c-8549-4859-9f41-43ff140ad36e)
Bad request for commit endpoint:
Invalid YAML in README.md: unknown tag !<tag:yaml.org,2002:python/tuple> (10:9)
7 | - 3
8 | - 224
9 | - 224
10 | dtype: float64
--------------^
11 | - name: input_ids
12 | sequence: int64
```
My guess is that the auto-generated yaml is unable to be parsed for some reason.
### Steps to reproduce the bug
The description contains most of what's needed to reproduce the issue, but I've added a shortened code snippet:
```
from datasets import Array2D, Array3D, ClassLabel, Dataset, Features, Sequence, Value
from PIL import Image
from transformers import AutoProcessor
features = Features(
{
"pixel_values": Array3D(dtype="float64", shape=(3, 224, 224)),
"input_ids": Sequence(feature=Value(dtype="int64")),
"attention_mask": Sequence(Value(dtype="int64")),
"tokens": Sequence(Value(dtype="string")),
"bbox": Array2D(dtype="int64", shape=(512, 4)),
}
)
processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
def preprocess_dataset(rows):
# Get images
images = [
Image.open(png_filename).convert("RGB") for png_filename in rows["png_filename"]
]
encoding = processor(
images,
rows["tokens"],
boxes=rows["bbox"],
truncation=True,
padding="max_length",
)
encoding["tokens"] = rows["tokens"]
return encoding
dataset = dataset.map(
preprocess_dataset,
batched=True,
batch_size=5,
features=features,
)
```
### Expected behavior
Using datasets==2.11.0, I'm able to succesfully push_to_hub, no issues, but with datasets==2.14.2, I run into the above error.
### Environment info
- `datasets` version: 2.14.2
- Platform: macOS-12.5-arm64-arm-64bit
- Python version: 3.10.12
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 1.5.3 | 6,112 |
https://github.com/huggingface/datasets/issues/6111 | raise FileNotFoundError("Directory {dataset_path} is neither a `Dataset` directory nor a `DatasetDict` directory." ) | [
"any idea?",
"This should work: `load_dataset(\"path/to/downloaded_repo\")`\r\n\r\n`load_from_disk` is intended to be used on directories created with `Dataset.save_to_disk` or `DatasetDict.save_to_disk`",
"> This should work: `load_dataset(\"path/to/downloaded_repo\")`\r\n> \r\n> `load_from_disk` is intended to be used on directories created with `Dataset.save_to_disk` or `DatasetDict.save_to_disk`\r\n\r\nThanks for your help. This works."
] | ### Describe the bug
For researchers in some countries or regions, it is usually the case that the download ability of `load_dataset` is disabled due to the complex network environment. People in these regions often prefer to use git clone or other programming tricks to manually download the files to the disk (for example, [How to elegantly download hf models, zhihu zhuanlan](https://zhuanlan.zhihu.com/p/475260268) proposed a crawlder based solution, and [Is there any mirror for hf_hub, zhihu answer](https://www.zhihu.com/question/371644077) provided some cloud based solutions, and [How to avoid pitfalls on Hugging face downloading, zhihu zhuanlan] gave some useful suggestions), and then use `load_from_disk` to get the dataset object.
However, when one finally has the local files on the disk, it is still buggy when trying to load the files into objects.
### Steps to reproduce the bug
Steps to reproduce the bug:
1. Found CIFAR dataset in hugging face: https://huggingface.co/datasets/cifar100/tree/main
2. Click ":" button to show "Clone repository" option, and then follow the prompts on the box:
```bash
cd my_directory_absolute
git lfs install
git clone https://huggingface.co/datasets/cifar100
ls my_directory_absolute/cifar100 # confirm that the directory exists and it is OK.
```
3. Write A python file to try to load the dataset
```python
from datasets import load_dataset, load_from_disk
dataset = load_from_disk("my_directory_absolute/cifar100")
```
Notice that according to issue #3700 , it is wrong to use load_dataset("my_directory_absolute/cifar100"), so we must use load_from_disk instead.
4. Then you will see the error reported:
```log
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[5], line 9
1 from datasets import load_dataset, load_from_disk
----> 9 dataset = load_from_disk("my_directory_absolute/cifar100")
File [~/miniconda3/envs/ai/lib/python3.10/site-packages/datasets/load.py:2232), in load_from_disk(dataset_path, fs, keep_in_memory, storage_options)
2230 return DatasetDict.load_from_disk(dataset_path, keep_in_memory=keep_in_memory, storage_options=storage_options)
2231 else:
-> 2232 raise FileNotFoundError(
2233 f"Directory {dataset_path} is neither a `Dataset` directory nor a `DatasetDict` directory."
2234 )
FileNotFoundError: Directory my_directory_absolute/cifar100 is neither a `Dataset` directory nor a `DatasetDict` directory.
```
### Expected behavior
The dataset should be load successfully.
### Environment info
```bash
datasets-cli env
```
-> results:
```txt
Copy-and-paste the text below in your GitHub issue.
- `datasets` version: 2.14.2
- Platform: Linux-4.18.0-372.32.1.el8_6.x86_64-x86_64-with-glibc2.28
- Python version: 3.10.12
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3
``` | 6,111 |
https://github.com/huggingface/datasets/issues/6110 | [BUG] Dataset initialized from in-memory data does not create cache. | [
"This is expected behavior. You must provide `cache_file_name` when performing `.map` on an in-memory dataset for the result to be cached."
] | ### Describe the bug
`Dataset` initialized from in-memory data (dictionary in my case, haven't tested with other types) does not create cache when processed with the `map` method, unlike `Dataset` initialized by other methods such as `load_dataset`.
### Steps to reproduce the bug
```python
# below code was run the second time so the map function can be loaded from cache if exists
from datasets import load_dataset, Dataset
dataset = load_dataset("tatsu-lab/alpaca")['train']
dataset = dataset.map(lambda x: {'input': x['input'] + 'hi'}) # some random map
print(len(dataset.cache_files))
# 1
# copy the exact same data but initialize from a dictionary
memory_dataset = Dataset.from_dict({
'instruction': dataset['instruction'],
'input': dataset['input'],
'output': dataset['output'],
'text': dataset['text']})
memory_dataset = memory_dataset.map(lambda x: {'input': x['input'] + 'hi'}) # exact same map
print(len(memory_dataset.cache_files))
# Map: 100%|██████████| 52002[/52002]
# 0
```
### Expected behavior
The `map` function should create cache regardless of the method the `Dataset` was created.
### Environment info
- `datasets` version: 2.14.2
- Platform: Linux-5.15.0-41-generic-x86_64-with-glibc2.31
- Python version: 3.9.16
- Huggingface_hub version: 0.14.1
- PyArrow version: 11.0.0
- Pandas version: 1.5.3 | 6,110 |
https://github.com/huggingface/datasets/issues/6109 | Problems in downloading Amazon reviews from HF | [
"Thanks for reporting, @610v4nn1.\r\n\r\nIndeed, the source data files are no longer available. We have contacted the authors of the dataset and they report that Amazon has decided to stop distributing the multilingual reviews dataset.\r\n\r\nWe are adding a notification about this issue to the dataset card.\r\n\r\nSee: https://huggingface.co/datasets/amazon_reviews_multi/discussions/4#64c3898db63057f1fd3ce1a0 ",
"The dataset can be accessed from https://www.kaggle.com/datasets/mexwell/amazon-reviews-multi.",
"For those willing to transform the csv files from Kaggle into Huggingface datasets for their NLP course (exercise on summarisation), you can use this code on Google Collab:\r\n\r\n`from datasets import load_dataset\r\n\r\nimport pandas as pd\r\nfrom datasets import Dataset, DatasetDict\r\n\r\n# Load your CSV previously downloaded files from Kaggle on Google Collab\r\ntrain_csv_path = \"/content/train.csv\"\r\nvalidation_csv_path = \"/content/validation.csv\"\r\ntest_csv_path = '/content/test.csv'\r\n\r\n# Read CSV files into pandas DataFrames\r\ntrain_df = pd.read_csv(train_csv_path, engine='python')\r\nvalidation_df = pd.read_csv(validation_csv_path, engine='python')\r\ntest_df = pd.read_csv(test_csv_path, engine='python')\r\n\r\n# Filter by language ('es' for Spanish and 'en' for English)\r\nspanish_train_df = train_df[train_df['language'] == 'es']\r\nspanish_validation_df = validation_df[validation_df['language'] == 'es']\r\nspanish_test_df = test_df[test_df['language'] == 'es']\r\n\r\nenglish_train_df = train_df[train_df['language'] == 'en']\r\nenglish_validation_df = validation_df[validation_df['language'] == 'en']\r\nenglish_test_df = test_df[test_df['language'] == 'en']\r\n\r\n# Create Hugging Face datasets\r\nspanish_dataset = DatasetDict({\r\n 'train': Dataset.from_pandas(spanish_train_df),\r\n 'validation': Dataset.from_pandas(spanish_validation_df),\r\n 'test': Dataset.from_pandas(spanish_test_df)\r\n})\r\n\r\nenglish_dataset = DatasetDict({\r\n 'train': Dataset.from_pandas(english_train_df),\r\n 'validation': Dataset.from_pandas(english_validation_df),\r\n 'test': Dataset.from_pandas(english_test_df)\r\n})\r\nenglish_dataset = english_dataset.remove_columns(['Unnamed: 0', '__index_level_0__'])\r\nspanish_dataset = spanish_dataset.remove_columns(['Unnamed: 0', '__index_level_0__'])`"
] | ### Describe the bug
I have a script downloading `amazon_reviews_multi`.
When the download starts, I get
```
Downloading data files: 0%| | 0/1 [00:00<?, ?it/s]
Downloading data: 243B [00:00, 1.43MB/s]
Downloading data files: 100%|██████████| 1/1 [00:01<00:00, 1.54s/it]
Extracting data files: 100%|██████████| 1/1 [00:00<00:00, 842.40it/s]
Downloading data files: 0%| | 0/1 [00:00<?, ?it/s]
Downloading data: 243B [00:00, 928kB/s]
Downloading data files: 100%|██████████| 1/1 [00:01<00:00, 1.42s/it]
Extracting data files: 100%|██████████| 1/1 [00:00<00:00, 832.70it/s]
Downloading data files: 0%| | 0/1 [00:00<?, ?it/s]
Downloading data: 243B [00:00, 1.81MB/s]
Downloading data files: 100%|██████████| 1/1 [00:01<00:00, 1.40s/it]
Extracting data files: 100%|██████████| 1/1 [00:00<00:00, 1294.14it/s]
Generating train split: 0%| | 0/200000 [00:00<?, ? examples/s]
```
the file is clearly too small to contain the requested dataset, in fact it contains en error message:
```
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>AGJWSY3ZADT2QVWE</RequestId><HostId>Gx1O2KXnxtQFqvzDLxyVSTq3+TTJuTnuVFnJL3SP89Yp8UzvYLPTVwd1PpniE4EvQzT3tCaqEJw=</HostId></Error>
```
obviously the script fails:
```
> raise DatasetGenerationError("An error occurred while generating the dataset") from e
E datasets.builder.DatasetGenerationError: An error occurred while generating the dataset
```
### Steps to reproduce the bug
1. load_dataset("amazon_reviews_multi", name="en", split="train", cache_dir="ADDYOURPATHHERE")
### Expected behavior
I would expect the dataset to be downloaded and processed
### Environment info
* The problem is present with both datasets 2.12.0 and 2.14.2
* python version 3.10.12 | 6,109 |
https://github.com/huggingface/datasets/issues/6108 | Loading local datasets got strangely stuck | [
"Yesterday I waited for more than 12 hours to make sure it was really **stuck** instead of proceeding too slow.",
"I've had similar weird issues with `load_dataset` as well. Not multiple files, but dataset is quite big, about 50G.",
"We use a generic multiprocessing code, so there is little we can do about this - unfortunately, turning off multiprocessing seems to be the only solution. Multithreading would make our code easier to maintain and (most likely) avoid issues such as this one, but we cannot use it until the GIL is dropped (no-GIL Python should be released in 2024, so we can start exploring this then)",
"The problem seems to be the `Generating train split`. Is it possible to avoid that? I have a dataset saved, just want to load it but somehow running into issues with that again.",
"Hey guys, recently I ran into this problem again and I spent one whole day trying to locate the problem. Finally I found the problem seems to be with `pyarrow`'s json parser, and it seems a long-existing problem. Similar issue can be found in #2181. Anyway, my solution is to adjust the `load_dataset`'s parameter `chunksize`. You can inspect the parameter set in `datasets/packaged_modules/json/json.py`, now the actual chunksize should be very small, and you can increase the value. For me, `chunksize=10<<23` could solve the stuck problem. But I also find that too big `chunksize`, like `10 << 30`, would also cause a stuck, which is rather weird. I think I may explore this when I am free. And hope this can help those who also encounter the same problem. ",
"Experiencing the same issue with the `kaist-ai/Feedback-Collection` dataset, which is comparatively small i.e. 100k rows.\r\nCode to reproduce\r\n\r\n```\r\nfrom datasets import load_dataset\r\ndataset = load_dataset(\"kaist-ai/Feedback-Collection\")\r\n```\r\n\r\nI have tried setting `num_proc=1` as well as `chunksize=1024, 64` but problem persists. Any pointers?"
] | ### Describe the bug
I try to use `load_dataset()` to load several local `.jsonl` files as a dataset. Every line of these files is a json structure only containing one key `text` (yeah it is a dataset for NLP model). The code snippet is as:
```python
ds = load_dataset("json", data_files=LIST_OF_FILE_PATHS, num_proc=16)['train']
```
However, I found that the loading process can get stuck -- the progress bar `Generating train split` no more proceed. When I was trying to find the cause and solution, I found a really strange behavior. If I load the dataset in this way:
```python
dlist = list()
for _ in LIST_OF_FILE_PATHS:
dlist.append(load_dataset("json", data_files=_)['train'])
ds = concatenate_datasets(dlist)
```
I can actually successfully load all the files despite its slow speed. But if I load them in batch like above, things go wrong. I did try to use Control-C to trace the stuck point but the program cannot be terminated in this way when `num_proc` is set to `None`. The only thing I can do is use Control-Z to hang it up then kill it. If I use more than 2 cpus, a Control-C would simply cause the following error:
```bash
^C
Process ForkPoolWorker-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/multiprocess/process.py", line 314, in _bootstrap
self.run()
File "/usr/local/lib/python3.10/dist-packages/multiprocess/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.10/dist-packages/multiprocess/pool.py", line 114, in worker
task = get()
File "/usr/local/lib/python3.10/dist-packages/multiprocess/queues.py", line 368, in get
res = self._reader.recv_bytes()
File "/usr/local/lib/python3.10/dist-packages/multiprocess/connection.py", line 224, in recv_bytes
buf = self._recv_bytes(maxlength)
File "/usr/local/lib/python3.10/dist-packages/multiprocess/connection.py", line 422, in _recv_bytes
buf = self._recv(4)
File "/usr/local/lib/python3.10/dist-packages/multiprocess/connection.py", line 387, in _recv
chunk = read(handle, remaining)
KeyboardInterrupt
Generating train split: 92431 examples [01:23, 1104.25 examples/s]
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/datasets/utils/py_utils.py", line 1373, in iflatmap_unordered
yield queue.get(timeout=0.05)
File "<string>", line 2, in get
File "/usr/local/lib/python3.10/dist-packages/multiprocess/managers.py", line 818, in _callmethod
kind, result = conn.recv()
File "/usr/local/lib/python3.10/dist-packages/multiprocess/connection.py", line 258, in recv
buf = self._recv_bytes()
File "/usr/local/lib/python3.10/dist-packages/multiprocess/connection.py", line 422, in _recv_bytes
buf = self._recv(4)
File "/usr/local/lib/python3.10/dist-packages/multiprocess/connection.py", line 387, in _recv
chunk = read(handle, remaining)
KeyboardInterrupt
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/mnt/data/liyongyuan/source/batch_load.py", line 11, in <module>
a = load_dataset(
File "/usr/local/lib/python3.10/dist-packages/datasets/load.py", line 2133, in load_dataset
builder_instance.download_and_prepare(
File "/usr/local/lib/python3.10/dist-packages/datasets/builder.py", line 954, in download_and_prepare
self._download_and_prepare(
File "/usr/local/lib/python3.10/dist-packages/datasets/builder.py", line 1049, in _download_and_prepare
self._prepare_split(split_generator, **prepare_split_kwargs)
File "/usr/local/lib/python3.10/dist-packages/datasets/builder.py", line 1842, in _prepare_split
for job_id, done, content in iflatmap_unordered(
File "/usr/local/lib/python3.10/dist-packages/datasets/utils/py_utils.py", line 1387, in iflatmap_unordered
[async_result.get(timeout=0.05) for async_result in async_results]
File "/usr/local/lib/python3.10/dist-packages/datasets/utils/py_utils.py", line 1387, in <listcomp>
[async_result.get(timeout=0.05) for async_result in async_results]
File "/usr/local/lib/python3.10/dist-packages/multiprocess/pool.py", line 770, in get
raise TimeoutError
multiprocess.context.TimeoutError
```
I have validated the basic correctness of these `.jsonl` files. They are correctly formatted (or they cannot be loaded singly by `load_dataset`) though some of the json may contain too long text (more than 1e7 characters). I do not know if this could be the problem. And there should not be any bottleneck in system's resource. The whole dataset is ~300GB, and I am using a cloud server with plenty of storage and 1TB ram.
Thanks for your efforts and patience! Any suggestion or help would be appreciated.
### Steps to reproduce the bug
1. use load_dataset() with `data_files = LIST_OF_FILES`
### Expected behavior
All the files should be smoothly loaded.
### Environment info
- Datasets: A private dataset. ~2500 `.jsonl` files. ~300GB in total. Each json structure only contains one key: `text`. Format checked.
- `datasets` version: 2.14.2
- Platform: Linux-4.19.91-014.kangaroo.alios7.x86_64-x86_64-with-glibc2.35
- Python version: 3.10.6
- Huggingface_hub version: 0.15.1
- PyArrow version: 10.0.1.dev0+ga6eabc2b.d20230609
- Pandas version: 1.5.2 | 6,108 |
https://github.com/huggingface/datasets/issues/6106 | load local json_file as dataset | [
"Hi! We use PyArrow to read JSON files, and PyArrow doesn't allow different value types in the same column. #5776 should address this.\r\n\r\nIn the meantime, you can combine `Dataset.from_generator` with the above code to cast the values to the same type. ",
"Thanks for your help!"
] | ### Describe the bug
I tried to load local json file as dataset but failed to parsing json file because some columns are 'float' type.
### Steps to reproduce the bug
1. load json file with certain columns are 'float' type. For example `data = load_data("json", data_files=JSON_PATH)`
2. Then, the error will be triggered like `ArrowInvalid: Could not convert '-0.2253' with type str: tried to convert to double
### Expected behavior
Should allow some columns are 'float' type, at least it should convert those columns to str type.
I tried to avoid the error by naively convert the float item to str:
```python
# if col type is not str, we need to convert it to str
mapping = {}
for col in keys:
if isinstance(dataset[0][col], str):
mapping[col] = [row.get(col) for row in dataset]
else:
mapping[col] = [str(row.get(col)) for row in dataset]
```
### Environment info
- `datasets` version: 2.14.2
- Platform: Linux-5.4.0-52-generic-x86_64-with-glibc2.31
- Python version: 3.9.16
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.0
- Pandas version: 2.0.1 | 6,106 |
https://github.com/huggingface/datasets/issues/6104 | HF Datasets data access is extremely slow even when in memory | [
"Possibly related:\r\n- https://github.com/pytorch/pytorch/issues/22462"
] | ### Describe the bug
Doing a simple `some_dataset[:10]` can take more than a minute.
Profiling it:
<img width="1280" alt="image" src="https://github.com/huggingface/datasets/assets/36224762/e641fb95-ff02-4072-9016-5416a65f75ab">
`some_dataset` is completely in memory with no disk cache.
This is proving fatal to my usage of HF Datasets. Is there a way I can forgo the arrow format and store the dataset as PyTorch tensors so that `_tensorize` is not needed? And is `_consolidate` supposed to take this long?
It's faster to produce the dataset from scratch than to access it from HF Datasets!
### Steps to reproduce the bug
I have uploaded the dataset that causes this problem [here](https://huggingface.co/datasets/NightMachinery/hf_datasets_bug1).
```python
#!/usr/bin/env python3
import sys
import time
import torch
from datasets import load_dataset
def main(dataset_name):
# Start the timer
start_time = time.time()
# Load the dataset from Hugging Face Hub
dataset = load_dataset(dataset_name)
# Set the dataset format as torch
dataset.set_format(type="torch")
# Perform an identity map
dataset = dataset.map(lambda example: example, batched=True, batch_size=20)
# End the timer
end_time = time.time()
# Print the time taken
print(f"Time taken: {end_time - start_time:.2f} seconds")
if __name__ == "__main__":
dataset_name = "NightMachinery/hf_datasets_bug1"
print(f"dataset_name: {dataset_name}")
main(dataset_name)
```
### Expected behavior
_
### Environment info
- `datasets` version: 2.13.1
- Platform: Linux-5.15.0-76-generic-x86_64-with-glibc2.35
- Python version: 3.10.12
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3 | 6,104 |
https://github.com/huggingface/datasets/issues/6100 | TypeError when loading from GCP bucket | [
"Thanks for reporting, @bilelomrani1.\r\n\r\nWe are fixing it. ",
"We have fixed it. We are planning to do a patch release today."
] | ### Describe the bug
Loading a dataset from a GCP bucket raises a type error. This bug was introduced recently (either in 2.14 or 2.14.1), and appeared during a migration from 2.13.1.
### Steps to reproduce the bug
Load any file from a GCP bucket:
```python
import datasets
datasets.load_dataset("json", data_files=["gs://..."])
```
The following exception is raised:
```python
Traceback (most recent call last):
...
packages/datasets/data_files.py", line 335, in resolve_pattern
protocol_prefix = fs.protocol + "://" if fs.protocol != "file" else ""
TypeError: can only concatenate tuple (not "str") to tuple
```
With a `GoogleFileSystem`, the attribute `fs.protocol` is a tuple `('gs', 'gcs')` and hence cannot be concatenated with a string.
### Expected behavior
The file should be loaded without exception.
### Environment info
- `datasets` version: 2.14.1
- Platform: macOS-13.2.1-x86_64-i386-64bit
- Python version: 3.10.12
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 2.0.3
| 6,100 |
https://github.com/huggingface/datasets/issues/6099 | How do i get "amazon_us_reviews | [
"Seems like the problem isn't with the library, but the dataset itself hosted on AWS S3.\r\n\r\nIts [homepage](https://s3.amazonaws.com/amazon-reviews-pds/readme.html) returns an `AccessDenied` XML response, which is the same thing you get if you try to log the `record` that triggers the exception\r\n\r\n```python\r\ntry:\r\n example = self.info.features.encode_example(record) if self.info.features is not None else record\r\nexcept Exception as e:\r\n print(record)\r\n```\r\n\r\n⬇️\r\n\r\n```\r\n{'<?xml version=\"1.0\" encoding=\"UTF-8\"?>': '<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>N2HFJ82ZV8SZW9BV</RequestId><HostId>Zw2DQ0V2GdRmvH5qWEpumK4uj5+W8YPcilQbN9fLBr3VqQOcKPHOhUZLG3LcM9X5fkOetxp48Os=</HostId></Error>'}\r\n```",
"I'm getting same errors when loading this dataset",
"I have figured it out. there was an option of **parquet formated files** i downloaded some from there. ",
"this dataset is unfortunately no longer public",
"Thanks for reporting, @IqraBaluch.\r\n\r\nWe contacted the authors and unfortunately they reported that Amazon has decided to stop distributing this dataset.",
"If anyone still needs this dataset, you could find it on kaggle here : https://www.kaggle.com/datasets/cynthiarempel/amazon-us-customer-reviews-dataset",
"Thanks @Maryam-Mostafa ",
"@albertvillanova don't tell 'em, we have figured it out. XD",
"I noticed that some book data is missing, we can only get Books_v1_02 data. \r\nIs there any way we can get the Books_v1_00 and Books_v1_01? \r\nReally appreciate !!!",
"@albertvillanova will this dataset be retired given the data are no longer hosted on S3? What is done in cases such as these?"
] | ### Feature request
I have been trying to load 'amazon_us_dataset" but unable to do so.
`amazon_us_reviews = load_dataset('amazon_us_reviews')`
`print(amazon_us_reviews)`
> [ValueError: Config name is missing.
Please pick one among the available configs: ['Wireless_v1_00', 'Watches_v1_00', 'Video_Games_v1_00', 'Video_DVD_v1_00', 'Video_v1_00', 'Toys_v1_00', 'Tools_v1_00', 'Sports_v1_00', 'Software_v1_00', 'Shoes_v1_00', 'Pet_Products_v1_00', 'Personal_Care_Appliances_v1_00', 'PC_v1_00', 'Outdoors_v1_00', 'Office_Products_v1_00', 'Musical_Instruments_v1_00', 'Music_v1_00', 'Mobile_Electronics_v1_00', 'Mobile_Apps_v1_00', 'Major_Appliances_v1_00', 'Luggage_v1_00', 'Lawn_and_Garden_v1_00', 'Kitchen_v1_00', 'Jewelry_v1_00', 'Home_Improvement_v1_00', 'Home_Entertainment_v1_00', 'Home_v1_00', 'Health_Personal_Care_v1_00', 'Grocery_v1_00', 'Gift_Card_v1_00', 'Furniture_v1_00', 'Electronics_v1_00', 'Digital_Video_Games_v1_00', 'Digital_Video_Download_v1_00', 'Digital_Software_v1_00', 'Digital_Music_Purchase_v1_00', 'Digital_Ebook_Purchase_v1_00', 'Camera_v1_00', 'Books_v1_00', 'Beauty_v1_00', 'Baby_v1_00', 'Automotive_v1_00', 'Apparel_v1_00', 'Digital_Ebook_Purchase_v1_01', 'Books_v1_01', 'Books_v1_02']
Example of usage:
`load_dataset('amazon_us_reviews', 'Wireless_v1_00')`]
__________________________________________________________________________
`amazon_us_reviews = load_dataset('amazon_us_reviews', 'Watches_v1_00')
print(amazon_us_reviews)`
**ERROR**
`Generating` train split: 0%
0/960872 [00:00<?, ? examples/s]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/datasets/builder.py in _prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id)
1692 )
-> 1693 example = self.info.features.encode_example(record) if self.info.features is not None else record
1694 writer.write(example, key)
11 frames
KeyError: 'marketplace'
The above exception was the direct cause of the following exception:
DatasetGenerationError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/datasets/builder.py in _prepare_split_single(self, gen_kwargs, fpath, file_format, max_shard_size, split_info, check_duplicate_keys, job_id)
1710 if isinstance(e, SchemaInferenceError) and e.__context__ is not None:
1711 e = e.__context__
-> 1712 raise DatasetGenerationError("An error occurred while generating the dataset") from e
1713
1714 yield job_id, True, (total_num_examples, total_num_bytes, writer._features, num_shards, shard_lengths)
DatasetGenerationError: An error occurred while generating the dataset
### Motivation
The dataset I'm using
https://huggingface.co/datasets/amazon_us_reviews
### Your contribution
What is the best way to load this data | 6,099 |
https://github.com/huggingface/datasets/issues/6097 | Dataset.get_nearest_examples does not return all feature values for the k most similar datapoints - side effect of Dataset.set_format | [
"Actually, my bad -- specifying\r\n```python\r\nfoo.set_format('numpy', ['vectors'], output_all_columns=True)\r\n```\r\nfixes it."
] | ### Describe the bug
Hi team!
I observe that there seems to be a side effect of `Dataset.set_format`: after setting a format and creating a FAISS index, the method `get_nearest_examples` from the `Dataset` class, fails to retrieve anything else but the embeddings themselves - not super useful. This is not the case if not using the `set_format` method: you can also retrieve any other feature value, such as an index/id/etc.
Are you able to reproduce what I observe?
### Steps to reproduce the bug
```python
from datasets import Dataset
import numpy as np
foo = {'vectors': np.random.random((100,1024)), 'ids': [str(u) for u in range(100)]}
foo = Dataset.from_dict(foo)
foo.set_format('numpy', ['vectors'])
foo.add_faiss_index('vectors')
new_vector = np.random.random(1024)
scores, res = foo.get_nearest_examples('vectors', new_vector, k=3)
```
This will return, for the resulting most similar vectors to `new_vector` - in particular it will not return the `ids` feature:
```
{'vectors': array([[random values ...]])}
```
### Expected behavior
The expected behavior happens when the `set_format` method is not called:
```python
from datasets import Dataset
import numpy as np
foo = {'vectors': np.random.random((100,1024)), 'ids': [str(u) for u in range(100)]}
foo = Dataset.from_dict(foo)
# foo.set_format('numpy', ['vectors'])
foo.add_faiss_index('vectors')
new_vector = np.random.random(1024)
scores, res = foo.get_nearest_examples('vectors', new_vector, k=3)
```
This *will* return the `ids` of the similar vectors - with unfortunately a list of lists in lieu of the array I think for caching reasons - read it elsewhere
```
{'vectors': [[random values on multiple lines...]], 'ids': ['x', 'y', 'z']}
```
### Environment info
- `datasets` version: 2.12.0
- Platform: Linux-5.4.0-155-generic-x86_64-with-glibc2.31
- Python version: 3.10.6
- Huggingface_hub version: 0.15.1
- PyArrow version: 11.0.0
- Pandas version: 1.5.3
| 6,097 |
https://github.com/huggingface/datasets/issues/6090 | FilesIterable skips all the files after a hidden file | [
"Thanks for reporting. We've merged a PR with a fix."
] | ### Describe the bug
When initializing `FilesIterable` with a list of file paths using `FilesIterable.from_paths`, it will discard all the files after a hidden file.
The problem is in [this line](https://github.com/huggingface/datasets/blob/88896a7b28610ace95e444b94f9a4bc332cc1ee3/src/datasets/download/download_manager.py#L233C26-L233C26) where `return` should be replaced by `continue`.
### Steps to reproduce the bug
https://colab.research.google.com/drive/1SQlxs4y_LSo1Q89KnFoYDSyyKEISun_J#scrollTo=93K4_blkW-8-
### Expected behavior
The script should print all the files except the hidden one.
### Environment info
- `datasets` version: 2.14.1
- Platform: Linux-5.15.109+-x86_64-with-glibc2.35
- Python version: 3.10.6
- Huggingface_hub version: 0.16.4
- PyArrow version: 9.0.0
- Pandas version: 1.5.3 | 6,090 |
https://github.com/huggingface/datasets/issues/6089 | AssertionError: daemonic processes are not allowed to have children | [
"We could add a \"threads\" parallel backend to `datasets.parallel.parallel_backend` to support downloading with threads but note that `download_and_extract` also decompresses archives, and this is a CPU-intensive task, which is not ideal for (Python) threads (good for IO-intensive tasks).",
"> We could add a \"threads\" parallel backend to `datasets.parallel.parallel_backend` to support downloading with threads but note that `download_and_extract` also decompresses archives, and this is a CPU-intensive task, which is not ideal for (Python) threads (good for IO-intensive tasks).\r\n\r\nGreat! Download takes more time than extract, multiple threads can download in parallel, which can speed up a lot."
] | ### Describe the bug
When I load_dataset with num_proc > 0 in a deamon process, I got an error:
```python
File "/Users/codingl2k1/Work/datasets/src/datasets/download/download_manager.py", line 564, in download_and_extract
return self.extract(self.download(url_or_urls))
^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/download/download_manager.py", line 427, in download
downloaded_path_or_paths = map_nested(
^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/utils/py_utils.py", line 468, in map_nested
mapped = parallel_map(function, iterable, num_proc, types, disable_tqdm, desc, _single_map_nested)
^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/utils/experimental.py", line 40, in _inner_fn
return fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/parallel/parallel.py", line 34, in parallel_map
return _map_with_multiprocessing_pool(
^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/parallel/parallel.py", line 64, in _map_with_multiprocessing_pool
with Pool(num_proc, initargs=initargs, initializer=initializer) as pool:
^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/context.py", line 119, in Pool
return Pool(processes, initializer, initargs, maxtasksperchild,
^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/pool.py", line 215, in __init__
self._repopulate_pool()
^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/pool.py", line 306, in _repopulate_pool
return self._repopulate_pool_static(self._ctx, self.Process,
^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/pool.py", line 329, in _repopulate_pool_static
w.start()
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/process.py", line 118, in start
assert not _current_process._config.get('daemon'), ^^^^^^^^^^^^^^^^^
AssertionError: daemonic processes are not allowed to have children
```
The download is io-intensive computing, may be datasets can replece the multi processing pool by a multi threading pool if in a deamon process.
### Steps to reproduce the bug
1. start a deamon process
2. run load_dataset with num_proc > 0
### Expected behavior
No error.
### Environment info
Python 3.11.4
datasets latest master | 6,089 |
https://github.com/huggingface/datasets/issues/6088 | Loading local data files initiates web requests | [] | As documented in the [official docs](https://huggingface.co/docs/datasets/v2.14.0/en/package_reference/loading_methods#datasets.load_dataset.example-2), I tried to load datasets from local files by
```python
# Load a JSON file
from datasets import load_dataset
ds = load_dataset('json', data_files='path/to/local/my_dataset.json')
```
But this failed on a web request because I'm executing the script on a machine without Internet access. Stacktrace shows
```
in PackagedDatasetModuleFactory.__init__(self, name, data_dir, data_files, download_config, download_mode)
940 self.download_config = download_config
941 self.download_mode = download_mode
--> 942 increase_load_count(name, resource_type="dataset")
```
I've read from the source code that this can be fixed by setting environment variable to run in offline mode. I'm just wondering that is this an expected behaviour that even loading a LOCAL JSON file requires Internet access by default? And what's the point of requesting to `increase_load_count` on some server when loading just LOCAL data files? | 6,088 |
https://github.com/huggingface/datasets/issues/6087 | fsspec dependency is set too low | [
"Thanks for reporting! A PR with a fix has just been merged."
] | ### Describe the bug
fsspec.callbacks.TqdmCallback (used in https://github.com/huggingface/datasets/blob/73bed12ecda17d1573fd3bf73ed5db24d3622f86/src/datasets/utils/file_utils.py#L338) was first released in fsspec [2022.3.0](https://github.com/fsspec/filesystem_spec/releases/tag/2022.3.0, commit where it was added: https://github.com/fsspec/filesystem_spec/commit/9577c8a482eb0a69092913b81580942a68d66a76#diff-906155c7e926a9ff58b9f23369bb513b09b445f5b0f41fa2a84015d0b471c68cR180), however the dependency is set to 2021.11.1 https://github.com/huggingface/datasets/blob/main/setup.py#L129
### Steps to reproduce the bug
1. Install fsspec==2021.11.1
2. Install latest datasets==2.14.1
3. Import datasets, import fails due to lack of `fsspec.callbacks.TqdmCallback`
### Expected behavior
No import issue
### Environment info
N/A | 6,087 |
https://github.com/huggingface/datasets/issues/6086 | Support `fsspec` in `Dataset.to_<format>` methods | [
"Hi @mariosasko unless someone's already working on it, I guess I can tackle it!",
"Hi! Sure, feel free to tackle this.",
"#self-assign",
"I'm assuming this should just cover `to_csv`, `to_parquet`, and `to_json`, right? As `to_list` and `to_dict` just return Python objects, `to_pandas` returns a `pandas.DataFrame` and `to_sql` just inserts into a SQL DB, is that right?",
"Fixed by #6096. "
] | Supporting this should be fairly easy.
Requested on the forum [here](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-can-i-convert-a-loaded-dataset-in-to-a-parquet-file-and-save-it-to-the-s3%2F48353).%3C%2Fdiv%3E%3C%2Fdiv%3E
| 6,086 |
https://github.com/huggingface/datasets/issues/6084 | Changing pixel values of images in the Winoground dataset | [] | Hi, as I followed the instructions, with lasted "datasets" version:
"
from datasets import load_dataset
examples = load_dataset('facebook/winoground', use_auth_token=<YOUR USER ACCESS TOKEN>)
"
I got slightly different datasets in colab and in my hpc environment. Specifically, the pixel values of images are slightly different.
I thought it was due to the package version difference, but today's morning I found out that my winoground dataset in colab became the same with the one in my hpc environment. The dataset in colab can produce the correct result but now it is gone as well.
Can you help me with this? What causes the datasets to have the wrong pixel values? | 6,084 |
https://github.com/huggingface/datasets/issues/6079 | Iterating over DataLoader based on HF datasets is stuck forever | [
"When the process starts to hang, can you interrupt it with CTRL + C and paste the error stack trace here? ",
"Thanks @mariosasko for your prompt response, here's the stack trace:\r\n\r\n```\r\nKeyboardInterrupt Traceback (most recent call last)\r\nCell In[12], line 4\r\n 2 t = time.time()\r\n 3 iter_ = 0\r\n----> 4 for batch in train_dataloader:\r\n 5 #batch_proc = streaming_obj.collect_streaming_data_batch(batch)\r\n 6 iter_ += 1\r\n 8 if iter_ == 1:\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/torch/utils/data/dataloader.py:634, in _BaseDataLoaderIter.__next__(self)\r\n 631 if self._sampler_iter is None:\r\n 632 # TODO(https://github.com/pytorch/pytorch/issues/76750)\r\n 633 self._reset() # type: ignore[call-arg]\r\n--> 634 data = self._next_data()\r\n 635 self._num_yielded += 1\r\n 636 if self._dataset_kind == _DatasetKind.Iterable and \\\r\n 637 self._IterableDataset_len_called is not None and \\\r\n 638 self._num_yielded > self._IterableDataset_len_called:\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/torch/utils/data/dataloader.py:678, in _SingleProcessDataLoaderIter._next_data(self)\r\n 676 def _next_data(self):\r\n 677 index = self._next_index() # may raise StopIteration\r\n--> 678 data = self._dataset_fetcher.fetch(index) # may raise StopIteration\r\n 679 if self._pin_memory:\r\n 680 data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py:32, in _IterableDatasetFetcher.fetch(self, possibly_batched_index)\r\n 30 for _ in possibly_batched_index:\r\n 31 try:\r\n---> 32 data.append(next(self.dataset_iter))\r\n 33 except StopIteration:\r\n 34 self.ended = True\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/iterable_dataset.py:1353, in IterableDataset.__iter__(self)\r\n 1350 yield formatter.format_row(pa_table)\r\n 1351 return\r\n-> 1353 for key, example in ex_iterable:\r\n 1354 if self.features:\r\n 1355 # `IterableDataset` automatically fills missing columns with None.\r\n 1356 # This is done with `_apply_feature_types_on_example`.\r\n 1357 example = _apply_feature_types_on_example(\r\n 1358 example, self.features, token_per_repo_id=self._token_per_repo_id\r\n 1359 )\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/iterable_dataset.py:956, in BufferShuffledExamplesIterable.__iter__(self)\r\n 954 # this is the shuffle buffer that we keep in memory\r\n 955 mem_buffer = []\r\n--> 956 for x in self.ex_iterable:\r\n 957 if len(mem_buffer) == buffer_size: # if the buffer is full, pick and example from it\r\n 958 i = next(indices_iterator)\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/iterable_dataset.py:296, in ShuffledDataSourcesArrowExamplesIterable.__iter__(self)\r\n 294 for key, pa_table in self.generate_tables_fn(**kwargs_with_shuffled_shards):\r\n 295 for pa_subtable in pa_table.to_reader(max_chunksize=config.ARROW_READER_BATCH_SIZE_IN_DATASET_ITER):\r\n--> 296 formatted_batch = formatter.format_batch(pa_subtable)\r\n 297 for example in _batch_to_examples(formatted_batch):\r\n 298 yield key, example\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/formatting/formatting.py:448, in PythonFormatter.format_batch(self, pa_table)\r\n 446 if self.lazy:\r\n 447 return LazyBatch(pa_table, self)\r\n--> 448 batch = self.python_arrow_extractor().extract_batch(pa_table)\r\n 449 batch = self.python_features_decoder.decode_batch(batch)\r\n 450 return batch\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/formatting/formatting.py:150, in PythonArrowExtractor.extract_batch(self, pa_table)\r\n 149 def extract_batch(self, pa_table: pa.Table) -> dict:\r\n--> 150 return pa_table.to_pydict()\r\n\r\nKeyboardInterrupt: \r\n```\r\n",
"Update: If i let it run, it eventually fails with:\r\n\r\n```\r\nRuntimeError Traceback (most recent call last)\r\nCell In[16], line 4\r\n 2 t = time.time()\r\n 3 iter_ = 0\r\n----> 4 for batch in train_dataloader:\r\n 5 #batch_proc = streaming_obj.collect_streaming_data_batch(batch)\r\n 6 iter_ += 1\r\n 8 if iter_ == 1:\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/torch/utils/data/dataloader.py:634, in _BaseDataLoaderIter.__next__(self)\r\n 631 if self._sampler_iter is None:\r\n 632 # TODO(https://github.com/pytorch/pytorch/issues/76750)\r\n 633 self._reset() # type: ignore[call-arg]\r\n--> 634 data = self._next_data()\r\n 635 self._num_yielded += 1\r\n 636 if self._dataset_kind == _DatasetKind.Iterable and \\\r\n 637 self._IterableDataset_len_called is not None and \\\r\n 638 self._num_yielded > self._IterableDataset_len_called:\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/torch/utils/data/dataloader.py:678, in _SingleProcessDataLoaderIter._next_data(self)\r\n 676 def _next_data(self):\r\n 677 index = self._next_index() # may raise StopIteration\r\n--> 678 data = self._dataset_fetcher.fetch(index) # may raise StopIteration\r\n 679 if self._pin_memory:\r\n 680 data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py:32, in _IterableDatasetFetcher.fetch(self, possibly_batched_index)\r\n 30 for _ in possibly_batched_index:\r\n 31 try:\r\n---> 32 data.append(next(self.dataset_iter))\r\n 33 except StopIteration:\r\n 34 self.ended = True\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/iterable_dataset.py:1360, in IterableDataset.__iter__(self)\r\n 1354 if self.features:\r\n 1355 # `IterableDataset` automatically fills missing columns with None.\r\n 1356 # This is done with `_apply_feature_types_on_example`.\r\n 1357 example = _apply_feature_types_on_example(\r\n 1358 example, self.features, token_per_repo_id=self._token_per_repo_id\r\n 1359 )\r\n-> 1360 yield format_dict(example) if format_dict else example\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/formatting/torch_formatter.py:85, in TorchFormatter.recursive_tensorize(self, data_struct)\r\n 84 def recursive_tensorize(self, data_struct: dict):\r\n---> 85 return map_nested(self._recursive_tensorize, data_struct, map_list=False)\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/utils/py_utils.py:463, in map_nested(function, data_struct, dict_only, map_list, map_tuple, map_numpy, num_proc, parallel_min_length, types, disable_tqdm, desc)\r\n 461 num_proc = 1\r\n 462 if num_proc != -1 and num_proc <= 1 or len(iterable) < parallel_min_length:\r\n--> 463 mapped = [\r\n 464 _single_map_nested((function, obj, types, None, True, None))\r\n 465 for obj in logging.tqdm(iterable, disable=disable_tqdm, desc=desc)\r\n 466 ]\r\n 467 else:\r\n 468 mapped = parallel_map(function, iterable, num_proc, types, disable_tqdm, desc, _single_map_nested)\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/utils/py_utils.py:464, in <listcomp>(.0)\r\n 461 num_proc = 1\r\n 462 if num_proc != -1 and num_proc <= 1 or len(iterable) < parallel_min_length:\r\n 463 mapped = [\r\n--> 464 _single_map_nested((function, obj, types, None, True, None))\r\n 465 for obj in logging.tqdm(iterable, disable=disable_tqdm, desc=desc)\r\n 466 ]\r\n 467 else:\r\n 468 mapped = parallel_map(function, iterable, num_proc, types, disable_tqdm, desc, _single_map_nested)\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/utils/py_utils.py:366, in _single_map_nested(args)\r\n 364 # Singleton first to spare some computation\r\n 365 if not isinstance(data_struct, dict) and not isinstance(data_struct, types):\r\n--> 366 return function(data_struct)\r\n 368 # Reduce logging to keep things readable in multiprocessing with tqdm\r\n 369 if rank is not None and logging.get_verbosity() < logging.WARNING:\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/formatting/torch_formatter.py:82, in TorchFormatter._recursive_tensorize(self, data_struct)\r\n 80 elif isinstance(data_struct, (list, tuple)):\r\n 81 return self._consolidate([self.recursive_tensorize(substruct) for substruct in data_struct])\r\n---> 82 return self._tensorize(data_struct)\r\n\r\nFile ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/datasets/formatting/torch_formatter.py:68, in TorchFormatter._tensorize(self, value)\r\n 66 if isinstance(value, PIL.Image.Image):\r\n 67 value = np.asarray(value)\r\n---> 68 return torch.tensor(value, **{**default_dtype, **self.torch_tensor_kwargs})\r\n\r\nRuntimeError: Could not infer dtype of decimal.Decimal\r\n```",
"PyTorch tensors cannot store `Decimal` objects. Casting the column with decimals to `float` should fix the issue.",
"I already have cast in collate_fn, in which I perform .astype(float) for each numerical field.\r\nOn the same instance, I installed a conda env with python 3.6, and this works well.\r\n\r\nSample:\r\n\r\n```\r\ndef streaming_data_collate_fn(batch):\r\n df = pd.DataFrame.from_dict(batch)\r\n feat_vals = torch.FloatTensor(np.nan_to_num(np.array(df[feats].astype(float))))\r\n\r\n```",
"`collate_fn` is applied after the `torch` formatting step, so I think the only option when working with an `IterableDataset` is to remove the `with_format` call and perform the conversion from Python values to PyTorch tensors in `collate_fn`. The standard `Dataset` supports `with_format(\"numpy\")`, which should make this conversion faster.",
"Thanks! \r\nPython 3.10 conda-env: After replacing with_format(\"torch\") with with_format(\"numpy\"), the error went away. However, it was still taking over 2 minutes to load a very small batch of 64 samples with num_workers set to 32. Once I removed with_format call altogether, it is finishing in 11 seconds.\r\n\r\nPython 3.6 based conda-env: When I switch the kernel , neither of the above work, and with_format(\"torch\") is the only thing that works, and executes in 1.6 seconds.\r\n\r\nI feel something else is also amiss here.",
"Can you share the `datasets` and `torch` versions installed in these conda envs?\r\n\r\n> Once I removed with_format call altogether, it is finishing in 11 seconds.\r\n\r\nHmm, that's surprising. What are your dataset's `.features`?",
"Python 3.6: \r\ndatasets.__version__ 2.4.0\r\ntorch.__version__ 1.10.1+cu102\r\n\r\nPython 3.10:\r\ndatasets.__version__ 2.14.0\r\ntorch.__version__ 2.0.0\r\n\r\nAnonymized features are of the form (subset shown here):\r\n{\r\n'string_feature_i': Value(dtype='string', id=None),\r\n'numerical_feature_i': Value(dtype='decimal128(38, 0)', id=None),\r\n'numerical_feature_series_i': Sequence(feature=Value(dtype='float64', id=None), length=-1, id=None),\r\n}\r\n\r\n\r\nThere is no output from .features in python 3.6 kernel BTW.",
"One more thing, in python 3.10 based kernel, interestingly increasing num_workers seem to be increasing the runtime of iterating I was trying out. In python 3.10 kernel execution, I do not even see multiple CPU cores spiking unlike in 3.6.\r\n\r\n512 batch size on 32 workers executes in 2.4 seconds on python 3.6 kernel, while it takes ~118 seconds on 3.10!",
"**Update**: It seems the latency part is more of a multiprocessing issue with torch and some host specific issue, and I had to scourge through relevant pytorch issues, when I stumbled across these threads:\r\n1. https://github.com/pytorch/pytorch/issues/102494\r\n2. https://github.com/pytorch/pytorch/issues/102269\r\n3. https://github.com/pytorch/pytorch/issues/99625\r\n\r\nOut of the suggested solutions, the one that worked in my case was:\r\n```\r\nos.environ['KMP_AFFINITY'] = \"disabled\"\r\n```\r\nIt is working for now, though I have no clue why, just I hope it does not get stuck when I do actual model training, will update by tomorrow.\r\n\r\n\r\n",
"I'm facing a similar situation in the local VS Code. \r\n\r\nDatasets version 2.14.4\r\nTorch 2.0.1+cu118\r\n\r\nSame code runs without issues in Colab\r\n\r\n```\r\nfrom datasets import load_dataset\r\n\r\ndataset = load_dataset(\"Supermaxman/esa-hubble\", streaming=True)\r\nsample = next(iter(dataset[\"train\"]))\r\n```\r\n\r\nis stuck for minutes. If I interrupt, I get\r\n\r\n```\r\n---------------------------------------------------------------------------\r\nKeyboardInterrupt Traceback (most recent call last)\r\nCell In[5], line 5\r\n 1 from datasets import load_dataset\r\n 3 dataset = load_dataset(\"Supermaxman/esa-hubble\", streaming=True)\r\n----> 5 sample = next(iter(dataset[\"train\"]))\r\n 6 print(sample[\"text\"])\r\n 7 sample[\"image\"]\r\n\r\nFile [~/miniconda3/envs/book/lib/python3.10/site-packages/datasets/iterable_dataset.py:1353](https://file+.vscode-resource.vscode-cdn.net/home/osanseviero/Desktop/workspace/genai/nbs/~/miniconda3/envs/book/lib/python3.10/site-packages/datasets/iterable_dataset.py:1353), in IterableDataset.__iter__(self)\r\n 1350 yield formatter.format_row(pa_table)\r\n 1351 return\r\n-> 1353 for key, example in ex_iterable:\r\n 1354 if self.features:\r\n 1355 # `IterableDataset` automatically fills missing columns with None.\r\n 1356 # This is done with `_apply_feature_types_on_example`.\r\n 1357 example = _apply_feature_types_on_example(\r\n 1358 example, self.features, token_per_repo_id=self._token_per_repo_id\r\n 1359 )\r\n\r\nFile [~/miniconda3/envs/book/lib/python3.10/site-packages/datasets/iterable_dataset.py:255](https://file+.vscode-resource.vscode-cdn.net/home/osanseviero/Desktop/workspace/genai/nbs/~/miniconda3/envs/book/lib/python3.10/site-packages/datasets/iterable_dataset.py:255), in ArrowExamplesIterable.__iter__(self)\r\n 253 def __iter__(self):\r\n 254 formatter = PythonFormatter()\r\n--> 255 for key, pa_table in self.generate_tables_fn(**self.kwargs):\r\n 256 for pa_subtable in pa_table.to_reader(max_chunksize=config.ARROW_READER_BATCH_SIZE_IN_DATASET_ITER):\r\n...\r\n-> 1130 return self._sslobj.read(len, buffer)\r\n 1131 else:\r\n 1132 return self._sslobj.read(len)\r\n```",
"@osanseviero I assume the `self._sslobj.read(len, buffer)` line comes from the built-in `ssl` module, so this probably has something to do with your network. Please open a new issue with the full stack trace in case you haven't resolved this yet.",
"Thank you reporting this and sharing the solution, I ran into this as well!",
"Ran into same issue after upgrading to pytorch-2.0. Disabling KMP_AFFINITY as mentioned above worked for me. Thanks!\r\n"
] | ### Describe the bug
I am using Amazon Sagemaker notebook (Amazon Linux 2) with python 3.10 based Conda environment.
I have a dataset in parquet format locally. When I try to iterate over it, the loader is stuck forever. Note that the same code is working for python 3.6 based conda environment seamlessly. What should be my next steps here?
### Steps to reproduce the bug
```
train_dataset = load_dataset(
"parquet", data_files = {'train': tr_data_path + '*.parquet'},
split = 'train',
collate_fn = streaming_data_collate_fn,
streaming = True
).with_format('torch')
train_dataloader = DataLoader(train_dataset, batch_size = 2, num_workers = 0)
t = time.time()
iter_ = 0
for batch in train_dataloader:
iter_ += 1
if iter_ == 1000:
break
print (time.time() - t)
```
### Expected behavior
The snippet should work normally and load the next batch of data.
### Environment info
datasets: '2.14.0'
pyarrow: '12.0.0'
torch: '2.0.0'
Python: 3.10.10 | packaged by conda-forge | (main, Mar 24 2023, 20:08:06) [GCC 11.3.0]
!uname -r
5.10.178-162.673.amzn2.x86_64 | 6,079 |
https://github.com/huggingface/datasets/issues/6078 | resume_download with streaming=True | [
"Currently, it's not possible to efficiently resume streaming after an error. Eventually, we plan to support this for Parquet (see https://github.com/huggingface/datasets/issues/5380). ",
"Ok thank you for your answer",
"I'm closing this as a duplicate of #5380"
] | ### Describe the bug
I used:
```
dataset = load_dataset(
"oscar-corpus/OSCAR-2201",
token=True,
language="fr",
streaming=True,
split="train"
)
```
Unfortunately, the server had a problem during the training process. I saved the step my training stopped at.
But how can I resume download from step 1_000_´000 without re-streaming all the first 1 million docs of the dataset?
`download_config=DownloadConfig(resume_download=True)` seems to not work with streaming=True.
### Steps to reproduce the bug
```
from datasets import load_dataset, DownloadConfig
dataset = load_dataset(
"oscar-corpus/OSCAR-2201",
token=True,
language="fr",
streaming=True, # optional
split="train",
download_config=DownloadConfig(resume_download=True)
)
# interupt the run and try to relaunch it => this restart from scratch
```
### Expected behavior
I would expect a parameter to start streaming from a given index in the dataset.
### Environment info
- `datasets` version: 2.14.0
- Platform: Linux-5.19.0-45-generic-x86_64-with-glibc2.29
- Python version: 3.8.10
- Huggingface_hub version: 0.15.1
- PyArrow version: 12.0.1
- Pandas version: 2.0.0 | 6,078 |
https://github.com/huggingface/datasets/issues/6077 | Mapping gets stuck at 99% | [
"The `MAX_MAP_BATCH_SIZE = 1_000_000_000` hack is bad as it loads the entire dataset into RAM when performing `.map`. Instead, it's best to use `.iter(batch_size)` to iterate over the data batches and compute `mean` for each column. (`stddev` can be computed in another pass).\r\n\r\nAlso, these arrays are big, so it makes sense to reduce `batch_size`/`writer_batch_size` to avoid RAM issues and slow IO.",
"Hi @mariosasko !\r\n\r\nI agree, it's an ugly hack, but it was convenient since the resulting `mean_std` could be cached by the library. For my large dataset (which doesn't fit in RAM), I'm actually using something similar to what you suggested. I got rid of the first mapping in the above scripts and replaced it with an iterator, but the issue with the second mapping still persists.",
"Have you tried to reduce `batch_size`/`writer_batch_size` in the 2nd `.map`? Also, can you interrupt the process when it gets stuck and share the error stack trace?",
"I think `batch_size/writer_batch_size` is already at its lowest in the 2nd `.map` since `batched=False` implies `batch_size=1` and `len(ds) = 1000 = writer_batch_size`.\r\n\r\nHere is also a bunch of stack traces when I interrupted the process:\r\n\r\n<details>\r\n <summary>stack trace 1</summary>\r\n\r\n```python\r\n(pyg)[d623204@rosetta-bigviz01 stage-laurent-f]$ python src/random_scripts/uses_random_data.py \r\nFound cached dataset random_data (/local_scratch/lfainsin/.cache/huggingface/datasets/random_data/default/0.0.0/444e214e1d0e6298cfd3f2368323ec37073dc1439f618e19395b1f421c69b066)\r\nApplying mean/std: 97%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ | 967/1000 [00:01<00:00, 534.87 examples/s]Traceback (most recent call last): \r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 179, in __arrow_array__\r\n storage = to_pyarrow_listarray(data, pa_type)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 1466, in to_pyarrow_listarray\r\n return pa.array(data, pa_type.storage_dtype)\r\n File \"pyarrow/array.pxi\", line 320, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 39, in pyarrow.lib._sequence_to_array\r\n File \"pyarrow/error.pxi\", line 144, in pyarrow.lib.pyarrow_internal_check_status\r\n File \"pyarrow/error.pxi\", line 123, in pyarrow.lib.check_status\r\npyarrow.lib.ArrowTypeError: Could not convert tensor([[-1.0273, -0.8037, -0.6860],\r\n [-0.5034, -1.2685, -0.0558],\r\n [-1.0908, -1.1820, -0.3178],\r\n ...,\r\n [-0.8171, 0.1781, -0.5903],\r\n [ 0.4370, 1.9305, 0.5899],\r\n [-0.1426, 0.9053, -1.7559]]) with type Tensor: was not a sequence or recognized null for conversion to list type\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3449, in _map_single\r\n writer.write(example)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 490, in write\r\n self.write_examples_on_file()\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 448, in write_examples_on_file\r\n self.write_batch(batch_examples=batch_examples)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 553, in write_batch\r\n arrays.append(pa.array(typed_sequence))\r\n File \"pyarrow/array.pxi\", line 236, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 110, in pyarrow.lib._handle_arrow_array_protocol\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 223, in __arrow_array__\r\n return pa.array(cast_to_python_objects(data, only_1d_for_numpy=True))\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 446, in cast_to_python_objects\r\n return _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 407, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 408, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 319, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 320, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 263, in _cast_to_python_objects\r\n def _cast_to_python_objects(obj: Any, only_1d_for_numpy: bool, optimize_list_casting: bool) -> Tuple[Any, bool]:\r\nKeyboardInterrupt\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 179, in __arrow_array__\r\n storage = to_pyarrow_listarray(data, pa_type)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 1466, in to_pyarrow_listarray\r\n return pa.array(data, pa_type.storage_dtype)\r\n File \"pyarrow/array.pxi\", line 320, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 39, in pyarrow.lib._sequence_to_array\r\n File \"pyarrow/error.pxi\", line 144, in pyarrow.lib.pyarrow_internal_check_status\r\n File \"pyarrow/error.pxi\", line 123, in pyarrow.lib.check_status\r\npyarrow.lib.ArrowTypeError: Could not convert tensor([[-1.0273, -0.8037, -0.6860],\r\n [-0.5034, -1.2685, -0.0558],\r\n [-1.0908, -1.1820, -0.3178],\r\n ...,\r\n [-0.8171, 0.1781, -0.5903],\r\n [ 0.4370, 1.9305, 0.5899],\r\n [-0.1426, 0.9053, -1.7559]]) with type Tensor: was not a sequence or recognized null for conversion to list type\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/gpfs_new/data/users/lfainsin/stage-laurent-f/src/random_scripts/uses_random_data.py\", line 62, in <module>\r\n ds_normalized = ds.map(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 580, in wrapper\r\n out: Union[\"Dataset\", \"DatasetDict\"] = func(self, *args, **kwargs)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 545, in wrapper\r\n out: Union[\"Dataset\", \"DatasetDict\"] = func(self, *args, **kwargs)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3087, in map\r\n for rank, done, content in Dataset._map_single(**dataset_kwargs):\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3492, in _map_single\r\n writer.finalize()\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 584, in finalize\r\n self.write_examples_on_file()\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 448, in write_examples_on_file\r\n self.write_batch(batch_examples=batch_examples)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 553, in write_batch\r\n arrays.append(pa.array(typed_sequence))\r\n File \"pyarrow/array.pxi\", line 236, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 110, in pyarrow.lib._handle_arrow_array_protocol\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 223, in __arrow_array__\r\n return pa.array(cast_to_python_objects(data, only_1d_for_numpy=True))\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 446, in cast_to_python_objects\r\n return _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 407, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 408, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 319, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 319, in <listcomp>\r\n [\r\nKeyboardInterrupt\r\n```\r\n\r\n</details>\r\n\r\n<details>\r\n <summary>stack trace 2</summary>\r\n\r\n```python\r\n(pyg)[d623204@rosetta-bigviz01 stage-laurent-f]$ python src/random_scripts/uses_random_data.py \r\nFound cached dataset random_data (/local_scratch/lfainsin/.cache/huggingface/datasets/random_data/default/0.0.0/444e214e1d0e6298cfd3f2368323ec37073dc1439f618e19395b1f421c69b066)\r\nApplying mean/std: 99%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▏ | 988/1000 [00:20<00:00, 526.19 examples/s]Applying mean/std: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊| 999/1000 [00:21<00:00, 9.66 examples/s]Traceback (most recent call last): \r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 179, in __arrow_array__\r\n storage = to_pyarrow_listarray(data, pa_type)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 1466, in to_pyarrow_listarray\r\n return pa.array(data, pa_type.storage_dtype)\r\n File \"pyarrow/array.pxi\", line 320, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 39, in pyarrow.lib._sequence_to_array\r\n File \"pyarrow/error.pxi\", line 144, in pyarrow.lib.pyarrow_internal_check_status\r\n File \"pyarrow/error.pxi\", line 123, in pyarrow.lib.check_status\r\npyarrow.lib.ArrowTypeError: Could not convert tensor([[-1.0273, -0.8037, -0.6860],\r\n [-0.5034, -1.2685, -0.0558],\r\n [-1.0908, -1.1820, -0.3178],\r\n ...,\r\n [-0.8171, 0.1781, -0.5903],\r\n [ 0.4370, 1.9305, 0.5899],\r\n [-0.1426, 0.9053, -1.7559]]) with type Tensor: was not a sequence or recognized null for conversion to list type\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3449, in _map_single\r\n writer.write(example)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 490, in write\r\n self.write_examples_on_file()\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 448, in write_examples_on_file\r\n self.write_batch(batch_examples=batch_examples)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 553, in write_batch\r\n arrays.append(pa.array(typed_sequence))\r\n File \"pyarrow/array.pxi\", line 236, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 110, in pyarrow.lib._handle_arrow_array_protocol\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 223, in __arrow_array__\r\n return pa.array(cast_to_python_objects(data, only_1d_for_numpy=True))\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 446, in cast_to_python_objects\r\n return _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 407, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 408, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 319, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 320, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 263, in _cast_to_python_objects\r\n def _cast_to_python_objects(obj: Any, only_1d_for_numpy: bool, optimize_list_casting: bool) -> Tuple[Any, bool]:\r\nKeyboardInterrupt\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 179, in __arrow_array__\r\n storage = to_pyarrow_listarray(data, pa_type)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 1466, in to_pyarrow_listarray\r\n return pa.array(data, pa_type.storage_dtype)\r\n File \"pyarrow/array.pxi\", line 320, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 39, in pyarrow.lib._sequence_to_array\r\n File \"pyarrow/error.pxi\", line 144, in pyarrow.lib.pyarrow_internal_check_status\r\n File \"pyarrow/error.pxi\", line 123, in pyarrow.lib.check_status\r\npyarrow.lib.ArrowTypeError: Could not convert tensor([[-1.0273, -0.8037, -0.6860],\r\n [-0.5034, -1.2685, -0.0558],\r\n [-1.0908, -1.1820, -0.3178],\r\n ...,\r\n [-0.8171, 0.1781, -0.5903],\r\n [ 0.4370, 1.9305, 0.5899],\r\n [-0.1426, 0.9053, -1.7559]]) with type Tensor: was not a sequence or recognized null for conversion to list type\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/gpfs_new/data/users/lfainsin/stage-laurent-f/src/random_scripts/uses_random_data.py\", line 62, in <module>\r\n ds_normalized = ds.map(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 580, in wrapper\r\n out: Union[\"Dataset\", \"DatasetDict\"] = func(self, *args, **kwargs)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 545, in wrapper\r\n out: Union[\"Dataset\", \"DatasetDict\"] = func(self, *args, **kwargs)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3087, in map\r\n for rank, done, content in Dataset._map_single(**dataset_kwargs):\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3492, in _map_single\r\n writer.finalize()\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 584, in finalize\r\n self.write_examples_on_file()\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 448, in write_examples_on_file\r\n self.write_batch(batch_examples=batch_examples)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 553, in write_batch\r\n arrays.append(pa.array(typed_sequence))\r\n File \"pyarrow/array.pxi\", line 236, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 110, in pyarrow.lib._handle_arrow_array_protocol\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 223, in __arrow_array__\r\n return pa.array(cast_to_python_objects(data, only_1d_for_numpy=True))\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 446, in cast_to_python_objects\r\n return _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 407, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 408, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 319, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 320, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 291, in _cast_to_python_objects\r\n if config.JAX_AVAILABLE and \"jax\" in sys.modules:\r\nKeyboardInterrupt\r\n```\r\n\r\n</details>\r\n\r\n<details>\r\n <summary>stack trace 3</summary>\r\n\r\n```python\r\n(pyg)[d623204@rosetta-bigviz01 stage-laurent-f]$ python src/random_scripts/uses_random_data.py \r\nFound cached dataset random_data (/local_scratch/lfainsin/.cache/huggingface/datasets/random_data/default/0.0.0/444e214e1d0e6298cfd3f2368323ec37073dc1439f618e19395b1f421c69b066)\r\nApplying mean/std: 99%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▎ | 989/1000 [00:01<00:00, 504.80 examples/s]Traceback (most recent call last): \r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 179, in __arrow_array__\r\n storage = to_pyarrow_listarray(data, pa_type)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 1466, in to_pyarrow_listarray\r\n return pa.array(data, pa_type.storage_dtype)\r\n File \"pyarrow/array.pxi\", line 320, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 39, in pyarrow.lib._sequence_to_array\r\n File \"pyarrow/error.pxi\", line 144, in pyarrow.lib.pyarrow_internal_check_status\r\n File \"pyarrow/error.pxi\", line 123, in pyarrow.lib.check_status\r\npyarrow.lib.ArrowTypeError: Could not convert tensor([[-1.0273, -0.8037, -0.6860],\r\n [-0.5034, -1.2685, -0.0558],\r\n [-1.0908, -1.1820, -0.3178],\r\n ...,\r\n [-0.8171, 0.1781, -0.5903],\r\n [ 0.4370, 1.9305, 0.5899],\r\n [-0.1426, 0.9053, -1.7559]]) with type Tensor: was not a sequence or recognized null for conversion to list type\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3449, in _map_single\r\n writer.write(example)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 490, in write\r\n self.write_examples_on_file()\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 448, in write_examples_on_file\r\n self.write_batch(batch_examples=batch_examples)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 553, in write_batch\r\n arrays.append(pa.array(typed_sequence))\r\n File \"pyarrow/array.pxi\", line 236, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 110, in pyarrow.lib._handle_arrow_array_protocol\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 223, in __arrow_array__\r\n return pa.array(cast_to_python_objects(data, only_1d_for_numpy=True))\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 446, in cast_to_python_objects\r\n return _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 407, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 408, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 319, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 320, in <listcomp>\r\n _cast_to_python_objects(\r\nKeyboardInterrupt\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 179, in __arrow_array__\r\n storage = to_pyarrow_listarray(data, pa_type)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 1466, in to_pyarrow_listarray\r\n return pa.array(data, pa_type.storage_dtype)\r\n File \"pyarrow/array.pxi\", line 320, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 39, in pyarrow.lib._sequence_to_array\r\n File \"pyarrow/error.pxi\", line 144, in pyarrow.lib.pyarrow_internal_check_status\r\n File \"pyarrow/error.pxi\", line 123, in pyarrow.lib.check_status\r\npyarrow.lib.ArrowTypeError: Could not convert tensor([[-1.0273, -0.8037, -0.6860],\r\n [-0.5034, -1.2685, -0.0558],\r\n [-1.0908, -1.1820, -0.3178],\r\n ...,\r\n [-0.8171, 0.1781, -0.5903],\r\n [ 0.4370, 1.9305, 0.5899],\r\n [-0.1426, 0.9053, -1.7559]]) with type Tensor: was not a sequence or recognized null for conversion to list type\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/gpfs_new/data/users/lfainsin/stage-laurent-f/src/random_scripts/uses_random_data.py\", line 62, in <module>\r\n ds_normalized = ds.map(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 580, in wrapper\r\n out: Union[\"Dataset\", \"DatasetDict\"] = func(self, *args, **kwargs)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 545, in wrapper\r\n out: Union[\"Dataset\", \"DatasetDict\"] = func(self, *args, **kwargs)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3087, in map\r\n for rank, done, content in Dataset._map_single(**dataset_kwargs):\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_dataset.py\", line 3492, in _map_single\r\n writer.finalize()\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 584, in finalize\r\n self.write_examples_on_file()\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 448, in write_examples_on_file\r\n self.write_batch(batch_examples=batch_examples)\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 553, in write_batch\r\n arrays.append(pa.array(typed_sequence))\r\n File \"pyarrow/array.pxi\", line 236, in pyarrow.lib.array\r\n File \"pyarrow/array.pxi\", line 110, in pyarrow.lib._handle_arrow_array_protocol\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/arrow_writer.py\", line 223, in __arrow_array__\r\n return pa.array(cast_to_python_objects(data, only_1d_for_numpy=True))\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 446, in cast_to_python_objects\r\n return _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 407, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 408, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 319, in _cast_to_python_objects\r\n [\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 320, in <listcomp>\r\n _cast_to_python_objects(\r\n File \"/local_scratch/lfainsin/.conda/envs/pyg/lib/python3.10/site-packages/datasets/features/features.py\", line 298, in _cast_to_python_objects\r\n if obj.ndim == 0:\r\nKeyboardInterrupt\r\n```\r\n\r\n</details>\r\n",
"Same issue by following code:\r\n\r\n```python\r\nfrom datasets import load_dataset\r\nfrom torchvision.transforms import transforms\r\n\r\npath = \"~/dataset/diffusiondb50k\" # path maybe not necessary\r\ndataset = load_dataset(\"poloclub/diffusiondb\", \"2m_first_1k\", data_dir=path)\r\n\r\ntransform = transforms.Compose([transforms.ToTensor()])\r\ndataset = dataset.map(\r\n lambda x: {\r\n 'image': transform(x['image']),\r\n 'prompt': x['prompt'],\r\n 'width': x['width'],\r\n 'height': x['height'],\r\n }, \r\n # num_proc=4,\r\n)\r\ndataset\r\n```\r\n\r\nAnd the `dataset.map()` stucks at `Map: 99% 986/1000 [00:07<00:00, 145.72 examples/s]`.\r\n\r\nAlso, there is 1 process left in `htop` with 100% CPU usage. And if I add `num_proc=4,`, there will be 4 same processes left.\r\n\r\n### Environment Info\r\n\r\n- `datasets` version: 2.15.0\r\n- Python version: 3.12.2\r\n- Platform: Linux-6.8.0-36-generic-x86_64-with-glibc2.39",
"Hi @zmoki688, I've noticed since that it's pretty common for disk writes to lag behind the operations performed by the `map` operator (especially when the data is large and the operations are cheap). Since the progress bar doesn't seem to account for the writes, it speeds up to 99% but wait until all writes are done. At least that's what I think happens when monitoring my disks I/O (with `iotop` and the likes)"
] | ### Describe the bug
Hi !
I'm currently working with a large (~150GB) unnormalized dataset at work.
The dataset is available on a read-only filesystem internally, and I use a [loading script](https://huggingface.co/docs/datasets/dataset_script) to retreive it.
I want to normalize the features of the dataset, meaning I need to compute the mean and standard deviation metric for each feature of the entire dataset. I cannot load the entire dataset to RAM as it is too big, so following [this discussion on the huggingface discourse](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcopy-columns-in-a-dataset-and-compute-statistics-for-a-column%2F22157) I am using a [map operation](https://huggingface.co/docs/datasets/v2.14.0/en/package_reference/main_classes#datasets.Dataset.map) to first compute the metrics and a second map operation to apply them on the dataset.
The problem lies in the second mapping, as it gets stuck at ~99%. By checking what the process does (using `htop` and `strace`) it seems to be doing a lot of I/O operations, and I'm not sure why.
Obviously, I could always normalize the dataset externally and then load it using a loading script. However, since the internal dataset is updated fairly frequently, using the library to perform normalization automatically would make it much easier for me.
### Steps to reproduce the bug
I'm able to reproduce the problem using the following scripts:
```python
# random_data.py
import datasets
import torch
_VERSION = "1.0.0"
class RandomDataset(datasets.GeneratorBasedBuilder):
def _info(self):
return datasets.DatasetInfo(
version=_VERSION,
supervised_keys=None,
features=datasets.Features(
{
"positions": datasets.Array2D(
shape=(30000, 3),
dtype="float32",
),
"normals": datasets.Array2D(
shape=(30000, 3),
dtype="float32",
),
"features": datasets.Array2D(
shape=(30000, 6),
dtype="float32",
),
"scalars": datasets.Sequence(
feature=datasets.Value("float32"),
length=20,
),
},
),
)
def _split_generators(self, dl_manager):
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN, # type: ignore
gen_kwargs={"nb_samples": 1000},
),
datasets.SplitGenerator(
name=datasets.Split.TEST, # type: ignore
gen_kwargs={"nb_samples": 100},
),
]
def _generate_examples(self, nb_samples: int):
for idx in range(nb_samples):
yield idx, {
"positions": torch.randn(30000, 3),
"normals": torch.randn(30000, 3),
"features": torch.randn(30000, 6),
"scalars": torch.randn(20),
}
```
```python
# main.py
import datasets
import torch
def apply_mean_std(
dataset: datasets.Dataset,
means: dict[str, torch.Tensor],
stds: dict[str, torch.Tensor],
) -> dict[str, torch.Tensor]:
"""Normalize the dataset using the mean and standard deviation of each feature.
Args:
dataset (`Dataset`): A huggingface dataset.
mean (`dict[str, Tensor]`): A dictionary containing the mean of each feature.
std (`dict[str, Tensor]`): A dictionary containing the standard deviation of each feature.
Returns:
dict: A dictionary containing the normalized dataset.
"""
result = {}
for key in means.keys():
# extract data from dataset
data: torch.Tensor = dataset[key] # type: ignore
# extract mean and std from dict
mean = means[key] # type: ignore
std = stds[key] # type: ignore
# normalize data
normalized_data = (data - mean) / std
result[key] = normalized_data
return result
# get dataset
ds = datasets.load_dataset(
path="random_data.py",
split="train",
).with_format("torch")
# compute mean (along last axis)
means = {key: torch.zeros(ds[key][0].shape[-1]) for key in ds.column_names}
means_sq = {key: torch.zeros(ds[key][0].shape[-1]) for key in ds.column_names}
for batch in ds.iter(batch_size=8):
for key in ds.column_names:
data = batch[key]
batch_size = data.shape[0]
data = data.reshape(-1, data.shape[-1])
means[key] += data.mean(dim=0) / len(ds) * batch_size
means_sq[key] += (data**2).mean(dim=0) / len(ds) * batch_size
# compute std (along last axis)
stds = {key: torch.sqrt(means_sq[key] - means[key] ** 2) for key in ds.column_names}
# normalize each feature of the dataset
ds_normalized = ds.map(
desc="Applying mean/std", # type: ignore
function=apply_mean_std,
batched=False,
fn_kwargs={
"means": means,
"stds": stds,
},
)
```
### Expected behavior
Using the previous scripts, the `ds_normalized` mapping completes in ~5 minutes, but any subsequent use of `ds_normalized` is really really slow, for example reapplying `apply_mean_std` to `ds_normalized` takes forever. This is very strange, I'm sure I must be missing something, but I would still expect this to be faster.
### Environment info
- `datasets` version: 2.13.1
- Platform: Linux-3.10.0-1160.66.1.el7.x86_64-x86_64-with-glibc2.17
- Python version: 3.10.12
- Huggingface_hub version: 0.15.1
- PyArrow version: 12.0.0
- Pandas version: 2.0.2 | 6,077 |
https://github.com/huggingface/datasets/issues/6075 | Error loading music files using `load_dataset` | [
"This code behaves as expected on my local machine or in Colab. Which version of `soundfile` do you have installed? MP3 requires `soundfile>=0.12.1`.",
"I upgraded the `soundfile` and it's working now! \r\nThanks @mariosasko for the help!"
] | ### Describe the bug
I tried to load a music file using `datasets.load_dataset()` from the repository - https://huggingface.co/datasets/susnato/pop2piano_real_music_test
I got the following error -
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 2803, in __getitem__
return self._getitem(key)
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/arrow_dataset.py", line 2788, in _getitem
formatted_output = format_table(
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/formatting/formatting.py", line 629, in format_table
return formatter(pa_table, query_type=query_type)
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/formatting/formatting.py", line 398, in __call__
return self.format_column(pa_table)
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/formatting/formatting.py", line 442, in format_column
column = self.python_features_decoder.decode_column(column, pa_table.column_names[0])
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/formatting/formatting.py", line 218, in decode_column
return self.features.decode_column(column, column_name) if self.features else column
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/features/features.py", line 1924, in decode_column
[decode_nested_example(self[column_name], value) if value is not None else None for value in column]
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/features/features.py", line 1924, in <listcomp>
[decode_nested_example(self[column_name], value) if value is not None else None for value in column]
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/features/features.py", line 1325, in decode_nested_example
return schema.decode_example(obj, token_per_repo_id=token_per_repo_id)
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/datasets/features/audio.py", line 184, in decode_example
array, sampling_rate = sf.read(f)
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/soundfile.py", line 372, in read
with SoundFile(file, 'r', samplerate, channels,
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/soundfile.py", line 740, in __init__
self._file = self._open(file, mode_int, closefd)
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/soundfile.py", line 1264, in _open
_error_check(_snd.sf_error(file_ptr),
File "/home/susnato/anaconda3/envs/p2p/lib/python3.9/site-packages/soundfile.py", line 1455, in _error_check
raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
RuntimeError: Error opening <_io.BufferedReader name='/home/susnato/.cache/huggingface/datasets/downloads/d2b09cb974b967b13f91553297c40c0f02f3c0d4c8356350743598ff48d6f29e'>: Format not recognised.
```
### Steps to reproduce the bug
Code to reproduce the error -
```python
from datasets import load_dataset
ds = load_dataset("susnato/pop2piano_real_music_test", split="test")
print(ds[0])
```
### Expected behavior
I should be able to read the music file without any error.
### Environment info
- `datasets` version: 2.14.0
- Platform: Linux-5.19.0-50-generic-x86_64-with-glibc2.35
- Python version: 3.9.16
- Huggingface_hub version: 0.15.1
- PyArrow version: 11.0.0
- Pandas version: 1.5.3
| 6,075 |
https://github.com/huggingface/datasets/issues/6073 | version2.3.2 load_dataset()data_files can't include .xxxx in path | [
"Version 2.3.2 is over one year old, so please use the latest release (2.14.0) to get the expected behavior. Version 2.3.2 does not contain some fixes we made to fix resolving hidden files/directories (starting with a dot)."
] | ### Describe the bug
First, I cd workdir.
Then, I just use load_dataset("json", data_file={"train":"/a/b/c/.d/train/train.json", "test":"/a/b/c/.d/train/test.json"})
that couldn't work and
<FileNotFoundError: Unable to find
'/a/b/c/.d/train/train.jsonl' at
/a/b/c/.d/>
And I debug, it is fine in version2.1.2
So there maybe a bug in path join.
Here is the whole bug report:
/x/datasets/loa │
│ d.py:1656 in load_dataset │
│ │
│ 1653 │ ignore_verifications = ignore_verifications or save_infos │
│ 1654 │ │
│ 1655 │ # Create a dataset builder │
│ ❱ 1656 │ builder_instance = load_dataset_builder( │
│ 1657 │ │ path=path, │
│ 1658 │ │ name=name, │
│ 1659 │ │ data_dir=data_dir, │
│ │
│ x/datasets/loa │
│ d.py:1439 in load_dataset_builder │
│ │
│ 1436 │ if use_auth_token is not None: │
│ 1437 │ │ download_config = download_config.copy() if download_config e │
│ 1438 │ │ download_config.use_auth_token = use_auth_token │
│ ❱ 1439 │ dataset_module = dataset_module_factory( │
│ 1440 │ │ path, │
│ 1441 │ │ revision=revision, │
│ 1442 │ │ download_config=download_config, │
│ │
│ x/datasets/loa │
│ d.py:1097 in dataset_module_factory │
│ │
│ 1094 │ │
│ 1095 │ # Try packaged │
│ 1096 │ if path in _PACKAGED_DATASETS_MODULES: │
│ ❱ 1097 │ │ return PackagedDatasetModuleFactory( │
│ 1098 │ │ │ path, │
│ 1099 │ │ │ data_dir=data_dir, │
│ 1100 │ │ │ data_files=data_files, │
│ │
│x/datasets/loa │
│ d.py:743 in get_module │
│ │
│ 740 │ │ │ if self.data_dir is not None │
│ 741 │ │ │ else get_patterns_locally(str(Path().resolve())) │
│ 742 │ │ ) │
│ ❱ 743 │ │ data_files = DataFilesDict.from_local_or_remote( │
│ 744 │ │ │ patterns, │
│ 745 │ │ │ use_auth_token=self.download_config.use_auth_token, │
│ 746 │ │ │ base_path=str(Path(self.data_dir).resolve()) if self.data │
│ │
│ x/datasets/dat │
│ a_files.py:590 in from_local_or_remote │
│ │
│ 587 │ │ out = cls() │
│ 588 │ │ for key, patterns_for_key in patterns.items(): │
│ 589 │ │ │ out[key] = ( │
│ ❱ 590 │ │ │ │ DataFilesList.from_local_or_remote( │
│ 591 │ │ │ │ │ patterns_for_key, │
│ 592 │ │ │ │ │ base_path=base_path, │
│ 593 │ │ │ │ │ allowed_extensions=allowed_extensions, │
│ │
│ /x/datasets/dat │
│ a_files.py:558 in from_local_or_remote │
│ │
│ 555 │ │ use_auth_token: Optional[Union[bool, str]] = None, │
│ 556 │ ) -> "DataFilesList": │
│ 557 │ │ base_path = base_path if base_path is not None else str(Path() │
│ ❱ 558 │ │ data_files = resolve_patterns_locally_or_by_urls(base_path, pa │
│ 559 │ │ origin_metadata = _get_origin_metadata_locally_or_by_urls(data │
│ 560 │ │ return cls(data_files, origin_metadata) │
│ 561 │
│ │
│ /x/datasets/dat │
│ a_files.py:195 in resolve_patterns_locally_or_by_urls │
│ │
│ 192 │ │ if is_remote_url(pattern): │
│ 193 │ │ │ data_files.append(Url(pattern)) │
│ 194 │ │ else: │
│ ❱ 195 │ │ │ for path in _resolve_single_pattern_locally(base_path, pat │
│ 196 │ │ │ │ data_files.append(path) │
│ 197 │ │
│ 198 │ if not data_files: │
│ │
│ /x/datasets/dat │
│ a_files.py:145 in _resolve_single_pattern_locally │
│ │
│ 142 │ │ error_msg = f"Unable to find '{pattern}' at {Path(base_path).r │
│ 143 │ │ if allowed_extensions is not None: │
│ 144 │ │ │ error_msg += f" with any supported extension {list(allowed │
│ ❱ 145 │ │ raise FileNotFoundError(error_msg) │
│ 146 │ return sorted(out) │
│ 147
### Steps to reproduce the bug
1. Version=2.3.2
2. In shell, cd workdir.(cd /a/b/c/.d/)
3. load_dataset("json", data_file={"train":"/a/b/c/.d/train/train.json", "test":"/a/b/c/.d/train/test.json"})
### Expected behavior
fix it please~
### Environment info
2.3.2 | 6,073 |
https://github.com/huggingface/datasets/issues/6071 | storage_options provided to load_dataset not fully piping through since datasets 2.14.0 | [
"Hi ! Thanks for reporting, I opened a PR to fix this\r\n\r\nWhat filesystem are you using ?",
"Hi @lhoestq ! Thank you so much 🙌 \r\n\r\nIt's a bit of a custom setup, but in practice I am using a [pyarrow.fs.S3FileSystem](https://arrow.apache.org/docs/python/generated/pyarrow.fs.S3FileSystem.html) (wrapped in a `fsspec.implementations.arrow.ArrowFSWrapper` [to make it](https://arrow.apache.org/docs/python/filesystems.html#using-arrow-filesystems-with-fsspec) `fsspec` compatible). I also register it as an entrypoint with `fsspec` so that it's the one that gets automatically resolved when looking for filesystems for the `s3` protocol\r\n\r\nIn my case the `storage_option` that seemed not getting piped through was the filesystem's `endpoint_override` that I use in some tests to point at a mock S3 bucket"
] | ### Describe the bug
Since the latest release of `datasets` (`2.14.0`), custom filesystem `storage_options` passed to `load_dataset()` do not seem to propagate through all the way - leading to problems if loading data files that need those options to be set.
I think this is because of the new `_prepare_path_and_storage_options()` (https://github.com/huggingface/datasets/pull/6028), which returns the right `storage_options` to use given a path and a `DownloadConfig` - but which might not be taking into account the extra `storage_options` explicitly provided e.g. through `load_dataset()`
### Steps to reproduce the bug
```python
import fsspec
import pandas as pd
import datasets
# Generate mock parquet file
data_files = "demo.parquet"
pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}).to_parquet(data_files)
_storage_options = {"x": 1, "y": 2}
fs = fsspec.filesystem("file", **_storage_options)
dataset = datasets.load_dataset(
"parquet",
data_files=data_files,
storage_options=fs.storage_options
)
```
Looking at the `storage_options` resolved here:
https://github.com/huggingface/datasets/blob/b0177910b32712f28d147879395e511207e39958/src/datasets/data_files.py#L331
they end up being `{}`, instead of propagating through the `storage_options` that were provided to `load_dataset` (`fs.storage_options`). As these then get used for the filesystem operation a few lines below
https://github.com/huggingface/datasets/blob/b0177910b32712f28d147879395e511207e39958/src/datasets/data_files.py#L339
the call will fail if the user-provided `storage_options` were needed.
---
A temporary workaround that seemed to work locally to bypass the problem was to bundle a duplicate of the `storage_options` into the `download_config`, so that they make their way all the way to `_prepare_path_and_storage_options()` and get extracted correctly:
```python
dataset = datasets.load_dataset(
"parquet",
data_files=data_files,
storage_options=fs.storage_options,
download_config=datasets.DownloadConfig(storage_options={fs.protocol: fs.storage_options}),
)
```
### Expected behavior
`storage_options` provided to `load_dataset` take effect in all backend filesystem operations.
### Environment info
datasets==2.14.0 | 6,071 |
https://github.com/huggingface/datasets/issues/6069 | KeyError: dataset has no key "image" | [
"You can list the dataset's columns with `ds.column_names` before `.map` to check whether the dataset has an `image` column. If it doesn't, then this is a bug. Otherwise, please paste the line with the `.map` call.\r\n\r\n\r\n",
"This is the piece of code I am running:\r\n```\r\ndata_transforms = utils.get_data_augmentation(args)\r\nimage_dataset = utils.load_image_dataset(args.dataset)\r\n\r\ndef resize(examples):\r\n examples[\"pixel_values\"] = [image.convert(\"RGB\").resize((300, 300)) for image in examples[\"image\"]]\r\n return examples\r\n\r\ndef preprocess_train(example_batch):\r\n print(f\"Example batch: \\n{example_batch}\")\r\n example_batch[\"pixel_values\"] = [\r\n data_transforms[\"train\"](image.convert(\"RGB\")) for image in example_batch[\"pixel_values\"]\r\n ]\r\n return example_batch\r\n\r\ndef preprocess_val(example_batch):\r\n example_batch[\"pixel_values\"] = [\r\n data_transforms[\"val\"](image.convert(\"RGB\")) for image in example_batch[\"pixel_values\"]\r\n ]\r\n return example_batch\r\n\r\nimage_dataset = image_dataset.map(resize, remove_columns=[\"image\"], batched=True)\r\n\r\nimage_dataset[\"train\"].set_transform(preprocess_train)\r\nimage_dataset[\"validation\"].set_transform(preprocess_val)\r\n```\r\n\r\nWhen I print ds.column_names I get the following\r\n`{'train': ['image', 'label'], 'validation': ['image', 'label'], 'test': ['image', 'label']}`\r\n\r\nThe `print(f\"Example batch: \\n{example_batch}\")` in the `preprocess_train` function outputs only labels without images:\r\n```\r\nExample batch: \r\n{'label': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]}\r\n```\r\n\r\nThe weird part of it all is that a sample code runs in a jupyter lab notebook without any bugs, but when I run my scripts from the terminal I get the bug. The same code.",
"The `remove_columns=[\"image\"]` argument in the `.map` call removes the `image` column from the output, so drop this argument to preserve it.",
"The problem is not with the removal of the image key. The bug is why only the labels are sent to be process, instead of all the featues or dictionary keys.\r\n\r\nP.S. I just dropped the removal argument as you've suggested, but that didn't solve the problem, because only the labels are being sent to be processed",
"All the `image_dataset.column_names` after the `map` call should also be present in `preprocess_train `/`preprocess_val` unless (input) `columns` in `set_transform` are specified.\r\n\r\nIf that's not the case, we need a full reproducer (not snippets) with the environment info.",
"I have resolved the error after including a collate function as indicated in the Quick Start session of the Datasets docs.:\r\n\r\nHere is what I did:\r\n```\r\ndata_transforms = utils.get_data_augmentation(args)\r\nimage_dataset = utils.load_image_dataset(args.dataset)\r\n\r\ndef preprocess_train(example_batch):\r\n example_batch[\"pixel_values\"] = [\r\n data_transforms[\"train\"](image.convert(\"RGB\")) for image in example_batch[\"image\"]\r\n ]\r\n return example_batch\r\n\r\ndef preprocess_val(example_batch):\r\n example_batch[\"pixel_values\"] = [\r\n data_transforms[\"val\"](image.convert(\"RGB\")) for image in example_batch[\"image\"]\r\n ]\r\n return example_batch\r\n\r\ndef collate_fn(examples):\r\n images = []\r\n labels = []\r\n for example in examples:\r\n images.append((example[\"pixel_values\"]))\r\n labels.append(example[\"label\"])\r\n\r\n pixel_values = torch.stack(images)\r\n labels = torch.tensor(labels)\r\n return {\"pixel_values\": pixel_values, \"label\": labels}\r\n\r\ntrain_dataset = image_dataset[\"train\"].with_transform(preprocess_train)\r\nval_dataset = image_dataset[\"validation\"].with_transform(preprocess_val)\r\n\r\nimage_datasets = {\r\n \"train\": train_dataset,\r\n \"val\": val_dataset\r\n}\r\n\r\nsamplers = {\r\n \"train\": data.RandomSampler(train_dataset),\r\n \"val\": data.SequentialSampler(val_dataset),\r\n}\r\n\r\ndataloaders = {\r\n x: data.DataLoader(\r\n image_datasets[x],\r\n collate_fn=collate_fn,\r\n batch_size=batch_size,\r\n sampler=samplers[x],\r\n num_workers=args.num_workers,\r\n worker_init_fn=utils.set_seed_for_worker,\r\n generator=g,\r\n pin_memory=True,\r\n )\r\n for x in [\"train\", \"val\"]\r\n}\r\n\r\ntrain_loader, val_loader = dataloaders[\"train\"], dataloaders[\"val\"]\r\n```\r\nEverything runs fine without any bug now. "
] | ### Describe the bug
I've loaded a local image dataset with:
`ds = laod_dataset("imagefolder", data_dir=path-to-data)`
And defined a transform to process the data, following the Datasets docs.
However, I get a keyError error, indicating there's no "image" key in my dataset. When I printed out the example_batch sent to the transformation function, it shows only the labels are being sent to the function.
For some reason, the images are not in the example batches.
### Steps to reproduce the bug
I'm using the latest stable version of datasets
### Expected behavior
I expect the example_batches to contain both images and labels
### Environment info
I'm using the latest stable version of datasets | 6,069 |
https://github.com/huggingface/datasets/issues/6066 | AttributeError: '_tqdm_cls' object has no attribute '_lock' | [
"Hi ! I opened https://github.com/huggingface/datasets/pull/6067 to add the missing `_lock`\r\n\r\nWe'll do a patch release soon, but feel free to install `datasets` from source in the meantime",
"I have tested the latest main, it does not work.\r\n\r\nI add more logs to reproduce this issue, it looks like a multi threading bug:\r\n\r\n```python\r\n@contextmanager\r\ndef ensure_lock(tqdm_class, lock_name=\"\"):\r\n \"\"\"get (create if necessary) and then restore `tqdm_class`'s lock\"\"\"\r\n import os\r\n import threading\r\n print(os.getpid(), threading.get_ident(), \"ensure_lock\", tqdm_class, lock_name)\r\n old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock\r\n lock = old_lock or tqdm_class.get_lock() # maybe create a new lock\r\n lock = getattr(lock, lock_name, lock) # maybe subtype\r\n tqdm_class.set_lock(lock)\r\n print(os.getpid(), threading.get_ident(), \"set_lock\")\r\n yield lock\r\n if old_lock is None:\r\n print(os.getpid(), threading.get_ident(), \"del tqdm_class\")\r\n del tqdm_class._lock\r\n else:\r\n tqdm_class.set_lock(old_lock)\r\n```\r\noutput\r\n```\r\n64943 8424758784 ensure_lock <datasets.utils.logging._tqdm_cls object at 0x2aa7fb250> \r\n64943 8424758784 set_lock\r\n64943 8424758784 del tqdm_class\r\n64943 8424758784 ensure_lock <datasets.utils.logging._tqdm_cls object at 0x2aa7fb250> \r\n64943 8424758784 set_lock\r\n64943 8424758784 del tqdm_class\r\n64943 11638370304 ensure_lock <datasets.utils.logging._tqdm_cls object at 0x2aa7fb250> \r\n64943 11638370304 set_lock\r\n64943 11568967680 ensure_lock <datasets.utils.logging._tqdm_cls object at 0x2aa7fb250> \r\n64943 11568967680 set_lock\r\n64943 11638370304 del tqdm_class\r\n64943 11638370304 ensure_lock <datasets.utils.logging._tqdm_cls object at 0x2aa7fb250> \r\n64943 11638370304 set_lock\r\n64943 11638370304 del tqdm_class\r\n64943 11568967680 del tqdm_class\r\n```\r\n\r\nThread `11638370304` del the _lock from tqdm_class first, then thread `11568967680` del _lock failed.",
"Maybe it is a bug of tqdm? I think simply use `try ... except AttributeError ...` wraps `del tqdm_class._lock` should work.",
"Yes it looks like a bug on their end indeed, do you want to open a PR on tqdm ?\r\n\r\nLet me see if I can find a workaround in the meantime",
"I opened https://github.com/huggingface/datasets/pull/6068 if you want to try it out",
"> I opened #6068 if you want to try it out\r\n\r\nThis fix works! Thanks.",
"Awesome ! closing this then :)\r\nWe'll do a patch release today or tomorrow"
] | ### Describe the bug
```python
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/site-packages/datasets/load.py", line 1034, in get_module
data_files = DataFilesDict.from_patterns(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/site-packages/datasets/data_files.py", line 671, in from_patterns
DataFilesList.from_patterns(
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/site-packages/datasets/data_files.py", line 586, in from_patterns
origin_metadata = _get_origin_metadata(data_files, download_config=download_config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/site-packages/datasets/data_files.py", line 502, in _get_origin_metadata
return thread_map(
^^^^^^^^^^^
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/site-packages/tqdm/contrib/concurrent.py", line 70, in thread_map
return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/site-packages/tqdm/contrib/concurrent.py", line 48, in _executor_map
with ensure_lock(tqdm_class, lock_name=lock_name) as lk:
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/contextlib.py", line 144, in __exit__
next(self.gen)
File "/Users/codingl2k1/.pyenv/versions/3.11.4/lib/python3.11/site-packages/tqdm/contrib/concurrent.py", line 25, in ensure_lock
del tqdm_class._lock
^^^^^^^^^^^^^^^^
AttributeError: '_tqdm_cls' object has no attribute '_lock'
```
### Steps to reproduce the bug
Happens ocasionally.
### Expected behavior
I added a print in tqdm `ensure_lock()`, got a `ensure_lock <datasets.utils.logging._tqdm_cls object at 0x16dddead0> ` print.
According to the code in https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/concurrent.py#L24
```python
@contextmanager
def ensure_lock(tqdm_class, lock_name=""):
"""get (create if necessary) and then restore `tqdm_class`'s lock"""
print("ensure_lock", tqdm_class, lock_name)
old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock
lock = old_lock or tqdm_class.get_lock() # maybe create a new lock
lock = getattr(lock, lock_name, lock) # maybe subtype
tqdm_class.set_lock(lock)
yield lock
if old_lock is None:
del tqdm_class._lock # <-- It tries to del the `_lock` attribute from tqdm_class.
else:
tqdm_class.set_lock(old_lock)
```
But, huggingface datasets `datasets.utils.logging._tqdm_cls` does not have the field `_lock`: https://github.com/huggingface/datasets/blob/main/src/datasets/utils/logging.py#L205
```python
class _tqdm_cls:
def __call__(self, *args, disable=False, **kwargs):
if _tqdm_active and not disable:
return tqdm_lib.tqdm(*args, **kwargs)
else:
return EmptyTqdm(*args, **kwargs)
def set_lock(self, *args, **kwargs):
self._lock = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*args, **kwargs)
def get_lock(self):
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
```
### Environment info
Python 3.11.4
tqdm '4.65.0'
datasets master | 6,066 |
https://github.com/huggingface/datasets/issues/6060 | Dataset.map() execute twice when in PyTorch DDP mode | [
"Sorry for asking a duplicate question about `num_proc`, I searched the forum and find the solution.\r\n\r\nBut I still can't make the trick with `torch.distributed.barrier()` to only map at the main process work. The [post on forum]( /static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fslow-processing-with-map-when-using-deepspeed-or-fairscale%2F7229%2F7) didn't help.",
"If it does the `map` twice then it means the hash of your map function is not some same between your two processes.\r\n\r\nCan you make sure your map functions have the same hash in different processes ?\r\n\r\n```python\r\nfrom datasets.fingerprint import Hasher\r\n\r\nprint(Hasher.hash(lambda x: cut_reorder_keys(x, num_stations_list=args.num_stations_list, is_pad=True, is_train=True)))\r\nprint(Hasher.hash(lambda x: random_shift(x, shift_range=(-160, 0), feature_scale=16)))\r\n```\r\n\r\nYou can also set the fingerprint used to reload the resulting dataset by passing `new_finegrprint=` in `map`, see https://huggingface.co/docs/datasets/v2.13.1/en/about_cache#the-cache. This will force the different processes to use the same fingerprint used to locate the resulting dataset in the cache.",
"Thanks for help! I find the fingerprint between processes don't have same hash:\r\n```\r\nRank 0: Gpu 0 cut_reorder_keys fingerprint c7f47f40e9a67657\r\nRank 0: Gpu 0 random_shift fingerprint 240a0ce79831e7d4\r\n\r\nRank 1: Gpu 1 cut_reorder_keys fingerprint 20edd3d9cf284001\r\nRank 1: Gpu 1 random_shift fingerprint 819f7c1c18e7733f\r\n```\r\nBut my functions only process the example one by one and don't need rank or other arguments. After all it can work in the test for dataset and dataloader.\r\nI'll try to set `new_fingerprint` to see if it works and figure out the reason of different hash.",
"I finally figure it out. The fingerprint of the function will change if other key-value pairs change in `args` even the `args.num_stations_list` is not changed.\r\n\r\n```python\r\nlambda x: cut_reorder_keys(x, num_stations_list=args.num_stations_list, is_pad=True, is_train=True)\r\n```\r\n\r\nMy `args` contains the key `rank` which refers the rank of its GPU, so the fingerprints change among the GPUs.\r\nI use `partial` in `functools` to generate a partial function that fixs the argument `num_stations_list=args.num_stations_list`, and the fingerprint of this partial function keeps among the GPUs. Finally I can reuse the mapped cache."
] | ### Describe the bug
I use `torchrun --standalone --nproc_per_node=2 train.py` to start training. And write the code following the [docs](https://huggingface.co/docs/datasets/process#distributed-usage). The trick about using `torch.distributed.barrier()` to only execute map at the main process doesn't always work. When I am training model, it will map twice. When I am running a test for dataset and dataloader (just print the batches), it can work. Their code about loading dataset are same.
And on another server with 30 CPU cores, I use 2 GPUs and it can't work neither.
I have tried to use `rank` and `local_rank` to check, they all didn't make sense.
### Steps to reproduce the bug
use `torchrun --standalone --nproc_per_node=2 train.py` or `torchrun --standalone train.py` to run
This is my code:
```python
if args.distributed and world_size > 1:
if args.local_rank > 0:
print(f"Rank {args.rank}: Gpu {args.gpu} waiting for main process to perform the mapping", force=True)
torch.distributed.barrier()
print("Mapping dataset")
dataset = dataset.map(lambda x: cut_reorder_keys(x, num_stations_list=args.num_stations_list, is_pad=True, is_train=True), num_proc=8, desc="cut_reorder_keys")
dataset = dataset.map(lambda x: random_shift(x, shift_range=(-160, 0), feature_scale=16), num_proc=8, desc="random_shift")
dataset_test = dataset_test.map(lambda x: cut_reorder_keys(x, num_stations_list=args.num_stations_list, is_pad=True, is_train=False), num_proc=8, desc="cut_reorder_keys")
if args.local_rank == 0:
print("Mapping finished, loading results from main process")
torch.distributed.barrier()
```
### Expected behavior
Only the main process will execute `map`, while the sub process will load cache from disk.
### Environment info
server with 64 CPU cores (AMD Ryzen Threadripper PRO 5995WX 64-Cores) and 2 RTX 4090
- `python==3.9.16`
- `datasets==2.13.1`
- `torch==2.0.1+cu117`
- `22.04.1-Ubuntu`
server with 30 CPU cores (Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz) and 2 RTX 4090
- `python==3.9.0`
- `datasets==2.13.1`
- `torch==2.0.1+cu117`
- `Ubuntu 20.04` | 6,060 |
https://github.com/huggingface/datasets/issues/6059 | Provide ability to load label mappings from file | [
"I would like this also as I have been working with a dataset with hierarchical classes. In fact, I encountered this very issue when trying to define the dataset with a script. I couldn't find a work around and reverted to hard coding the class names in the readme yaml.\r\n\r\n@david-waterworth do you envision also being able to define the hierarchical structure of the classes?",
"@danielduckworth yes I did need to do that (but I ended up ditching datasets as it looks like this is a \"wont fix\"). ",
"@david-waterworth Hmm, that's a shame. What are you using now? Also, I’m curious to know about the work you’re doing that involves hierarchical classes, if you don’t mind sharing."
] | ### Feature request
My task is classification of a dataset containing a large label set that includes a hierarchy. Even ignoring the hierarchy I'm not able to find an example using `datasets` where the label names aren't hard-coded. This works find for classification of a handful of labels but ideally there would be a way of loading the name/id mappings required for `datasets.features.ClassLabel` from a file.
It is possible to pass a file to ClassLabel but I cannot see an easy way of using this with `GeneratorBasedBuilder` since `self._info` is called before the `dl_manager` is constructed so even if my dataset contains say `label_mappings.json` there's no way of loading it in order to construct the `datasets.DatasetInfo`
I can see other uses to accessing the `download_manager` from `self._info` - i.e. if the files contain a schema (i.e. `arrow` or `parquet` files) the `datasets.DatasetInfo` could be inferred.
The workaround that was suggested in the forum is to generate a `.py` file from the `label_mappings.json` and import it.
```
class TestDatasetBuilder(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version("1.0.0")
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"text": datasets.Value("string"),
"label": datasets.features.ClassLabel(names=["label_1", "label_2"]),
}
),
task_templates=[TextClassification(text_column="text", label_column="label")],
)
def _split_generators(self, dl_manager):
train_path = dl_manager.download_and_extract(_TRAIN_DOWNLOAD_URL)
test_path = dl_manager.download_and_extract(_TEST_DOWNLOAD_URL)
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": train_path}),
datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": test_path}),
]
def _generate_examples(self, filepath):
"""Generate AG News examples."""
with open(filepath, encoding="utf-8") as csv_file:
csv_reader = csv.DictReader(csv_file)
for id_, row in enumerate(csv_reader):
yield id_, row
```
### Motivation
Allow `datasets.DatasetInfo` to be generated based on the contents of the dataset.
### Your contribution
I'm willing to work on a PR with guidence. | 6,059 |
https://github.com/huggingface/datasets/issues/6058 | laion-coco download error | [
"This can also mean one of the files was not downloaded correctly.\r\n\r\nWe 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.\r\n\r\n(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)\r\n"
] | ### 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 | 6,058 |
https://github.com/huggingface/datasets/issues/6057 | Why is the speed difference of gen example so big? | [
"Hi!\r\n\r\nIt's hard to explain this behavior without more information. Can you profile the slower version with the following code\r\n```python\r\nimport cProfile, pstats\r\nfrom datasets import load_dataset\r\n\r\nwith cProfile.Profile() as profiler:\r\n ds = load_dataset(...)\r\n\r\nstats = pstats.Stats(profiler).sort_stats(\"cumtime\")\r\nstats.print_stats()\r\n```\r\nand 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.
| 6,057 |
https://github.com/huggingface/datasets/issues/6055 | Fix host URL in The Pile datasets | [] | ### Describe the bug
In #3627 and #5543, you tried to fix the host URL in The Pile datasets. But both URLs are not working now:
`HTTPError: 404 Client Error: Not Found for URL: https://the-eye.eu/public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst`
And
`ConnectTimeout: HTTPSConnectionPool(host='mystic.the-eye.eu', port=443): Max retries exceeded with url: /public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst (Caused by ConnectTimeoutError(, 'Connection to mystic.the-eye.eu timed out. (connect timeout=10.0)'))`
### Steps to reproduce the bug
```
from datasets import load_dataset
# This takes a few minutes to run, so go grab a tea or coffee while you wait :)
data_files = "https://mystic.the-eye.eu/public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst"
pubmed_dataset = load_dataset("json", data_files=data_files, split="train")
pubmed_dataset
```
Result:
`ConnectTimeout: HTTPSConnectionPool(host='mystic.the-eye.eu', port=443): Max retries exceeded with url: /public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst (Caused by ConnectTimeoutError(, 'Connection to mystic.the-eye.eu timed out. (connect timeout=10.0)'))`
And
```
from datasets import load_dataset
# This takes a few minutes to run, so go grab a tea or coffee while you wait :)
data_files = "https://the-eye.eu/public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst"
pubmed_dataset = load_dataset("json", data_files=data_files, split="train")
pubmed_dataset
```
Result:
`HTTPError: 404 Client Error: Not Found for URL: https://the-eye.eu/public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst`
### Expected behavior
Downloading as normal.
### Environment info
Environment info
`datasets` version: 2.9.0
Platform: Windows
Python version: 3.9.13
| 6,055 |
https://github.com/huggingface/datasets/issues/6054 | Multi-processed `Dataset.map` slows down a lot when `import torch` | [
"A duplicate of https://github.com/huggingface/datasets/issues/5929"
] | ### Describe the bug
When using `Dataset.map` with `num_proc > 1`, the speed slows down much if I add `import torch` to the start of the script even though I don't use it.
I'm not sure if it's `torch` only or if any other package that is "large" will also cause the same result.
BTW, `import lightning` also slows it down.
Below are the progress bars of `Dataset.map`, the only difference between them is with or without `import torch`, but the speed varies by 6-7 times.
- without `import torch` ![image](https://github.com/huggingface/datasets/assets/47121592/0233055a-ced4-424a-9f0f-32a2afd802c2)
- with `import torch` ![image](https://github.com/huggingface/datasets/assets/47121592/463eafb7-b81e-4eb9-91ca-fd7fe20f3d59)
### Steps to reproduce the bug
Below is the code I used, but I don't think the dataset and the mapping function have much to do with the phenomenon.
```python3
from datasets import load_from_disk, disable_caching
from transformers import AutoTokenizer
# import torch
# import lightning
def rearrange_datapoints(
batch,
tokenizer,
sequence_length,
):
datapoints = []
input_ids = []
for x in batch['input_ids']:
input_ids += x
while len(input_ids) >= sequence_length:
datapoint = input_ids[:sequence_length]
datapoints.append(datapoint)
input_ids[:sequence_length] = []
if input_ids:
paddings = [-1] * (sequence_length - len(input_ids))
datapoint = paddings + input_ids if tokenizer.padding_side == 'left' else input_ids + paddings
datapoints.append(datapoint)
batch['input_ids'] = datapoints
return batch
if __name__ == '__main__':
disable_caching()
tokenizer = AutoTokenizer.from_pretrained('...', use_fast=False)
dataset = load_from_disk('...')
dataset = dataset.map(
rearrange_datapoints,
fn_kwargs=dict(
tokenizer=tokenizer,
sequence_length=2048,
),
batched=True,
num_proc=8,
)
```
### Expected behavior
The multi-processed `Dataset.map` function speed between with and without `import torch` should be the same.
### Environment info
- `datasets` version: 2.13.1
- Platform: Linux-3.10.0-1127.el7.x86_64-x86_64-with-glibc2.31
- Python version: 3.10.11
- Huggingface_hub version: 0.14.1
- PyArrow version: 12.0.0
- Pandas version: 2.0.1 | 6,054 |
https://github.com/huggingface/datasets/issues/6053 | Change package name from "datasets" to something less generic | [
"This would break a lot of existing code, so we can't really do this."
] | ### Feature request
I'm repeatedly finding myself in situations where I want to have a package called `datasets.py` or `evaluate.py` in my code and can't because those names are being taken up by Huggingface packages. While I can understand how (even from the user's perspective) it's aesthetically pleasing to have nice terse library names, ultimately a library hogging simple names like this is something I find short-sighted, impractical and at my most irritable, frankly rude.
My preference would be a pattern like what you get with all the other big libraries like numpy or pandas:
```
import huggingface as hf
# hf.transformers, hf.datasets, hf.evaluate
```
or things like
```
import huggingface.transformers as tf
# tf.load_model(), etc
```
If this isn't possible for some technical reason, at least just call the packages something like `hf_transformers` and so on.
I realize this is a very big change that's probably been discussed internally already, but I'm making this issue and sister issues on each huggingface project just to start the conversation and begin tracking community feeling on the matter, since I suspect I'm not the only one who feels like this.
Sorry if this has been requested already on this issue tracker, I couldn't find anything looking for terms like "package name".
Sister issues:
- [transformers](https://github.com/huggingface/transformers/issues/24934)
- **datasets**
- [evaluate](https://github.com/huggingface/evaluate/issues/476)
### Motivation
Not taking up package names the user is likely to want to use.
### Your contribution
No - more a matter of internal discussion among core library authors. | 6,053 |
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:\r\n```python\r\nfrom datasets.table import embed_table_storage\r\n# load_dataset(...)\r\nformat = dataset.format\r\ndataset = dataset.with_format(\"arrow\")\r\ndataset = dataset.map(embed_table_storage, batched=True)\r\ndataset = dataset.with_format(**format)\r\n# push_to_hub(...)\r\n```\r\n\r\n(In Datasets 3.0, these external bytes will be written to an Arrow file when generating a dataset to avoid this \"embed\" step)",
"Hi, thanks, this solution saves some time.\r\nBut can't we avoid embedding all external image files bytes with each push, skipping the images that have already been pushed into the repo?\r\n\r\nEdit: 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
| 6,051 |
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 | 6,048 |
https://github.com/huggingface/datasets/issues/6046 | Support proxy and user-agent in fsspec calls | [
"hii @lhoestq can you assign this issue to me?\r\n",
"You can reply \"#self-assign\" to this issue to automatically get assigned to it :)\r\nLet me know if you have any questions or if I can help",
"#2289 ",
"Actually i am quite new to figure it out how everything goes and done \r\n\r\n> You can reply \"#self-assign\" to this issue to automatically get assigned to it :)\r\n> Let me know if you have any questions or if I can help\r\n\r\nwhen i wrote #self-assign it automatically got converted to some number is it correct or i have done it some wrong way, I am quite new to open source thus wanna try to learn and explore it",
"#2289 #self-assign ",
"Ah yea github tries to replace the #self-assign with an issue link. I guess you can try to copy-paste instead to see if it works\r\n\r\nAnyway let me assign you manually",
"thanks a lot @lhoestq ! though i have a very lil idea of the issue, i am new. as i said before, but gonna try my best shot to do it.\r\ncan you please suggest some tips or anything from your side, how basically we approach it will be really helpfull.\r\nWill try my best!",
"The HfFileSystem from the `huggingface_hub` package can already read the HTTP_PROXY and HTTPS_PROXY environment variables. So the remaining thing missing is the `user_agent` that the user may include in a `DownloadConfig` object. The user agent can be used for regular http calls but also calls to the HfFileSystem.\r\n\r\n- for http, the `user_agent` isn't passed from `DownloadConfig` to `get_datasets_user_agent` in `_prepare_single_hop_path_and_storage_options` in `streaming_download_manager.py` so we need to include it\r\n- for HfFileSystem I think it requires a PR in https://github.com/huggingface/huggingface_hub to include it in the `HfFileSystem.__init__`"
] | Since we switched to the new HfFileSystem we no longer apply user's proxy and user-agent.
Using the HTTP_PROXY and HTTPS_PROXY environment variables works though since we use aiohttp to call the HF Hub.
This can be implemented in `_prepare_single_hop_path_and_storage_options`.
Though ideally the `HfFileSystem` could support passing at least the proxies | 6,046 |
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`\".\r\n\r\nCan you please elaborate on it?\r\n\r\nThanks!",
"Hi @aryanxk02 ! Sure, what I actually meant is that when passing a path-like `path_or_buf` here\r\n\r\nhttps://github.com/huggingface/datasets/blob/14f6edd9222e577dccb962ed5338b79b73502fa5/src/datasets/arrow_dataset.py#L4708-L4714 \r\n\r\nit gets converted to a file object behind the scenes here\r\n\r\nhttps://github.com/huggingface/datasets/blob/14f6edd9222e577dccb962ed5338b79b73502fa5/src/datasets/io/csv.py#L92-L94\r\n\r\nand 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`\r\n\r\nhttps://github.com/huggingface/datasets/blob/14f6edd9222e577dccb962ed5338b79b73502fa5/src/datasets/io/csv.py#L107-L109",
"@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`
| 6,043 |
https://github.com/huggingface/datasets/issues/6039 | Loading column subset from parquet file produces error since version 2.13 | [] | ### Describe the bug
`load_dataset` allows loading a subset of columns from a parquet file with the `columns` argument. Since version 2.13, this produces the following error:
```
Traceback (most recent call last):
File "/usr/lib/python3.10/site-packages/datasets/builder.py", line 1879, in _prepare_split_single
for _, table in generator:
File "/usr/lib/python3.10/site-packages/datasets/packaged_modules/parquet/parquet.py", line 68, in _generate_tables
raise ValueError(
ValueError: Tried to load parquet data with columns '['sepal_length']' with mismatching features '{'sepal_length': Value(dtype='float64', id=None), 'sepal_width': Value(dtype='float64', id=None), 'petal_length': Value(dtype='float64', id=None), 'petal_width': Value(dtype='float64', id=None), 'species': Value(dtype='string', id=None)}'
```
This seems to occur because `datasets` is checking whether the columns in the schema exactly match the provided list of columns, instead of whether they are a subset.
### Steps to reproduce the bug
```python
# Prepare some sample data
import pandas as pd
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
iris.to_parquet('iris.parquet')
# ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
print(iris.columns)
# Load data with datasets
from datasets import load_dataset
# Load full parquet file
dataset = load_dataset('parquet', data_files='iris.parquet')
# Load column subset; throws error for datasets>=2.13
dataset = load_dataset('parquet', data_files='iris.parquet', columns=['sepal_length'])
```
### Expected behavior
No error should be thrown and the given column subset should be loaded.
### Environment info
- `datasets` version: 2.13.0
- Platform: Linux-5.15.0-76-generic-x86_64-with-glibc2.35
- Python version: 3.10.9
- Huggingface_hub version: 0.16.4
- PyArrow version: 12.0.1
- Pandas version: 1.5.3 | 6,039 |
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):\r\n```python\r\nfrom datasets import load_dataset\r\nds = load_dataset(\"json\", data_files={\"train\": os.path.join(data_dir[\"train\"]), \"dev\": os.path.join(data_dir[\"dev\"])})\r\n```"
] | 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? | 6,038 |
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.\r\n\r\nInitially, 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)",
"Sorry I thought I'd selected the latest version."
] | ### 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 | 6,037 |
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.",
"Thanks - that works! However it doesn't resolve the original issue (but I am not sure if it is a WSL problem)",
"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. | 6,034 |
https://github.com/huggingface/datasets/issues/6033 | `map` function doesn't fully utilize `input_columns`. | [] | ### Describe the bug
I wanted to select only some columns of data.
And I thought that's why the argument `input_columns` exists.
What I expected is like this:
If there are ["a", "b", "c", "d"] columns, and if I set `input_columns=["a", "d"]`, the data will have only ["a", "d"] columns.
But it doesn't select columns.
It preserves existing columns.
The main cause is `update` function of `dictionary` type `transformed_batch`.
https://github.com/huggingface/datasets/blob/682d21e94ab1e64c11b583de39dc4c93f0101c5a/src/datasets/iterable_dataset.py#L687-L691
`transformed_batch` gets all the columns by `transformed_batch = dict(batch)`.
Even `function_args` selects `input_columns`, `update` preserves columns other than `input_columns`.
I think it should take a new dictionary with columns in `input_columns` like this:
```
# transformed_batch = dict(batch)
# transformed_batch.update(self.function(*function_args, **self.fn_kwargs)
# This is what I think correct.
transformed_batch = self.function(*function_args, **self.fn_kwargs)
```
Let me know how to use `input_columns`.
### Steps to reproduce the bug
Described all above.
### Expected behavior
Described all above.
### Environment info
datasets: 2.12
python: 3.8 | 6,033 |
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).\r\n\r\nWe plan to implement https://github.com/huggingface/datasets/issues/5080 and make this behavior more consistent eventually.",
"> this\r\n\r\nThanks. I will try `huggingface_hub.configure_http_backend` to change session's config.",
"@mariosasko are you saying if I do the following:\r\n\r\n```\r\ndef backend_factory() -> requests.Session:\r\n session = requests.Session()\r\n session.proxies = {\r\n \"https\": \"127.0.0.1:8887\",\r\n \"http\": \"127.0.0.1:8887\",\r\n }\r\n session.verify = \"/etc/ssl/certs/ca-certificates.crt\"\r\n return session\r\n\r\n# Set it as the default session factory\r\nconfigure_http_backend(backend_factory=backend_factory)\r\n```\r\n\r\nwhich works nicely with transformer library:\r\n\r\n```\r\ndef download_gpt_2_model():\r\n tokenizer = GPT2Tokenizer.from_pretrained(\r\n \"gpt2\", force_download=True, resume_download=False\r\n )\r\n text = \"Replace me by any text you'd like.\"\r\n encoded_input = tokenizer(text, return_tensors=\"pt\")\r\n print(encoded_input)\r\n\r\n model = GPT2Model.from_pretrained(\r\n \"gpt2\", force_download=True, resume_download=False\r\n )\r\n output = model(**encoded_input)\r\n```\r\n\r\nshould work for datasets library as well ?\r\n\r\nIn my case if I just do:\r\n\r\n```\r\ndef download_sts12_sts_dataset():\r\n dataset = load_dataset(\r\n \"mteb/sts12-sts\",\r\n download_mode=\"force_redownload\",\r\n verification_mode=\"basic_checks\",\r\n revision=\"main\",\r\n )\r\n\r\n```\r\nI am getting:\r\n`ConnectionError: Couldn't reach https://huggingface.co/datasets/mteb/sts12-sts/resolve/main/dataset_infos.json (ConnectTimeout(MaxRetryError(\"HTTPSConnectionPool(host='huggingface.co', port=443): Max retries exceeded with url: /datasets/mteb/sts12-sts/resolve/main/dataset_infos.json (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x7f429e87a3a0>, 'Connection to huggingface.co timed out. (connect timeout=100)'))\")))`\r\n\r\nwhich is typical when the proxy server is not defined. Looks like what is set in configure_http_backend(backend_factory=backend_factory) is ignore.\r\n\r\nIf I use env variable instead, it is working \r\n```\r\ndef download_sts12_sts_dataset():\r\n\r\n os.environ[\"https_proxy\"] = \"127.0.0.1:8887\"\r\n os.environ[\"http_proxy\"] = \"127.0.0.1:8887\"\r\n os.environ[\"REQUESTS_CA_BUNDLE\"] = \"/etc/ssl/certs/ca-certificates.crt\"\r\n\r\n dataset = load_dataset(\r\n \"mteb/sts12-sts\",\r\n download_mode=\"force_redownload\",\r\n verification_mode=\"basic_checks\",\r\n revision=\"main\",\r\n )\r\n```\r\n\r\nShould I add something ?\r\n\r\nI am using `huggingface_hub 0.15.1`, `datasets 2.13.0`, `transformers 4.30.2`",
"`huggingface_hub.configure_http_backend` works for `transformers` because they only use the `huggingface_hub` lib for downloads. Our download logic is a bit more complex (e.g., we also support downloading non-Hub files), so we are not aligned with them yet. In the meantime, it's best to use the env vars.",
"@mariosasko I fully understand that the logic for dataset is different. I see 2 issues with the current implementation of the env variables:\r\n\r\n- having the same https_proxy/http_prox/no_proxy env variables for all tools is not good in some case. For example I have 2 differents proxy server. In 2019 we had discussion with the Tensorflow teams and they recommended to do the following: TFDS_HTTP_PROXY, TFDS_HTTPS_PROXY ...\r\n- with recent version of requests, it is not possible to deactivate TLS interception (verify=false) by using env variable. This is useful to debug things and in some case TLS is not working and you need to ignore verifying the SSL certificate (probably not recommended) \r\n\r\nOne of the best way is to able to pass our requests.Session() directly\r\n```\r\nimport openai\r\nsession = requests.Session()\r\nsession.cert = CERT\r\nsession.verify = False\r\nopenai.requestssession = session\r\n```\r\n\r\nMy 2 cents in this discussion"
] | ### 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 | 6,032 |
https://github.com/huggingface/datasets/issues/6031 | Argument type for map function changes when using `input_columns` for `IterableDataset` | [
"Yes, this is intended."
] | ### Describe the bug
I wrote `tokenize(examples)` function as an argument for `map` function for `IterableDataset`.
It process dictionary type `examples` as a parameter.
It is used in `train_dataset = train_dataset.map(tokenize, batched=True)`
No error is raised.
And then, I found some unnecessary keys and values in `examples` so I added `input_columns` argument to `map` function to select keys and values.
It gives me an error saying
```
TypeError: tokenize() takes 1 positional argument but 3 were given.
```
The code below matters.
https://github.com/huggingface/datasets/blob/406b2212263c0d33f267e35b917f410ff6b3bc00/src/datasets/iterable_dataset.py#L687
For example, `inputs = {"a":1, "b":2, "c":3}`.
If `self.input_coluns` is `None`,
`inputs` is a dictionary type variable and `function_args` becomes a `list` of a single `dict` variable.
`function_args` becomes `[{"a":1, "b":2, "c":3}]`
Otherwise, lets say `self.input_columns = ["a", "c"]`
`[inputs[col] for col in self.input_columns]` results in `[1, 3]`.
I think it should be `[{"a":1, "c":3}]`.
I want to ask if the resulting format is intended.
Maybe I can modify `tokenize()` to have 2 parameters in this case instead of having 1 dictionary.
But this is confusing to me.
Or it should be fixed as `[{col:inputs[col] for col in self.input_columns}]`
### Steps to reproduce the bug
Run `map` function of `IterableDataset` with `input_columns` argument.
### Expected behavior
`function_args` looks better to have same format.
I think it should be `[{"a":1, "c":3}]`.
### Environment info
dataset version: 2.12
python: 3.8 | 6,031 |
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.\r\n` "
] | ### 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. | 6,025 |
https://github.com/huggingface/datasets/issues/6022 | Batch map raises TypeError: '>=' not supported between instances of 'NoneType' and 'int' | [
"Thanks for reporting! I've opened a PR with a fix."
] | ### Describe the bug
When mapping some datasets with `batched=True`, datasets may raise an exeception:
```python
Traceback (most recent call last):
File "/Users/codingl2k1/Work/datasets/venv/lib/python3.11/site-packages/multiprocess/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/utils/py_utils.py", line 1328, in _write_generator_to_queue
for i, result in enumerate(func(**kwargs)):
File "/Users/codingl2k1/Work/datasets/src/datasets/arrow_dataset.py", line 3483, in _map_single
writer.write_batch(batch)
File "/Users/codingl2k1/Work/datasets/src/datasets/arrow_writer.py", line 549, in write_batch
array = cast_array_to_feature(col_values, col_type) if col_type is not None else col_values
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/table.py", line 1831, in wrapper
return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/table.py", line 1831, in <listcomp>
return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/table.py", line 2063, in cast_array_to_feature
return feature.cast_storage(array)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/features/features.py", line 1098, in cast_storage
if min_max["max"] >= self.num_classes:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: '>=' not supported between instances of 'NoneType' and 'int'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/codingl2k1/Work/datasets/t1.py", line 33, in <module>
ds = ds.map(transforms, num_proc=14, batched=True, batch_size=5)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/dataset_dict.py", line 850, in map
{
File "/Users/codingl2k1/Work/datasets/src/datasets/dataset_dict.py", line 851, in <dictcomp>
k: dataset.map(
^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/arrow_dataset.py", line 577, in wrapper
out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/arrow_dataset.py", line 542, in wrapper
out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/src/datasets/arrow_dataset.py", line 3179, in map
for rank, done, content in iflatmap_unordered(
File "/Users/codingl2k1/Work/datasets/src/datasets/utils/py_utils.py", line 1368, in iflatmap_unordered
[async_result.get(timeout=0.05) for async_result in async_results]
File "/Users/codingl2k1/Work/datasets/src/datasets/utils/py_utils.py", line 1368, in <listcomp>
[async_result.get(timeout=0.05) for async_result in async_results]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/codingl2k1/Work/datasets/venv/lib/python3.11/site-packages/multiprocess/pool.py", line 774, in get
raise self._value
TypeError: '>=' not supported between instances of 'NoneType' and 'int'
```
### Steps to reproduce the bug
1. Checkout the latest main of datasets.
2. Run the code:
```python
from datasets import load_dataset
def transforms(examples):
# examples["pixel_values"] = [image.convert("RGB").resize((100, 100)) for image in examples["image"]]
return examples
ds = load_dataset("scene_parse_150")
ds = ds.map(transforms, num_proc=14, batched=True, batch_size=5)
print(ds)
```
### Expected behavior
map without exception.
### Environment info
Datasets: https://github.com/huggingface/datasets/commit/b8067c0262073891180869f700ebef5ac3dc5cce
Python: 3.11.4
System: Macos | 6,022 |
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): \r\n```python\r\nimport datasets\r\n\r\n...\r\n\r\nfeatures = dataset.features\r\nfeatures[\"output\"] = = [{\"test\": datasets.Value(\"int64\")}]\r\ntest2 = dataset.map(lambda row, idx: test_func(row, idx), with_indices=True, num_proc=32, features=features)\r\n```",
"I just encountered the same error in the same situation (multiprocessing with variable length outputs).\r\n\r\nThe funny (or dangerous?) thing is, that this error only showed up when testing with a small test dataset (16 examples, ValueError with `num_proc` >1) but the same code works fine for the full dataset (~70k examples).\r\n\r\n@mariosasko Any idea on how to do that with a nested feature with lists of variable lengths containing dicts?\r\n\r\nEDIT: Was able to narrow it down: >200 Examples: no error, <150 Examples: Error. \r\nNow idea what to make of this but pretty obvious that this is a bug....",
"This error also occurs while concatenating the datasets."
] | ### 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 | 6,020 |
https://github.com/huggingface/datasets/issues/6017 | Switch to huggingface_hub's HfFileSystem | [] | instead of the current datasets.filesystems.hffilesystem.HfFileSystem which can be slow in some cases
related to https://github.com/huggingface/datasets/issues/5846 and https://github.com/huggingface/datasets/pull/5919 | 6,017 |