jamesLeeeeeee/datasets-github-issues huggingface dataset:
resume_download with streaming=True
Author: NicolasMICAUX | Pull request: no | State: closed

### 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
No gzip encoding from github
Author: lhoestq | Pull request: yes | State: closed

Don't accept gzip encoding from github, otherwise some files are not streamable + seekable.

fix https://huggingface.co/datasets/code_x_glue_cc_code_to_code_trans/discussions/2#64c0e0c1a04a514ba6303e84

and making sure https://github.com/huggingface/datasets/issues/2918 works as well
Misc doc improvements
Author: mariosasko | Pull request: yes | State: closed

Removes the warning about requiring to write a dataset loading script to define multiple configurations, as the README YAML can be used instead (for simple cases). Also, deletes the section about using the `BatchSampler` in `torch<=1.12.1` to speed up loading, as `torch 1.12.1` is over a year old (and `torch 2.0` has been out for a while).
storage_options provided to load_dataset not fully piping through since datasets 2.14.0
Author: exs-avianello | Pull request: no | State: closed

### 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
KeyError: dataset has no key "image"
Author: etetteh | Pull request: no | State: closed

### 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
Add column type guessing from map return function
Author: piercefreeman | Pull request: yes | State: closed

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

### 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`
Provide ability to load label mappings from file
Author: david-waterworth | Pull request: no | State: open

### 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.
Why is the speed difference of gen example so big?
Author: pixeli99 | Pull request: no | State: closed

```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.
Implement proper checkpointing for dataset uploading with resume function that does not require remapping shards that have already been uploaded
Author: AntreasAntoniou | Pull request: yes | State: open

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

### 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
Multi-processed `Dataset.map` slows down a lot when `import torch`
Author: ShinoharaHare | Pull request: no | State: closed

### 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
Change package name from "datasets" to something less generic
Author: geajack | Pull request: no | State: closed

### 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.
Skipping shard in the remote repo and resume upload
Author: rs9000 | Pull request: no | State: closed

### 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
when i use datasets.load_dataset, i encounter the http connect error!
Author: yangy1992 | Pull request: no | State: closed

### 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
Support proxy and user-agent in fsspec calls
Author: lhoestq | Pull request: no | State: open

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