HuggingFace datasets¶
Two classes, one selector flag:
HuggingFaceDataset(eager) — loads the entire split into memory, tokenizes once, packs into fixed-length sequences.StreamingHuggingFaceDataset(streaming) — anIterableDatasetthat pulls documents from the Hub on the fly, tokenizes per iteration, and yields packed sequences as they fill.
Config flag: data.hf_streaming (default false).
Both classes live in
kempnerforge/data/dataset.py.
Eager — HuggingFaceDataset¶
[data]
hf_dataset_name = "wikitext"
hf_dataset_config = "wikitext-103-raw-v1" # optional
hf_dataset_split = "train"
hf_dataset_text_field = "text"
hf_streaming = false
tokenizer_path = "gpt2"
Flow on construction:
AutoTokenizer.from_pretrained(tokenizer_path)— loads the tokenizer. The EOS token ID falls back to0if the tokenizer doesn’t declare one.load_dataset(name, config, split=split)— the full HF split is materialized.Each example’s
text_fieldis encoded withadd_special_tokens=False, an EOS token is appended, and the combined token stream is sliced into fixed(seq_len + 1)chunks. The extra+1is for the next-token label offset.Partial remainder at the end is discarded — clean, full sequences only.
At training time __getitem__(idx) returns
{"input_ids": tokens[:-1], "labels": tokens[1:]} (plus doc_ids if
pack_sequences=true).
Good for: small-to-medium corpora that fit in memory; repeatable experiments where you want a fixed sequence order.
Bad for: anything where load_dataset(...) itself would OOM.
Streaming — StreamingHuggingFaceDataset¶
[data]
hf_dataset_name = "allenai/c4"
hf_dataset_split = "train"
hf_streaming = true
tokenizer_path = "meta-llama/Llama-3-8B"
Stream mode is an IterableDataset:
No
__len__, no sampler (the dataset is its own iterator).build_data_pipelinewraps it inStreamingDataLoader, which wraps atorch.utils.data.DataLoaderand saves and replays its position (see Resumption in streaming mode).The stream is split across data-parallel ranks after the shuffle, with
datasets.distributed.split_dataset_by_node. When the source’s shard count divides by the data-parallel size, each rank reads only its own shards; otherwise every rank reads the stream and keeps everyworld_size-th document. With uneven shards, a rank with less text finishes its pass and reads its data again while the others are still in their first pass.
Buffered shuffling is applied at the HF level:
ds = load_dataset(name, config, split=split, streaming=True)
ds = ds.shuffle(seed=self.seed + self._epoch,
buffer_size=self.shuffle_buffer_size) # default 10k
The default buffer holds 10,000 examples. Larger buffers give better shuffle quality at the cost of startup latency and RAM.
Tokenizer is lazy¶
The tokenizer is loaded on first __iter__ call, not at construction.
This sidesteps a common fork() issue with multiprocessing DataLoader
workers: a tokenizer loaded in the parent can deadlock if the worker
processes fork after HF has already spawned its own threads.
Resumption in streaming mode¶
StreamingDataLoader saves
{"epoch", "batches_yielded", "stream", "data_parallel_rank"}: how many
batches training took in the current pass, the rank that took them, and
what decides the stream’s order (the source’s data files by name and size, or its Hub
name and config, with its shard count; the data-parallel size, seed and
shuffle buffer, seq_len, tokenizer, pack_sequences, batch size and
num_workers). On resume it rebuilds the pass and discards that many
batches before yielding, so training continues at the exact next sample:
the shuffle, the split across ranks and DataLoader workers, and the
packing are deterministic. The replay reads and tokenizes the consumed
part of the pass again, about k × batch_size × seq_len / rate for a
resume at batch k, and logs its progress; from the Hub it downloads
that part again.
A resume with one of those settings changed raises DataPositionError
naming the change, because the same count would land on different
samples, so a streaming run keeps its data-parallel size, batch size and
num_workers across resumes. Moving the same files to another directory
is fine; a new version of the dataset or of datasets can shift the
replay unnoticed. A checkpoint.load_path warm start starts the stream at
its first document instead of raising, and so does an auto-resume onto
another data-parallel size with
checkpoint.ignore_rank_state_mismatch = true, which without the flag
is refused before the position is applied (see
Resharding).
Hugging Face’s own
IterableDataset.state_dict() is not used: it drops the examples in the
shuffle buffer on resume. On several ranks an auto-resume gives every
rank its own count, as does one that checkpoint.ignore_rank_state_mismatch
lets onto another layout of the same data-parallel size; a
checkpoint.load_path warm start gives every rank rank 0’s count, which
is exact until the first rank finishes a pass. See
Stateful dataloader § Streaming loader
for the replay cost and for how the ranks’ counts differ.
Packing and document boundaries¶
Same as Memory-mapped § Sequence packing:
setting pack_sequences = true adds doc_ids to each sample and
masks cross-document label positions with -100. Both HF paths
support it.
Eval datasets¶
[eval] can mirror either path independently of training:
[eval]
enabled = true
hf_dataset_name = "wikitext"
hf_dataset_split = "validation"
For HF eval sets, rank 0 tokenizes and broadcasts the packed tensor
to all ranks via torch.distributed.broadcast. This is a deliberate
choice to avoid load_dataset file-lock (flock) failures on
cluster filesystems (Lustre, VAST) where parallel opens crash.
Limitations¶
Eager mode re-tokenizes on every process start; no tokenized cache beyond the HF
~/.cache/huggingface/layer.Streaming resumes by replaying: it reads and tokenizes the consumed part of the pass again, and needs the saved data-parallel size, batch size,
num_workersand stream settings.Neither class supports on-disk tokenization caching. If you want that, pre-tokenize with
tatmand switch to Memory-mapped.
See also¶
Memory-mapped — the faster path once you have pre-tokenized shards.
Mixing and annealing — compose HF sources alongside mmap ones in a
MixtureDataset.configs/train/hf_wikitext.toml— a working streaming-mode config.