The naive version, and the fast one
# slow: one Python call per row
ds = ds.map(lambda r: {"n_chars": len(r["text"])})
# fast: one Python call per thousand rows
ds = ds.map(
lambda b: {"n_chars": [len(t) for t in b["text"]]},
batched=True, batch_size=1000,
)In batched mode the function receives a dictionary of input lists. All output lists in a batch must have the same length as one another. That output length can differ from the input length. Batching can reduce call overhead. Benchmark it with your own data and transformation.
Batching can also help fast tokenizers process several strings together. Compare results on your own data:
def tok_fn(batch):
return tok(batch["text"], truncation=True, max_length=512)
ds = ds.map(tok_fn, batched=True, remove_columns=["text"])remove_columns drops the original text after tokenization in this example. Compare the resulting cache sizes on your data before budgeting storage.
Parallelism across cores
ds = ds.map(fn, batched=True, num_proc=8)This forks processes, each mapping a shard, and then concatenates. Two cautions that cost people real time:
- Fast tokenizers already use threads. Combining
num_procwith them can oversubscribe the CPU and run slower. The library will warn aboutTOKENIZERS_PARALLELISM; set it tofalsewhen usingnum_proc, or use one or the other. - Anything holding a GPU does not fork well. For GPU work, use one process and a large batch, not eight processes fighting over one card.
A batch does not have to stay the same size
This is the feature people miss. A batched map may return more or fewer rows than it received, which makes it the tool for splitting and dropping:
def chunk(batch, size=800, overlap=100):
if not 0 <= overlap < size:
raise ValueError("Require 0 <= overlap < size")
out = {"chunk": [], "doc_id": []}
for doc_id, text in zip(batch["id"], batch["text"]):
for start in range(0, len(text), size - overlap):
end = min(start + size, len(text))
out["chunk"].append(text[start:end])
out["doc_id"].append(doc_id)
if end == len(text):
break
return out
chunks = docs.map(
chunk, batched=True,
remove_columns=docs.column_names,
)The output contains one source ID per chunk. An empty document produces zero chunks. The loop stops once a chunk reaches the end of its document. The number of chunks depends on the source lengths and the chunk settings. Here, remove_columns=docs.column_names drops the original columns, whose input lengths would otherwise conflict when the output row count changes. You can also return aligned replacements for any columns you keep.
filter, and doing it in one pass
ds = ds.filter(lambda b: [len(t) > 50 for t in b["text"]], batched=True, num_proc=4)Filtering reads everything, so chain your conditions into one predicate rather than calling filter four times. Four filters are four full passes.
set_transform: when you do not want a new file
map materialises a new Arrow file. When the transformation is cheap and varies per epoch (image augmentation, random cropping, dynamic masking) that is wasteful and wrong, because you want different randomness each time.
def augment(batch):
batch["pixel_values"] = [aug(img) for img in batch["image"]]
return batch
ds.set_transform(augment) # applied on access, nothing writtenRule: map for deterministic preprocessing you want cached, set_transform for anything random or cheap.
Making it reproducible
Every map that involves randomness needs a seed passed in, not read from global state, or your cache and your results diverge from each other. And keep the transformation code in a module rather than a notebook cell, because a notebook cell that was edited and re-run is not a record of what produced your data.
Sorting, grouping and joining
sort, class_encode_column and flatten_indices cover most reshaping. For a join by key, one option is to use a table library such as pandas, then convert the result back:
import pandas as pd
from datasets import Dataset
merged = Dataset.from_pandas(ds.to_pandas().merge(other_df, on="id"))This example loads both inputs into RAM. Check their size before running it. For larger Parquet inputs, the next lesson shows a DuckDB approach.
Do this now
Take one map you have written per row and rewrite it batched. Time both on 50,000 rows. The number you get is the tax you have been paying on every dataset you have ever processed one row at a time.
Check your understanding
A batched map takes four documents and returns six chunks. Its unchanged title column still has four values. What repairs the mismatch?
Pick the one you would defend. Your answer stays private.
Your place and first choices stay on this browser. Classroom credit is recorded separately.
Every lesson here is open. Your progress is recorded once you pass the Image Generation, in Practice exam.
Stuck on something?Ask Arjun, your AI tutor