Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / batching / build_dataloader.py: 75%
377 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Build DataLoaders and calculate distributed micro-batch sizing."""
17from __future__ import annotations
19import copy
20from abc import ABC, abstractmethod
21from collections.abc import Callable, Iterator, Mapping, Sequence
22from dataclasses import replace
23from typing import Any
25import torch
26from torch.utils.data import IterableDataset, default_collate
27from torchdata.stateful_dataloader import StatefulDataLoader
29from hyper_parallel.data.batching.dynamic_batch import (
30 FullSampleCheckpoint,
31 IndexReplayCheckpoint,
32 MappingReplayDataset,
33 _BatchPipeline,
34 _OmniPackingPipeline,
35 _TokenBatchPipeline,
36)
37from hyper_parallel.data.batching.build_collate_fn import TextPackingCollator
38from hyper_parallel.data.dataset_logging import get_dataset_logger
39from hyper_parallel.data.parallel import build_dataset_batch_sampler
40from hyper_parallel.data.parallel.batch_sampler import (
41 get_sampler_checkpoint_state, has_torchdata_state, sampler_optimizer_step_progress, sampler_state_for_load,
42)
44from hyper_parallel.data.distributed import (
45 BalancingAlgorithm,
46 CostModel,
47 DistributedDatasetConfig,
48 SampleMetadata,
49 TensorFieldSpec,
50 build_distributed_dataloader,
51)
53logger = get_dataset_logger(__name__)
56def calculate_num_micro_batches(
57 global_batch_size: int,
58 micro_batch_size: int,
59 dp_world_size: int,
60) -> int:
61 """Calculate the number of micro-batches in one optimizer step.
63 Args:
64 global_batch_size: Number of samples processed by one optimizer step.
65 micro_batch_size: Number of samples processed by each DP rank and forward pass.
66 dp_world_size: Number of data-parallel ranks.
68 Returns:
69 Number of forward/backward micro-batches executed by each DP rank.
71 Raises:
72 ValueError: If the global batch cannot be divided exactly.
73 """
74 distributed_micro_batch_size = micro_batch_size * dp_world_size
75 if global_batch_size % distributed_micro_batch_size != 0:
76 raise ValueError(
77 f"global_batch_size ({global_batch_size}) must be divisible by "
78 f"micro_batch_size * dp_world_size ({distributed_micro_batch_size})"
79 )
81 num_micro_batches = global_batch_size // distributed_micro_batch_size
82 logger.debug(
83 "Resolved micro-batches=%d from global_batch_size=%d, micro_batch_size=%d, dp_world_size=%d",
84 num_micro_batches,
85 global_batch_size,
86 micro_batch_size,
87 dp_world_size,
88 )
89 return num_micro_batches
92def _is_iterable_dataset(dataset: Any) -> bool:
93 """Return whether a Dataset streams samples without mapping-style access."""
94 if isinstance(dataset, IterableDataset):
95 is_iterable = True
96 else:
97 has_iterator = callable(getattr(dataset, "__iter__", None))
98 has_index_access = callable(getattr(dataset, "__getitem__", None))
99 is_iterable = has_iterator and not has_index_access
100 return is_iterable
103def _resolve_load_balance(
104 dataloader_target: Any, data_config: Mapping[str, Any],
105) -> Mapping[str, Any] | None:
106 """Validate the balancing block and reject obsolete Dataset-side settings."""
107 removed_options = {
108 "load_balance", "distributed_dataloader", "balance_window_size", "device_prefetch_depth",
109 "log_balance", "min_balance_gain", "repack_sequences", "use_data_process",
110 }.intersection(data_config)
112 if removed_options:
113 raise ValueError(f"Move data_config balancing options {sorted(removed_options)} to dataloader.load_balance")
115 load_balance = getattr(dataloader_target, "load_balance", None)
117 if load_balance is not None and not isinstance(load_balance, Mapping):
118 raise ValueError("dataloader.load_balance must be a mapping; omit it to disable balancing")
120 return load_balance
123def _build_distributed_packing_config(
124 dataloader_target: Any,
125 data_config: Mapping[str, Any],
126 *,
127 micro_batch_size: int,
128 seed: int,
129 max_seq_len: int | None = None,
130) -> DistributedDatasetConfig:
131 """Derive distributed-packing sizes and retain optional runtime tuning."""
132 try:
133 seq_len = int(data_config.get("max_seq_len", max_seq_len))
134 except (KeyError, TypeError, ValueError) as exc:
135 raise ValueError("Distributed loading requires data_config.max_seq_len or transform.max_seq_len") from exc
137 if max_seq_len is not None and seq_len != max_seq_len:
138 raise ValueError("data_config.max_seq_len must match transform.max_seq_len for native batch balancing")
140 options = dict(dataloader_target.load_balance)
141 trainer_managed_options = {
142 "seq_len",
143 "local_batch_size",
144 "dp_dim_names",
145 "drop_last",
146 "seed",
147 "num_workers",
148 "pin_memory",
149 "prefetch_factor",
150 "persistent_workers",
151 "dataset_already_sharded",
152 }
153 conflicting_options = sorted(set(options) & trainer_managed_options)
155 if conflicting_options:
156 raise ValueError(
157 "dataloader.load_balance cannot override Trainer-managed options "
158 f"{conflicting_options}; configure DataLoader execution options on dataloader "
159 "and sequence length on dataset.data_config"
160 )
162 return DistributedDatasetConfig(
163 seq_len=seq_len,
164 local_batch_size=micro_batch_size,
165 dp_dim_names=("dp",),
166 drop_last=bool(getattr(dataloader_target, "drop_last", True)),
167 seed=seed,
168 dataset_already_sharded=False,
169 **options,
170 )
173def _native_text_metadata(sample: Mapping[str, Any]) -> SampleMetadata:
174 """Describe a complete GPT output without inferring new attention boundaries."""
175 seq_len = int(sample["input_ids"].shape[-1])
176 return SampleMetadata(pack_tokens=seq_len, features={"P": seq_len, "D": 0})
179def _resolve_policy(dataloader_target: Any, name: str, supplied: Any, model_config: Any) -> Any:
180 """Prefer an explicit policy, otherwise instantiate its configured target."""
182 if supplied is not None:
183 return supplied
185 configured = getattr(dataloader_target, name, None)
187 if configured is None:
188 return None
190 return configured.build(model_config=model_config)
193def _native_dataloader_kwargs(dataloader_target: Any) -> dict[str, Any]:
194 """Forward configured execution options without changing distributed packing."""
195 return {
196 name: getattr(dataloader_target, name)
197 for name in (
198 "num_workers", "pin_memory", "prefetch_factor", "persistent_workers",
199 "timeout", "worker_init_fn", "multiprocessing_context", "pin_memory_device", "in_order",
200 )
201 if getattr(dataloader_target, name, None) is not None
202 }
205def _trainer_model_batch_spec(target: Any, collate_fn: Any, data_config: Mapping[str, Any]) -> Any:
206 """Resolve declared model fields without reading samples on model peers."""
207 configured = getattr(target, "model_batch_spec", None)
209 if configured is not None:
211 return configured.build() if callable(getattr(configured, "build", None)) else configured
213 declared = getattr(collate_fn, "model_batch_spec", None)
215 if declared is not None:
217 return declared
219 if isinstance(collate_fn, TextPackingCollator):
221 return {
222 "input_ids": TensorFieldSpec((1, None), torch.int64),
223 "labels": TensorFieldSpec((1, None), torch.int64),
224 "cu_seq_lens": TensorFieldSpec((None,), torch.int32),
225 }
227 # Instruction and multimodal providers may emit additional model-owned fields.
228 # Their layouts must be configured explicitly rather than guessed from a sample.
230 if collate_fn is default_collate and not data_config.get("is_instruction_dataset", False):
231 spec = {name: TensorFieldSpec((None, None), torch.int64) for name in ("input_ids", "labels")}
233 if data_config.get("inter_document_masking", False):
234 spec["cu_seq_lens"] = TensorFieldSpec((None, None), torch.int32)
236 if data_config.get("create_ltor_fields_in_dataloader", False):
237 spec.update({
238 "loss_mask": TensorFieldSpec((None, None), torch.float32),
239 "position_ids": TensorFieldSpec((None, None), torch.int64),
240 "attention_mask": TensorFieldSpec((None, 1, None, None), torch.bool),
241 })
243 return spec
245 return None
248def _build_native_sampler_loader(
249 dataset: Any,
250 batch_sampler: Any,
251 collate_fn: Any,
252 dataloader_target: Any,
253 mesh_context: Any,
254 data_config: Mapping[str, Any],
255 seed: int,
256 *,
257 metadata_fn: Callable[[Any], SampleMetadata] | None = None,
258 max_seq_len: int | None = None,
259 model_config: Any = None,
260 cost_model: CostModel | None = None,
261 balancing_algorithm: BalancingAlgorithm | None = None,
262) -> Any:
263 """Reuse native Dataset outputs and the existing collator in collective loading."""
265 if batch_sampler is None:
266 raise ValueError("Native BatchSampler balancing requires a mapping Dataset")
268 if getattr(mesh_context, "device_mesh", None) is None:
269 raise ValueError("Native BatchSampler balancing requires mesh_context.device_mesh")
271 if int(getattr(mesh_context, "pp_size", 1)) != 1:
272 raise ValueError("Native BatchSampler balancing does not yet support pipeline parallelism")
274 target_callable = getattr(dataloader_target, "_target_", None)
276 if isinstance(target_callable, type) and issubclass(target_callable, _DynamicBatchLoader):
277 raise ValueError("Native BatchSampler balancing must not override native batches with dynamic batching")
279 config = _build_distributed_packing_config(
280 dataloader_target, data_config,
281 micro_batch_size=batch_sampler.micro_batch_size, seed=seed,
282 max_seq_len=max_seq_len,
283 )
284 device_type = getattr(mesh_context.device_mesh, "device_type", "cpu")
286 if device_type != "npu" and "communication_backend" not in dataloader_target.load_balance:
287 config = replace(config, communication_backend="gloo")
289 communication_device = torch.device("cpu")
291 if device_type != "cpu":
292 communication_device = torch.device(device_type, getattr(torch, device_type).current_device())
294 effective_metadata_fn = metadata_fn
296 if not config.metadata_mode and effective_metadata_fn is None:
297 effective_metadata_fn = _native_text_metadata
299 effective_cost_model = _resolve_policy(dataloader_target, "cost_model", cost_model, model_config)
300 return build_distributed_dataloader(
301 dataset, mesh_context.device_mesh, config,
302 batch_sampler=batch_sampler, metadata_fn=effective_metadata_fn,
303 metadata=getattr(dataset, "metadata", None) if config.metadata_mode else None,
304 collate_fn=None if config.repack_sequences else collate_fn,
305 model_batch_spec=_trainer_model_batch_spec(
306 dataloader_target, None if config.repack_sequences else collate_fn, data_config,
307 ),
308 dataloader_kwargs=_native_dataloader_kwargs(dataloader_target),
309 device=communication_device,
310 model_config=model_config,
311 cost_model=effective_cost_model,
312 balancing_algorithm=_resolve_policy(
313 dataloader_target, "balancing_algorithm", balancing_algorithm, model_config,
314 ),
315 )
318def _build_split_batch_sampler(
319 dataset: Any, dataloader_target: Any, training_config: Any, mesh_context: Any, seed: int,
320) -> Any:
321 """Build rank-local sampling for mapping datasets; iterable sources own their order."""
323 if _is_iterable_dataset(dataset):
324 return None
326 return build_dataset_batch_sampler(
327 total_samples=len(dataset),
328 micro_batch_size=training_config.micro_batch_size,
329 global_batch_size=training_config.global_batch_size,
330 dp_world_size=mesh_context.dp_size,
331 dp_rank=mesh_context.dp_rank,
332 data_rearrange_map=getattr(dataloader_target, "data_rearrange_map", None),
333 sampler_type=getattr(dataloader_target, "sampler_type", "single"),
334 data_sharding=getattr(dataloader_target, "data_sharding", False),
335 seed=seed,
336 )
339def build_dataloader(
340 dataloader_target: Any,
341 *,
342 datasets: Sequence[Any | None],
343 collate_fn: Any,
344 mesh_context: Any,
345 training_config: Any,
346 data_config: Mapping[str, Any] | None = None,
347 max_seq_len: int | None = None,
348 default_seed: int = 1234,
349 metadata_fn: Callable[[Any], SampleMetadata] | None = None,
350 model_config: Any = None,
351 cost_model: CostModel | None = None,
352 balancing_algorithm: BalancingAlgorithm | None = None,
353) -> tuple[tuple[Any | None, ...], tuple[Any | None, ...]]:
354 """Build train, validation, and test DataLoaders.
356 Mapping Datasets receive a distributed batch sampler. Iterable Datasets
357 control their own order. The configured target decides whether selected
358 samples use fixed collation or dynamic token batching.
360 Args:
361 dataloader_target: DataLoader build target. A load_balance mapping enables
362 balancing, including an empty mapping; omission disables it. With balancing, its optional
363 model_batch_spec is a tensor layout or a Target that builds one.
364 Standard GPT and Online text layouts are provided automatically;
365 instruction and multimodal collators require an explicit declaration
366 on this target or the collator when model parallelism is enabled.
367 datasets: Train, validation, and test datasets.
368 collate_fn: Collator applied after fixed or dynamic sample selection.
369 mesh_context: Data-parallel mesh context.
370 training_config: Batch size and random seed configuration.
371 data_config: Dataset options, including the source sequence length.
372 max_seq_len: Per-row packing limit and fixed padding length for Online data.
373 default_seed: Seed used when no training seed is configured.
374 metadata_fn: Native physical sample metadata for online
375 ``dataloader.load_balance``. Defaults to complete GPT output
376 lengths; VLMTrainer supplies image metadata. Offline mode uses the
377 ``dataset.metadata`` instead: an indexable SampleMetadata sequence
378 aligned one-to-one with that Dataset split's logical outputs.
379 model_config: Effective model dimensions for the default workload estimator.
380 Unsupported architectures require an explicit cost model.
381 cost_model: Optional workload callback overriding the configured cost-model target.
382 balancing_algorithm: Optional assignment policy overriding its configured target.
384 Returns:
385 DataLoader and batch-sampler tuples for the three Dataset splits.
386 """
388 if len(datasets) != 3:
389 raise ValueError("datasets must contain train, validation, and test entries")
391 if all(dataset is None for dataset in datasets):
392 return (None, None, None), (None, None, None)
394 if dataloader_target is None:
395 raise ValueError("dataloader_target must define a build target")
397 micro_batch_size = training_config.micro_batch_size
398 seed = training_config.seed if training_config.seed is not None else default_seed
400 dp_world_size = mesh_context.dp_size
402 sampler_type = getattr(dataloader_target, "sampler_type", "single")
403 data_config = data_config or {}
404 load_balance = _resolve_load_balance(dataloader_target, data_config)
405 dataloaders: list[Any | None] = [None] * len(datasets)
406 batch_samplers: list[Any | None] = [None] * len(datasets)
408 for split_index, (split_name, dataset) in enumerate(zip(("train", "valid", "test"), datasets)):
409 if dataset is None:
410 logger.debug("Skipping empty Dataset split=%s", split_name)
411 continue
413 batch_sampler = _build_split_batch_sampler(
414 dataset, dataloader_target, training_config, mesh_context, seed,
415 )
417 if load_balance is not None:
418 dataloader = _build_native_sampler_loader(
419 dataset, batch_sampler, collate_fn, dataloader_target, mesh_context, data_config, seed,
420 metadata_fn=metadata_fn, max_seq_len=max_seq_len,
421 model_config=model_config, cost_model=cost_model, balancing_algorithm=balancing_algorithm,
422 )
424 else:
425 dataloader = dataloader_target.build(
426 dataset=dataset, collate_fn=collate_fn, batch_sampler=batch_sampler,
427 batch_size=micro_batch_size, sampler_type=sampler_type,
428 dp_world_size=dp_world_size, max_seq_len=max_seq_len, seed=seed,
429 )
431 logger.debug(
432 "Built DataLoader split=%s, dataset=%s, batch_sampler=%s",
433 split_name, type(dataset).__name__,
434 type(batch_sampler).__name__ if batch_sampler is not None else None,
435 )
436 dataloaders[split_index] = dataloader
437 # The collective loader owns sampler checkpoint/epoch state; exposing
438 # its speculative cursor to the Trainer would skip prefetched batches.
439 batch_samplers[split_index] = None if load_balance is not None else batch_sampler
441 logger.debug("Finished building train/valid/test DataLoaders")
442 return tuple(dataloaders), tuple(batch_samplers)
445class RepeatingDataLoader:
446 """Repeat Online data from the beginning when the source loader is exhausted.
448 Training epoch boundaries reuse the same iterator. Dynamic loaders handle
449 repetition internally; this wrapper repeats ordinary loaders' batches.
451 Attributes:
452 source_dataloader: Loader that reads and batches the data.
453 source_repeat_num: Number of restarts after EOF; initially zero.
454 _micro_batches_since_restart: Source batches yielded in the current pass,
455 used to reject an empty pass even when restoring at EOF.
456 _repeating_iterator: Iterator reused across training epochs.
457 """
459 def __init__(self, source_dataloader: Any) -> None:
460 """Wrap a finite data source.
462 Args:
463 source_dataloader: Loader to restart when exhausted.
464 """
465 self.source_dataloader = source_dataloader
466 self.source_repeat_num = 0
467 self._micro_batches_since_restart = 0
468 self._repeating_iterator: Iterator[Any] | None = None
470 def __iter__(self) -> Iterator[Any]:
471 """Reuse the iterator across training epochs."""
473 if self._repeating_iterator is None:
474 self._repeating_iterator = self._repeat_batches()
476 return self._repeating_iterator
478 def _repeat_batches(self) -> Iterator[Any]:
479 """Repeat at EOF; raise if a full pass produces no batches."""
480 while True:
481 for micro_batch in self.source_dataloader:
482 self._micro_batches_since_restart += 1
483 yield micro_batch
485 if not self._micro_batches_since_restart:
486 raise ValueError("Online repeat=true source produced no batches on this rank")
488 self.source_repeat_num += 1
489 self._micro_batches_since_restart = 0
490 self.source_dataloader.set_epoch(self.source_repeat_num)
491 logger.warning(
492 "Online data source exhausted; repeating data from the beginning (source_repeat_num=%s).",
493 self.source_repeat_num,
494 )
496 def set_epoch(self, epoch: int) -> None:
497 """Preserve the source pass and buffered iterator across training epochs."""
498 del epoch
500 def wait_for_prefetch(self) -> None:
501 """Drain source prefetch work when the wrapped loader supports it."""
502 wait = getattr(self.source_dataloader, "wait_for_prefetch", None)
503 if callable(wait):
504 wait()
506 def prefetch(self) -> None:
507 """Start source prefetch when the wrapped loader supports it."""
508 prefetch = getattr(self.source_dataloader, "prefetch", None)
509 if callable(prefetch):
510 prefetch()
512 def prefetch_plan(self) -> None:
513 """Run the source pipeline prefetch plan when available."""
514 prefetch_plan = getattr(self.source_dataloader, "prefetch_plan", None)
515 if callable(prefetch_plan):
516 prefetch_plan()
518 def close(self) -> None:
519 """Close the wrapped loader when it owns closeable resources."""
520 close = getattr(self.source_dataloader, "close", None)
521 if callable(close):
522 close()
524 def state_dict(self) -> dict[str, Any]:
525 """Save repeat progress and source loader state."""
526 checkpoint_state = {
527 "source_epoch": self.source_repeat_num,
528 "batches_in_pass": self._micro_batches_since_restart,
529 "dataloader": self.source_dataloader.state_dict(),
530 }
531 return checkpoint_state
533 def load_state_dict(self, checkpoint_state: dict[str, Any]) -> None:
534 """Restore repeat progress and source loader state."""
535 self.source_repeat_num = checkpoint_state["source_epoch"]
536 self._micro_batches_since_restart = checkpoint_state["batches_in_pass"]
537 self.source_dataloader.load_state_dict(checkpoint_state["dataloader"])
538 self._repeating_iterator = None
540 def state_dict_for_load(self) -> dict[str, Any]:
541 """Build the state template for checkpoint loading."""
542 build_source_restore_state = getattr(
543 self.source_dataloader, "state_dict_for_load", self.source_dataloader.state_dict
544 )
545 checkpoint_state = {
546 "source_epoch": self.source_repeat_num,
547 "batches_in_pass": self._micro_batches_since_restart,
548 "dataloader": build_source_restore_state(),
549 }
550 return checkpoint_state
553class FixedBatchDataLoader(StatefulDataLoader):
554 """Build fixed-sample batches while retaining Trainer iterator policy."""
556 def __init__(
557 self,
558 dataset: Any,
559 batch_sampler: Any = None,
560 collate_fn: Callable[[list[Any]], Any] | None = None,
561 *,
562 batch_size: int | None = None,
563 drop_last: bool = True,
564 sampler_type: str = "single",
565 num_workers: int = 0,
566 seed: int = 1234,
567 pin_memory: bool = False,
568 prefetch_factor: int | None = None,
569 ) -> None:
570 """Initialize the stateful DataLoader."""
572 if sampler_type not in ("single", "cyclic"):
573 raise ValueError("sampler_type must be 'single' or 'cyclic'")
575 self.drop_last = drop_last
576 self.sampler_type = sampler_type
577 generator = torch.Generator().manual_seed(seed)
578 worker_options = {
579 "num_workers": num_workers,
580 "generator": generator,
581 "pin_memory": pin_memory,
582 }
584 if num_workers > 0 and prefetch_factor is not None:
585 worker_options["prefetch_factor"] = prefetch_factor
587 if batch_sampler is None:
588 resolved_batch_size = 1 if batch_size is None else batch_size
589 super().__init__(
590 dataset=dataset,
591 batch_size=resolved_batch_size,
592 collate_fn=collate_fn,
593 drop_last=drop_last,
594 **worker_options,
595 )
596 else:
597 super().__init__(
598 dataset=dataset,
599 batch_sampler=batch_sampler,
600 collate_fn=collate_fn,
601 **worker_options,
602 )
604 # Native worker snapshots may precede the delivered optimizer boundary.
605 if hasattr(batch_sampler, "enable_source_batch_resume"):
606 batch_sampler.enable_source_batch_resume()
608 def state_dict(self) -> dict[str, Any]:
609 """Save the native delivered cursor alongside torchdata's worker state."""
610 state = super().state_dict()
612 if "_snapshot" not in state:
613 return state
615 snapshot = state["_snapshot"]["_main_snapshot"]
616 sampler = snapshot.get("_index_sampler_state")
618 if isinstance(sampler, dict) and "consumed_samples" in sampler:
619 sampler = dict(sampler)
620 sampler["consumed_samples"] += (
621 state.get("_steps_since_snapshot", 0) * self.batch_sampler.global_micro_batch_size
622 )
623 state["_index_sampler_state"] = sampler
625 return state
627 def state_dict_for_load(self) -> dict[str, Any]:
628 """Request native worker state and shared or legacy sampler cursors."""
629 return sampler_state_for_load(self.state_dict())
631 def load_state_dict(self, state_dict: dict[str, Any]) -> None:
632 """Restore torchdata state, or a balanced loader's complete native cursor.
634 Args:
635 state_dict: State saved by the ordinary or balanced native loader.
636 """
637 # The training frame may still retain the old iterator during rollback.
638 # Stop its producers before torchdata drops the loader's iterator reference.
639 iterator = self._iterator
640 if self.num_workers > 0 and iterator is not None:
641 # torchdata exposes worker shutdown only through its iterator's private API.
642 iterator._shutdown_workers() # pylint: disable=protected-access
643 sampler = get_sampler_checkpoint_state(state_dict)
644 snapshot = state_dict.get("_snapshot", {}).get("_main_snapshot", {})
645 native_sampler = sampler if sampler is not None else snapshot.get("_index_sampler_state")
646 repartition = isinstance(native_sampler, Mapping) and any(
647 native_sampler.get(name) != getattr(self.batch_sampler, name, native_sampler.get(name))
648 for name in ("global_batch_size", "dp_world_size")
649 )
651 if state_dict.get("global_rank") is None and has_torchdata_state(state_dict) and not repartition:
652 if isinstance(native_sampler, Mapping) and native_sampler.get("epoch") is not None:
653 self.set_epoch(native_sampler["epoch"])
655 super().load_state_dict(state_dict)
656 return
658 if sampler is None:
659 raise ValueError("Balanced checkpoint has no native sampler cursor on this rank")
661 if sampler["epoch"] < 0 or sampler_optimizer_step_progress(sampler):
662 raise ValueError("Switching loaders requires a complete optimizer-step cursor")
664 self.batch_sampler.load_state_dict(sampler)
665 self.set_epoch(sampler["epoch"])
666 super().load_state_dict({})
667 self.next_iter_state = None
669 def set_epoch(self, epoch: int) -> None:
670 """Forward epoch state to the Dataset and configured batch sampler.
672 Args:
673 epoch: Epoch index used by the sampler and Dataset.
674 """
676 if self.batch_sampler is not None and hasattr(self.batch_sampler, "set_epoch"):
677 self.batch_sampler.set_epoch(epoch)
679 epoch_setter = getattr(self.dataset, "set_epoch", None)
681 if callable(epoch_setter):
682 dataset_epoch = epoch if self.sampler_type == "cyclic" else 0
683 epoch_setter(dataset_epoch)
686class _DynamicBatchLoader(ABC):
687 """Own common dynamic source iteration, buffering, and checkpoint state.
689 Subclasses define how candidates are selected and finalized before the
690 configured collator builds a batch.
692 Args:
693 dataset: Online mapping or iterable Dataset producing ModelSamples.
694 batch_sampler: Optional mapping-style batch sampler.
695 collate_fn: Final batch collator receiving the selected ModelSamples.
696 batch_size: Number of independently packed rows in each micro-batch.
697 dp_world_size: Number of data-parallel source lanes.
698 save_by_idx: Whether to checkpoint buffer entries as output indices.
699 Mapping Datasets default to true and iterable Datasets default to false.
700 max_seq_len: Required per-row packing limit and fixed padding length.
701 Oversized samples are skipped.
702 min_buffered_samples: Minimum candidate samples buffered before batching.
703 drop_last: Drop an incomplete group of packed rows at finite EOF.
704 Repeating iteration retains candidates across source restarts.
705 repeat: Restart the source at EOF while retaining buffered candidates.
706 None inherits the Trainer's Online policy; standalone iteration is finite.
707 sampler_type: Whether each Dataset epoch reuses one order or advances
708 the deterministic cyclic order.
709 num_workers: Number of source DataLoader workers.
710 seed: Source DataLoader random seed.
711 pin_memory: Whether source samples use pinned host memory.
712 prefetch_factor: Number of source batches prefetched by each worker.
713 """
715 def __init__(
716 self,
717 dataset: Any,
718 batch_sampler: Any = None,
719 collate_fn: Callable[[Sequence[Mapping[str, Any]]], Mapping[str, Any]] | None = None,
720 *,
721 batch_size: int,
722 dp_world_size: int | None = None,
723 save_by_idx: bool | None = None,
724 max_seq_len: int,
725 min_buffered_samples: int = 200,
726 drop_last: bool = True,
727 repeat: bool | None = None,
728 sampler_type: str = "single",
729 num_workers: int = 0,
730 seed: int = 1234,
731 pin_memory: bool = False,
732 prefetch_factor: int | None = None,
733 ) -> None:
734 """Initialize source reading, token selection, and Online packing."""
736 # pylint: disable=too-many-locals
737 if collate_fn is None:
738 raise ValueError(f"{type(self).__name__} requires a collate_fn")
740 if batch_size <= 0:
741 raise ValueError("batch_size must be positive")
743 if max_seq_len is None or max_seq_len <= 0:
744 raise ValueError("max_seq_len must be positive")
746 resolved_dp_world_size = dp_world_size
748 if resolved_dp_world_size <= 0:
749 raise ValueError("dp_world_size must be positive")
751 if batch_sampler is not None and batch_sampler.dp_world_size != resolved_dp_world_size:
752 raise ValueError("batch_sampler.dp_world_size must match dp_world_size")
754 if batch_sampler is not None:
755 # Drop only incomplete packed rows, retaining every raw source tail.
756 batch_sampler.drop_last = False
758 self.drop_last = drop_last
759 self.batch_size = batch_size
760 self.repeat = repeat is True
761 self.source_repeat_num = 0
762 self._source_batches_since_restart = 0
763 self._batch_iterator: Iterator[Mapping[str, Any]] | None = None
764 self.batch_collate_fn = collate_fn
765 self.dp_world_size = resolved_dp_world_size
767 # build_candidate_buffer
768 self._batch_pipeline = self._build_batch_pipeline(dataset)
769 self.candidate_buffer = self._batch_pipeline.build_candidate_buffer(
770 token_budget=max_seq_len,
771 min_buffered_samples=min_buffered_samples,
772 )
774 # Resuming training from a checkpoint
775 self._buffer_checkpoint = self._build_buffer_checkpoint(dataset, save_by_idx)
777 self.source_dataloader = FixedBatchDataLoader(
778 dataset=self._buffer_checkpoint.source_dataset,
779 batch_sampler=batch_sampler,
780 # Keep source samples separate until the candidate buffer selects them.
781 collate_fn=list,
782 batch_size=1 if batch_sampler is None else batch_size,
783 drop_last=False,
784 sampler_type=sampler_type,
785 num_workers=num_workers,
786 seed=seed,
787 pin_memory=pin_memory,
788 prefetch_factor=prefetch_factor,
789 )
790 self.resume_pending = False
792 @staticmethod
793 def _build_buffer_checkpoint(
794 dataset: Any,
795 save_by_idx: bool | None,
796 ) -> IndexReplayCheckpoint | FullSampleCheckpoint:
797 """Build candidate-buffer checkpoint storage for the Dataset access mode."""
798 is_iterable = _is_iterable_dataset(dataset)
799 resolved_save_by_idx = not is_iterable if save_by_idx is None else save_by_idx
801 # Mapping Datasets have stable indices. Iterable Datasets must explicitly
802 # provide replay access before their buffer can be checkpointed by index.
803 replay_dataset = (dataset if is_iterable else
804 MappingReplayDataset(dataset, output_index_for_resume=resolved_save_by_idx))
805 supports_replay = not is_iterable or IndexReplayCheckpoint.supports(dataset)
806 if resolved_save_by_idx and not supports_replay:
807 raise ValueError("save_by_idx=True requires get_item() and output_index_for_resume")
809 if is_iterable and hasattr(dataset, "output_index_for_resume"):
810 dataset.output_index_for_resume = resolved_save_by_idx
812 if resolved_save_by_idx:
813 buffer_checkpoint = IndexReplayCheckpoint(replay_dataset)
814 else:
815 # Keep replay access only for loading an earlier index-buffer checkpoint.
816 checkpoint_replay_dataset = replay_dataset if supports_replay else None
817 buffer_checkpoint = FullSampleCheckpoint(replay_dataset, checkpoint_replay_dataset)
819 return buffer_checkpoint
821 def __iter__(self) -> Iterator[Mapping[str, Any]]:
822 """Start source iteration while retaining restored buffer state."""
824 if self.repeat and self._batch_iterator is not None:
825 return self._batch_iterator
827 if not self.resume_pending:
828 self.candidate_buffer.buffer.clear()
829 self.candidate_buffer.buffer_output_indices.clear()
830 self.candidate_buffer.buffer_token_count = 0
831 self._source_batches_since_restart = 0
833 self._batch_iterator = self._batch_data_generator()
834 self.resume_pending = False
835 return self._batch_iterator
837 def _batch_data_generator(self) -> Iterator[Mapping[str, Any]]:
838 """Lazily yield micro-batches as source samples fill the candidate buffer."""
839 # Use ready checkpointed candidates before advancing the source.
840 while self.candidate_buffer.is_ready_for_micro_batch(self.batch_size):
841 yield self._build_micro_batch()
843 while True:
844 for source_samples in self.source_dataloader:
845 buffered_samples = len(self.candidate_buffer.buffer)
847 for source_sample in source_samples:
848 self._buffer_checkpoint.put_source_item(source_sample, self.candidate_buffer)
850 if len(self.candidate_buffer.buffer) > buffered_samples:
851 self._source_batches_since_restart += 1
853 while self.candidate_buffer.is_ready_for_micro_batch(self.batch_size):
854 yield self._build_micro_batch()
856 if not self.repeat:
857 break
859 if not self._source_batches_since_restart:
860 raise ValueError("Online repeat=true source produced no batches on this rank")
862 self.source_repeat_num += 1
863 self._source_batches_since_restart = 0
864 self.source_dataloader.set_epoch(self.source_repeat_num)
865 logger.warning(
866 "Online data source exhausted; keeping buffer and repeating (source_repeat_num=%s).",
867 self.source_repeat_num,
868 )
870 # Finite sources emit remaining candidates even below readiness thresholds.
871 logger.debug(
872 "Dynamic loader source exhausted: buffered_samples=%d buffered_tokens=%d "
873 "token_budget=%d drop_last=%s; draining remaining candidates",
874 len(self.candidate_buffer.buffer), self.candidate_buffer.buffer_token_count,
875 self.candidate_buffer.token_budget, self.drop_last, enabled=True,
876 )
878 while not self.candidate_buffer.empty():
879 batch = self._build_micro_batch()
881 if not self.drop_last or batch["input_ids"].shape[0] == self.batch_size:
882 yield batch
884 logger.debug("Dynamic loader tail drained; no candidates remain", enabled=True)
886 @abstractmethod
887 def _build_batch_pipeline(self, dataset: Any) -> _BatchPipeline:
888 """Build the batching pipeline selected by the concrete Loader."""
889 raise NotImplementedError
891 def _build_micro_batch(self) -> Mapping[str, Any]:
892 """Pack up to B independent rows, pad together, and encode one batch."""
893 packed_rows = []
895 # Pack rows independently, retaining candidates that do not fit for later rows.
896 for _ in range(self.batch_size):
897 if self.candidate_buffer.empty():
898 break
900 selected_samples = self.candidate_buffer.get_micro_batch()
901 packed_rows.extend(self._batch_pipeline.finalize_selected_samples(selected_samples))
902 logger.debug(
903 "Dynamic loader selected: samples=%d token_budget=%d remaining_samples=%d remaining_tokens=%d",
904 len(packed_rows), self.candidate_buffer.token_budget, len(self.candidate_buffer.buffer),
905 self.candidate_buffer.buffer_token_count, enabled=True,
906 )
908 for row in packed_rows:
909 if row["input_ids"].shape[-1] > self.candidate_buffer.token_budget:
910 raise ValueError("Encoded packed row exceeds max_seq_len; packing_length must include encoded tokens")
912 # Choose one padding length only after the packed rows are complete.
913 batch = self.batch_collate_fn(packed_rows)
914 encoded_batch = self._batch_pipeline.encode_batch(batch)
915 return encoded_batch
917 def state_dict(self) -> dict[str, Any]:
918 """Capture the future source cursor and unconsumed dynamic buffer."""
919 state = {
920 "dp_world_size": self.dp_world_size,
921 "source_dataloader": self.source_dataloader.state_dict(),
922 "save_by_idx": self._buffer_checkpoint.save_by_idx,
923 "buffer": self._buffer_checkpoint.get_buffer_state(self.candidate_buffer),
924 "buffer_token_count": self.candidate_buffer.buffer_token_count,
925 }
927 if self.repeat:
928 # Retain the checkpoint layout previously saved by RepeatingDataLoader.
929 state = {
930 "source_epoch": self.source_repeat_num,
931 "batches_in_pass": self._source_batches_since_restart,
932 "dataloader": state,
933 }
935 checkpoint_state = copy.deepcopy(state)
937 return checkpoint_state
939 def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
940 """Restore the future source cursor and unconsumed dynamic buffer.
942 Args:
943 state_dict: Saved source progress and unconsumed candidate buffer.
944 """
945 checkpoint_state = copy.deepcopy(dict(state_dict))
946 self.source_repeat_num = checkpoint_state.get("source_epoch", 0)
947 self._source_batches_since_restart = checkpoint_state.get("batches_in_pass", 0)
948 checkpoint_state = checkpoint_state.get("dataloader", checkpoint_state)
949 saved_dp_world_size = checkpoint_state.get("dp_world_size", self.dp_world_size)
951 if saved_dp_world_size != self.dp_world_size:
952 raise ValueError(
953 "Online dataloader resume does not support DP world-size changes: "
954 f"saved_dp_world_size={saved_dp_world_size}, current_dp_world_size={self.dp_world_size}"
955 )
957 previous_save_by_idx = bool(checkpoint_state.get("save_by_idx", False))
958 saved_buffer = checkpoint_state["buffer"]
959 restored_buffer, restored_indices = self._buffer_checkpoint.restore_buffer(
960 saved_buffer,
961 previous_save_by_idx,
962 self.candidate_buffer,
963 )
965 restored_token_count = sum(sample_length for _, sample_length in restored_buffer)
967 if restored_token_count != checkpoint_state["buffer_token_count"]:
968 raise ValueError("buffer_token_count does not match the restored dynamic buffer")
970 self.source_dataloader.load_state_dict(checkpoint_state["source_dataloader"])
971 self.candidate_buffer.buffer = restored_buffer
972 self.candidate_buffer.buffer_output_indices = restored_indices
973 self.candidate_buffer.buffer_token_count = restored_token_count
974 self.resume_pending = True
975 self._batch_iterator = None
977 def set_epoch(self, epoch: int) -> None:
978 """Forward training epochs only for finite iteration.
980 Repeating iteration advances source epochs itself at EOF.
982 Args:
983 epoch: Epoch index forwarded to the source DataLoader.
984 """
986 if not self.repeat:
987 self.source_dataloader.set_epoch(epoch)
990class TokenBatchLoader(_DynamicBatchLoader):
991 """Select fully encoded samples within one token budget."""
993 def _build_batch_pipeline(self, dataset: Any) -> _BatchPipeline:
994 """Build token-budget batching for fully encoded Dataset samples."""
995 batch_pipeline = _TokenBatchPipeline()
996 return batch_pipeline
999class OmniPackingLoader(_DynamicBatchLoader):
1000 """Pack selected samples after applying the Dataset encoding lifecycle."""
1002 def _build_batch_pipeline(self, dataset: Any) -> _BatchPipeline:
1003 """Build packing around the normalized Dataset encoding lifecycle."""
1004 batch_pipeline = _OmniPackingPipeline.from_dataset(dataset)
1005 return batch_pipeline
1008# Compatibility name for callers of the pre-refactor dynamic text loader.
1009DynamicBatchDataLoader = TokenBatchLoader