llm.data — Datasets, DataModules, and Sources¶
The llm.data package is split into three layers:
- Sources (
llm.data.sources) — pluggable text iterators backed by local files or HuggingFace streaming. Plugins register intoSOURCE_REGISTRY. - Datasets (
llm.data.datasets) —IterableDatasetandMapwrappers that turn raw text into token chunks ready for the trainer. - DataModules (
llm.data.modules) —Lightning-stylesetup/prepare_data/train_dataloader/val_dataloadercontainers that combine the above with config validation and checkpoint resume.
See the data guide for end-to-end usage and the streaming guide for detailed streaming pipeline documentation.
Base Classes¶
base
¶
BaseDataModule
¶
Bases: ABC
Abstract base class for defining a DataModule.
Map-style modules iterate a finite Dataset with DistributedSampler. Stream-style modules use IterableDataset and fixed steps_per_epoch.
源代码位于: src/llm/data/base.py
MapDataModule
¶
Bases: BaseDataModule
Finite dataset module using DistributedSampler during training.
源代码位于: src/llm/data/base.py
StreamDataModule
¶
Bases: BaseDataModule, CheckpointContributor
Iterable dataset module for unbounded / large corpora.
源代码位于: src/llm/data/base.py
Streaming Data Modules¶
For large-scale pretraining, the streaming data module handles memory-bounded data loading with checkpoint resume support:
streaming
¶
Streaming DataModule for large-scale language modeling.
StreamingTextDataModule
¶
Bases: StreamDataModule
Iterable DataModule for memory-bounded pretraining.
源代码位于: src/llm/data/modules/streaming.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
Map-Style Data Modules¶
The lm / SFT / DPO / reward / PPO tasks pair with map-style data
modules built on SamplerMapDataModule:
map_base
¶
Shared helpers for map-style DataModules.
SamplerMapDataModule
¶
Bases: MapDataModule
Map DataModule with shared DistributedSampler DataLoader helpers.
源代码位于: src/llm/data/modules/map_base.py
TokenizedMapDataModule
¶
Bases: SamplerMapDataModule
Map DataModule with shared tokenizer loading and DistributedSampler loaders.
源代码位于: src/llm/data/modules/map_base.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
assign_train_val_datasets
¶
Assign train/val datasets from a full dataset or explicit val path.
源代码位于: src/llm/data/modules/map_base.py
setup_tokenized_file_dataset
¶
Shared setup for file-backed tokenized datasets.
源代码位于: src/llm/data/modules/map_base.py
text
¶
TextDataModule
¶
Bases: TokenizedMapDataModule
DataModule for Language Modeling using TextDataset.
源代码位于: src/llm/data/modules/text.py
synthetic
¶
SyntheticDataModule
¶
Bases: SamplerMapDataModule
DataModule for generating synthetic regression data.
源代码位于: src/llm/data/modules/synthetic.py
sft
¶
SFTDataModule
¶
Bases: TokenizedMapDataModule
DataModule for Supervised Fine-Tuning (SFT) using SFTDataset.
源代码位于: src/llm/data/modules/sft.py
dpo
¶
DPODataModule
¶
Bases: TokenizedMapDataModule
DataModule for Direct Preference Optimization (DPO).
源代码位于: src/llm/data/modules/dpo.py
reward
¶
Reward Model DataModule for RLHF.
RewardDataModule
¶
Bases: TokenizedMapDataModule
DataModule for Reward Model training with DDP-compatible loaders.
源代码位于: src/llm/data/modules/reward.py
prompt
¶
Prompt DataModule for PPO rollouts.
PromptDataModule
¶
Bases: SamplerMapDataModule
DataModule that yields prompt batches for PPO rollouts.
源代码位于: src/llm/data/modules/prompt.py
Map-Style Datasets¶
text
¶
TextDataset
¶
Bases: Dataset
A PyTorch Dataset for loading and processing text data for language modeling.
The dataset reads a text file, tokenizes it, and creates overlapping or non-overlapping sequences of a fixed maximum length. Shorter sequences (typically the last one) are padded.
源代码位于: src/llm/data/datasets/text.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
create_dataloader
¶
Build a simple DataLoader for a TextDataset (scripts / legacy tests).
源代码位于: src/llm/data/datasets/text.py
build_text_dataloader
¶
Build a PyTorch DataLoader for a TextDataset.
Prefer TokenizedMapDataModule for training; this helper is for scripts.
源代码位于: src/llm/data/datasets/text.py
sft
¶
SFTDataset
¶
Bases: Dataset
Dataset for Supervised Fine-Tuning (SFT) / Instruction Tuning.
Processing flow: 1. Read JSONL data. 2. Format into prompt/response using a template. 3. Tokenize. 4. Create labels where prompt tokens are masked (set to -100). 5. Pad to max_seq_len.
源代码位于: src/llm/data/datasets/sft.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | |
alpaca_template
¶
Default Alpaca-style template.
源代码位于: src/llm/data/datasets/sft.py
dpo
¶
DPODataset
¶
Bases: Dataset
Dataset for Direct Preference Optimization (DPO).
Expects JSONL data with keys: 'prompt', 'chosen', 'rejected'.
Or generic keys mapped via template_fn.
Produces a dict with: - chosen_input_ids, chosen_labels, chosen_attention_mask - rejected_input_ids, rejected_labels, rejected_attention_mask
源代码位于: src/llm/data/datasets/dpo.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
reward
¶
Reward Model Dataset for RLHF.
Handles preference pairs for training a reward model that scores responses.
RewardDataset
¶
Bases: Dataset
Dataset for Reward Model training.
Expects JSONL data with keys: 'prompt', 'chosen', 'rejected'. Produces pairs of tokenized sequences for comparison.
Output keys per sample: - chosen_input_ids, chosen_attention_mask - rejected_input_ids, rejected_attention_mask
源代码位于: src/llm/data/datasets/reward.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
prompt
¶
Prompt dataset for RLHF / PPO rollouts.
PromptDataset
¶
Bases: Dataset
Dataset of prompt strings loaded from JSONL.
源代码位于: src/llm/data/datasets/prompt.py
Streaming Dataset¶
streaming
¶
Streaming datasets for large-scale language modeling.
StreamingTextDataset
¶
Bases: IterableDataset
Memory-efficient IterableDataset backed by a pluggable TextSource.
Shards data across DDP ranks and DataLoader workers to avoid duplication.
源代码位于: src/llm/data/datasets/streaming.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
reset
¶
Clear the resume cursor so the next iteration restarts the corpus.
Called by the training engine when the streaming source is exhausted
before steps_per_epoch is reached: pretraining cycles the corpus
(optionally de-duplicated) until the step budget is met.
If the underlying source is a persistent-dedup wrapper, its
cross-run seen-set is also cleared: otherwise a corpus whose whole
content was consumed+hashed in a prior run classifies every record
as already-seen on the recycled pass and the engine raises
"streaming corpus is empty" (RIL ISS-064). In-memory per-pass
dedup is unaffected.
源代码位于: src/llm/data/datasets/streaming.py
Stream State¶
stream_state
¶
Checkpointable state for streaming IterableDataset shards.
StreamShardState
dataclass
¶
Resume cursor for one DDP rank x DataLoader worker shard.
源代码位于: src/llm/data/stream_state.py
StreamDataState
dataclass
¶
Collection of per-shard streaming cursors.
源代码位于: src/llm/data/stream_state.py
reset
¶
Zero all per-shard cursors.
Used when a streaming corpus is exhausted before the step budget is
met: the next iteration restarts the corpus from the beginning
(streaming pretraining cycles the corpus until steps_per_epoch
completes).
源代码位于: src/llm/data/stream_state.py
Built-in Dataset Presets¶
The presets module ships well-known pretraining dataset configurations so users don't have to hand-author the HF triples.
presets
¶
Built-in data presets for common pretraining datasets.
The project already ships a streaming data pipeline
(:class:llm.data.modules.streaming.StreamingTextDataModule +
:class:llm.data.sources.HFStreamTextSource), but every well-known
dataset requires hand-authoring the DataConfig triple
(dataset_name, dataset_config, text_column). This module
ships those triples out of the box so users can pick a dataset by
name instead of looking up the HF identifier every time.
The presets are intentionally decoupled from the datasets
package: this module imports nothing from
llm.data.datasets or llm.data.modules, only
:class:llm.training.core.config.DataConfig. That keeps the import
cheap on hosts that don't have datasets installed.
Example
from llm.training.core.config import DataConfig from llm.data.presets import C4_PRESET, apply_to_config cfg = DataConfig(data_source="hf", max_seq_len=2048) _ = apply_to_config(cfg, C4_PRESET) # mutates cfg in-place cfg.dataset_name 'allenai/c4' cfg.dataset_config 'en' cfg.text_column 'text'
DatasetPreset
dataclass
¶
A well-known HuggingFace dataset configuration.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
dataset_name |
str
|
HuggingFace dataset identifier (e.g.
|
dataset_config |
str | None
|
HF dataset config name (subset /
|
dataset_split |
str
|
Split to stream. |
text_column |
str
|
Name of the text field in each row. Most
English-text datasets use |
description |
str
|
Human-readable one-liner for CLI / docs. |
preset_name |
str
|
Canonical short name (lowercase, kebab-case)
used by :func: |
源代码位于: src/llm/data/presets.py
apply_to_config
¶
Mutate config (a :class:DataConfig) to bind to preset.
Sets data_source="hf" and the four HF fields
(dataset_name, dataset_config, dataset_split,
text_column). Unrelated fields (max_seq_len,
tokenizer_*, val_dataset_path, …) are left untouched.
The mutated config is returned for fluent use:
.. code-block:: python
cfg = apply_to_config(DataConfig(...), C4_PRESET)
引发:
| 类型 | 描述 |
|---|---|
TypeError
|
if |
源代码位于: src/llm/data/presets.py
resolve_preset
¶
Look up a preset by name.
name may be:
- the preset's canonical short name (
"c4","the-pile","redpajama/c4"…), or - the full HuggingFace dataset id (
"allenai/c4").
引发:
| 类型 | 描述 |
|---|---|
KeyError
|
if no preset matches. The error message includes the available preset names so callers can self-correct. |
源代码位于: src/llm/data/presets.py
list_presets
¶
Pluggable Text Sources¶
The TextSource abstraction + SOURCE_REGISTRY plugin entry
points. Most users won't need to read this — the built-in
local and hf sources cover the common cases — but custom
sources (S3, GCS, private archives) plug in here.
sources
¶
Pluggable text sources for streaming data pipelines.
TextSource
¶
Bases: ABC
Abstract source of text records for streaming datasets.
源代码位于: src/llm/data/sources.py
LocalLineTextSource
¶
Bases: TextSource
Stream UTF-8 text line-by-line from a local file.
源代码位于: src/llm/data/sources.py
HFStreamTextSource
¶
Bases: TextSource
Stream text from a HuggingFace dataset in streaming mode.
源代码位于: src/llm/data/sources.py
DedupTextSource
¶
Bases: TextSource
TextSource wrapper that drops duplicate records by content hash.
Useful for pretraining data preparation where web-crawl-derived corpora contain substantial exact duplicates. The wrapper:
- hashes the normalized text and drops records whose hash has already been yielded this run;
- optionally loads a pre-populated "seen hashes" file on construction so dedup state is shared across runs / shards;
- optionally appends new hashes to that file so dedup state grows monotonically;
- exposes a stable :meth:
source_fingerprintthat includes the inner source's fingerprint plus the dedup strategy, so :func:validate_source_fingerprintcatches configuration drift on checkpoint resume.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
inner
|
TextSource
|
The wrapped source. Records yielded by
|
必需 |
normalize
|
Callable[[str], str] | None
|
Optional callable that normalizes text before
hashing. Default: :func: |
None
|
seen_hashes_path
|
str | Path | None
|
Optional path to a file containing previously seen hashes (one per line, hex-encoded). If the file exists when the wrapper is constructed, its contents are loaded into the seen-set so dedup state survives across runs. |
None
|
write_seen_hashes
|
bool
|
If True, append new hashes to
|
False
|
hash_algo
|
str
|
Name of any algorithm accepted by :func: |
'sha256'
|
Example::
>>> src = LocalLineTextSource("data.txt") # doctest: +SKIP
>>> dedup = DedupTextSource(src, seen_hashes_path="seen.txt") # doctest: +SKIP
>>> unique_texts = list(dedup.iter_texts()) # doctest: +SKIP
源代码位于: src/llm/data/sources.py
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 | |
reset_cross_run_seen
¶
Forget the persisted cross-run seen-set so the next pass re-yields the corpus (scoped to per-pass in-memory dedup again).
The engine calls this when a streaming corpus is exhausted and reset
before steps_per_epoch: without it, a corpus whose entire content
was consumed and hashed in an earlier run would classify every record
as already-seen on the first pass of the next run and raise
"streaming corpus is empty; nothing to train on" (RIL ISS-064).
_written is kept (hashes already persisted this session stay
persisted); only the baseline used to seed per-pass seen is
cleared, so in-memory per-pass dedup still removes in-corpus
duplicates while a recycled corpus can be consumed again.
源代码位于: src/llm/data/sources.py
build_text_source
¶
Resolve TextSource from DataConfig via SOURCE_REGISTRY.
源代码位于: src/llm/data/sources.py
source_fingerprint_from_config
¶
Build a stable fingerprint for the configured text source without loading data.
validate_source_fingerprint
¶
Raise if checkpoint source metadata does not match the active DataModule config.
源代码位于: src/llm/data/sources.py
DVC Integration¶
dvc
¶
Optional DVC integration for data-versioning on the streaming pipeline.
This module wraps the parts of DVC's CLI we actually use (version a data artifact; pull a previously-versioned artifact; report status) in a small Python surface that:
- Lazily imports
dvc:import llm.data.dvcis always cheap, regardless of whether the user installed thedvcoptional dep. Every helper checks :data:DVC_AVAILABLEfirst and degrades to a no-op with a clear warning whendvcis missing. - Hashes source fingerprints: :func:
compute_fingerprint_hashproduces a stable sha256 of a fingerprint dict (sorted JSON,sort_keys=True). The hash is what we record alongside a DVC artifact as the "version" key, so twosource_fingerprintcalls that produce identical dicts always produce the same hash. - Idempotent init: :func:
init_dvcrunsdvc initonly when the repo isn't already a DVC repo (idempotent across repeated calls). - Tracks per-artifact, not per-run: :func:
dvc_addrunsdvc add <path>once per unique (path, fingerprint-hash) pair; re-adding a path that hasn't changed is a no-op.
The streaming pipeline's checkpoint resume already validates the
source_fingerprint on every :meth:load_checkpoint_state call (see
:mod:llm.data.modules.streaming); this module layers DVC on top so
the raw data files can be re-fetched from the configured remote with
a single dvc pull, instead of having to re-download the corpus
from HuggingFace every time the cache is wiped.
Install with uv sync --extra dvc (or pip install llm[dvc] for
non-uv users) to enable. Without it, every helper in this module is a
no-op — the streaming pipeline still trains, it just doesn't version
its inputs.
compute_fingerprint_hash
¶
Compute a stable sha256 hex digest of a source fingerprint dict.
Used to key DVC artifacts on the content of the data source, not
the path on disk. Two source_fingerprint() calls that produce
identical dicts always produce the same hash, even across machines
or Python versions (the JSON encoding is fully deterministic —
sort_keys=True, default=str, separators=(",", ":")).
源代码位于: src/llm/data/dvc.py
is_dvc_initialized
¶
True if the given directory is a DVC repo (has a .dvc/ subdir).
Cheap filesystem probe; does NOT shell out. Safe to call on every helper invocation.
源代码位于: src/llm/data/dvc.py
init_dvc
¶
Initialize DVC in repo_root (idempotent).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
repo_root
|
Path | str
|
Repository root directory (the parent of |
必需 |
remote_url
|
str | None
|
Optional remote URL to configure as the default
storage. Supported schemes depend on the installed DVC
extras — local paths, |
None
|
remote_name
|
str
|
Remote name to register (default |
'storage'
|
返回:
| 类型 | 描述 |
|---|---|
bool
|
True if |
bool
|
initialized); False if it was a no-op. Note that this is the |
bool
|
inverse of :func: |
bool
|
repo" answer, which makes the return value useful for logging. |
源代码位于: src/llm/data/dvc.py
dvc_status
¶
Return one of: "tracked" | "untracked" | "not_found" | "no_dvc".
Pure filesystem probe — does NOT shell out to dvc status and
does NOT require dvc to be installed. Inspects the
filesystem for the .dvc directory and for a <path>.dvc
file (the marker DVC writes next to each tracked artifact). Useful
for callers that want to detect "this dir was previously a DVC
repo" without paying the dvc import cost.
Note: "no_dvc" here means "no DVC bookkeeping on disk" — not
"dvc package isn't importable". Callers that need to gate on the
import availability should check :data:DVC_AVAILABLE separately.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
Path | str
|
Path to the artifact (file or directory). May be
absolute or relative to |
必需 |
repo_root
|
Path | str | None
|
Repository root. Required when |
None
|
源代码位于: src/llm/data/dvc.py
dvc_add
¶
Track path with DVC; return a metadata dict (or None if DVC is unavailable).
Idempotent: re-tracking a path that is already versioned is a
no-op (we skip the dvc add call). The metadata dict carries
path (the artifact path), fingerprint_hash (sha256 of
fingerprint if provided), repo_root (resolved), and
versioned_at (ISO 8601 UTC timestamp).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
Path | str
|
File or directory to version. Relative paths are
resolved against |
必需 |
fingerprint
|
dict[str, Any] | None
|
Optional |
None
|
repo_root
|
Path | str | None
|
Repository root. When |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, str] | None
|
|
dict[str, str] | None
|
Otherwise the metadata dict; raises :class: |
dict[str, str] | None
|
|
源代码位于: src/llm/data/dvc.py
dvc_pull
¶
Pull path from the configured DVC remote.
Returns True on success, False if DVC is unavailable. Raises
:class:RuntimeError when the underlying dvc pull fails.