skip to content

Your Hugging Face Datasets map(batched=True) tokenization re-runs from scratch whenever the script starts: how does its cache decide reuse, and what breaks it?

level: middleimportance: must knowfreq 22%

answer

  1. a hash chain, not timestamps
  2. previous fingerprint plus transform hash
  3. cache-<fingerprint>.arrow beside the data
  4. unpicklable function gets a random hash
  5. unseeded split upstream changes everything

basics

~20 s

Dataset.map() names its output cache file after a fingerprint: a hash of the previous fingerprint, the function and its arguments. A function that cannot be hashed stably, an unseeded shuffle or split upstream, an in-memory dataset or disabled caching forces recomputation.

solid answer

~50 s

Every `Dataset` carries a **fingerprint**. `map` (and `filter`, `shuffle`, `train_test_split`) computes the next one by hashing the previous fingerprint, the function, which is serialised with dill, and the arguments, then looks for `cache-<fingerprint>.arrow` next to the dataset's Arrow files; if it exists and `load_from_cache_file` is on (the default while caching is enabled), the work is skipped. It re-runs when: the function cannot be pickled, so a **random hash** is used with a one-time warning; the function closes over an object whose bytes change between runs; an **unseeded** `shuffle` or `train_test_split` upstream took a random fingerprint; the dataset lives only in memory (`Dataset.from_dict`, `keep_in_memory=True`), so no cache file is written; or caching was disabled or the cache directory is wiped each run. Fix with a module-level function, `seed=`, a persistent `HF_DATASETS_CACHE`, or `save_to_disk` of the result.

code

python · 19 lines
python
from datasets import load_dataset
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("your-org/your-model")

def tokenize(batch):                 # module level: picklable, stable hash
    return tok(batch["text"], truncation=True, max_length=512)

ds = load_dataset("your-org/support-tickets", split="train")
splits = ds.train_test_split(test_size=0.05, seed=42)   # seeded split

train = splits["train"].map(
    tokenize,
    batched=True,                    # 1,000 rows per call by default
    num_proc=8,                      # eight worker processes
    remove_columns=["text"],
    desc="tokenize",
)
print(train.cache_files)             # Arrow files the next run reloads

go deeper

for a junior

Recall that map writes its output to a cache file and that batched=True passes lists of rows to your function.

for a middle

Explain the fingerprint chain: previous fingerprint plus hashes of the function and arguments, the cache file named after it, and load_from_cache_file.

for a senior

Diagnose a cache that never hits: the random-hash warning, unseeded shuffles or splits upstream, in-memory datasets, and ephemeral cache directories in containers.

for a principal

Decide whether preprocessing belongs in every training job or in a separate step that publishes a tokenized dataset, trading cache fragility for an extra artifact to manage.

## Why the cache exists In the Hugging Face **Datasets** library, `Dataset.map(fn, batched=True)` applies `fn` to batches of rows (1,000 per call by default, set with `batch_size`) and writes the result as a new **Arrow file**. Tokenizing millions of rows can take an hour, so the library tries hard not to do it twice: the next time the same transform is applied to the same data, it reloads the file instead. When that reuse silently fails, every script start pays the full cost, which is exactly the symptom in the question. ## How reuse is decided: the fingerprint chain A **fingerprint** is a short hash that stands for the current state of a dataset. 1. A freshly loaded dataset gets an initial fingerprint from a hash of its Arrow files. 2. Each transform computes a new fingerprint from **the previous fingerprint**, a hash of **the function** and a hash of **the arguments** (`batch_size`, `remove_columns`, `fn_kwargs` and so on, leaving out ones still at their defaults). 3. The function is hashed by serialising it with **dill**, which recursively includes every variable it uses. Change a tokenizer setting the function closes over, and the hash changes, as it should. 4. The output is written to `cache-<fingerprint>.arrow` in the same directory as the dataset's own Arrow files. 5. On the next run, if that file exists and `load_from_cache_file` is true (its default whenever caching is enabled), `map` loads it and skips the function. No timestamps or file modification times are involved; it is purely a chain of hashes. `filter`, `shuffle`, `select` and `train_test_split` take part in the same chain. `filter` and `shuffle` usually produce an **indices mapping** cache file rather than rewriting rows. ## What breaks the chain | Cause | What happens | Fix | |---|---|---| | Function or argument not picklable | a **random** fingerprint is used, with a warning printed once per session | define the function at module level and pass plain arguments | | Function captures something nondeterministic | the hash differs on every run | remove the varying object, or hash suspects with `datasets.fingerprint.Hasher` | | Unseeded `shuffle` or `train_test_split` upstream | a fingerprint is drawn from NumPy's random state, so this step and everything after it recompute, and the split itself changes | pass `seed=` | | Dataset held only in memory | `from_dict`, `from_pandas` or `keep_in_memory=True` give a dataset with no cache files, so results stay in RAM | save it with `save_to_disk` and reload it, or pass `cache_file_name=` | | Caching turned off or cache wiped | `disable_caching()` or `load_from_cache_file=False`, or a container whose cache directory is ephemeral | keep caching on and mount a persistent `HF_DATASETS_CACHE` | | You changed the transform | a new fingerprint, by design | nothing to fix | The random-fingerprint warning is the clearest clue. It says the transform "couldn't be hashed properly, a random hash was used instead", and it is shown only once per session, so it is easy to miss in a long log. ## Making the cache work for you - **`batched=True`** hands your function a dictionary of lists, which lets a fast tokenizer process a thousand texts in one call; it is usually the biggest speed-up on its own. - **`num_proc=8`** splits the table into eight contiguous shards processed in separate processes, each writing its own cache file. The function must be picklable for this to work at all, which also keeps the hash stable. - **`remove_columns=["text"]`** drops the raw text from the output, so the new cache file holds only what training needs. - **`cache_file_name=`** pins the output path explicitly; **`new_fingerprint=`** lets you set the fingerprint yourself when you know better than the hasher. - **`desc=`** labels the progress bar, which makes it obvious in logs whether a step ran or was loaded. - **`cleanup_cache_files()`** removes stale cache files once the pipeline settles; every changed transform leaves another full Arrow file behind. ## A quick diagnostic routine 1. Print `ds._fingerprint` after each step in two consecutive runs and find the first step where they differ. 2. Search the log for the hashing warning. 3. Check `ds.cache_files`: an empty list means the dataset lives in memory and nothing is cached. 4. Confirm the cache directory survives between runs, especially in containers and CI.

  • Your preprocessing runs in a fresh container for every job. How do you keep the Hugging Face Datasets map cache?
    Mount a persistent volume and point `HF_DATASETS_CACHE` (or `HF_HOME`) at it, so the prepared Arrow files and `cache-<fingerprint>.arrow` outputs survive. Alternatively, run the preprocessing once and publish the result with `push_to_hub` or `save_to_disk`, and have training jobs load that instead of re-mapping.
  • Does filter() in Hugging Face Datasets rewrite the table the way map() does?
    Usually not. `filter` takes part in the same fingerprint chain but, unless the kept rows are contiguous, it records an indices mapping: a cached list of which rows survive. Reads through that mapping are slower; `flatten_indices()` rewrites contiguous data when read speed matters more than disk.

  • map() decides cache reuse by comparing file modification times
  • map() only caches results when batched=True
  • An unseeded train_test_split is harmless because only map is expensive
  • Datasets built with Dataset.from_dict cache map results like any other
  • num_proc changes nothing about how the mapped function must be written