Backed by Apache Arrow on disk — that’s why loads are zero-copy and memory-mapped. Dataset
has random access; IterableDataset (streaming mode) doesn’t. The Hub CLI
moved from huggingface-cli to hf in
huggingface_hub ≥ 0.24 — both still work, hf is the new one.
Install · envSetup
bash
# Core
pip install datasets # ≥ 3.0
# Optional extras — install what you need
pip install "datasets[audio]" # soundfile + librosa + torchcodec
pip install "datasets[vision]" # Pillow + image features
pip install "datasets[s3]" # s3fs for cloud-backed paths
# To upload to the Hub
pip install huggingface_hub
hf auth login # paste a token from huggingface.co/settings/tokens
# Optional speed-ups
pip install pyarrow # bundled, but pin if you need a version
Where things liveCommon imports
from datasets import load_dataset
The 90% entry point. Reads from Hub, files, or builders.
from datasets import Dataset, DatasetDict, IterableDataset, IterableDatasetDict
Core classes. DatasetDict = splits wrapper.
from datasets import Features, Value, ClassLabel, Sequence
Schema primitives.
from datasets import Audio, Image, Video
Media features — auto-decode on read.
from datasets import concatenate_datasets, interleave_datasets
Concat (stack) or interleave (mix) splits.
from datasets import load_from_disk
Reload a dataset saved with save_to_disk.
from huggingface_hub import login
Programmatic auth. Or just run hf auth login.
From Hub · from filesLoading
From the Hub
load_dataset("imdb")
Repo on hub. Returns a DatasetDict with all splits.
Load two heterogeneous sources, give them an explicit schema, dedupe, stratify-split into train/val/test, save locally and push to the Hub.
python
from datasets import load_dataset, DatasetDict, Features, ClassLabel, Value
# 1 · Load a CSV from disk and a JSONL from a URL — same call shape
local = load_dataset("csv", data_files="reviews.csv", split="train")
remote = load_dataset(
"json",
data_files="https://example.com/reviews.jsonl",
split="train",
)
# 2 · Concatenate and define an explicit schema
from datasets import concatenate_datasets
ds = concatenate_datasets([local, remote])
ds = ds.cast(Features({
"text": Value("string"),
"label": ClassLabel(names=["neg", "pos"]),
}))
# 3 · Clean, dedupe, split
ds = ds.filter(lambda x: x["text"] and x["text"].strip())
ds = ds.shuffle(seed=42)
# train / val / test = 80 / 10 / 10
train_test = ds.train_test_split(test_size=0.2, seed=42, stratify_by_column="label")
val_test = train_test["test"].train_test_split(test_size=0.5, seed=42)
final = DatasetDict({
"train": train_test["train"],
"validation": val_test["train"],
"test": val_test["test"],
})
# 4 · Save locally + push to the Hub
final.save_to_disk("./reviews_dataset")
final.push_to_hub("my-org/reviews", private=True)
Best practiceGood to know
Always pass batched=True to map() for tokenization.
A vectorized tokenizer call on 1000 rows is dramatically faster than 1000 individual calls. The function just receives a dict-of-lists instead of a dict.
Use slice syntax at load time, not after.split="train[:1%]" only downloads what you need; load_dataset(…)[:1%] downloads the full split first.
Streaming for terabyte-scale corpora; cached Dataset for everything else.
Streaming avoids disk pressure but loses random access and reproducibility. Most fine-tuning workflows want a cached Dataset.
Common trapsWatch out for
Streaming + .shuffle is approximate.
The buffer is a sliding window — rows far apart in the file never meet. For true random order, materialize first.
map() with num_proc > 1 requires picklable functions.
Closures over local state, tokenizers loaded outside the worker, and lambdas can all break multiprocessing silently. Define helpers at module scope.
Cache files survive across runs and silently feed stale results.
Change your transform and forget to bust the cache → you’re training on yesterday’s data. Pass load_from_cache_file=False when iterating.
What is the HuggingFace Datasets library used for?
The HuggingFace Datasets library provides a fast, memory-efficient way to load, process, and share datasets for machine learning. It uses Apache Arrow for zero-copy memory mapping, so you can process datasets larger than RAM without running out of memory.
How does load_dataset work?
load_dataset('dataset_name') downloads a dataset from the HuggingFace Hub and caches it locally as Arrow files. You can pass a split ('train', 'test', 'validation'), a data_files path, or a streaming=True flag. Local CSV, JSON, and Parquet files are also supported.
What is the difference between Dataset and IterableDataset?
Dataset is fully loaded into memory-mapped Arrow files and supports random access and fast slicing. IterableDataset (streaming mode) yields examples lazily without downloading the whole dataset, which is essential for very large datasets that do not fit on disk.
How do I push a dataset to the HuggingFace Hub?
Call ds.push_to_hub('your-org/dataset-name') after logging in with huggingface-cli login. You can push individual splits, set private=True, or pass a commit_message. The Hub stores the dataset as Parquet shards so others can stream it without a full download.
Does HuggingFace Datasets work with PyTorch and TensorFlow?
Yes. Call ds.with_format('torch') or ds.with_format('tensorflow') to get framework-native tensors. For PyTorch, with_format returns a dataset compatible with DataLoader. For TensorFlow, use to_tf_dataset() to get a tf.data.Dataset with configurable batch size and shuffle.