|
| 1 | +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. |
| 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 | +"""Canonical-grid batch sampling for MegatronMIMO scalable data-parallel reads. |
| 16 | +
|
| 17 | +With ``megatron_mimo_scalable_dp`` every module's loaders must materialize the same |
| 18 | +ordered global micro-batch, because the ``BridgeCommunicator`` routes modality |
| 19 | +embeddings to language ranks by contiguous position along the batch dim. A sampler's |
| 20 | +shard assignment depends on its ``(data_parallel_rank, data_parallel_size, |
| 21 | +micro_batch_size)``, so modules with different DP sizes cannot shard by their own DP: |
| 22 | +a shuffling sampler would hand them different sample sets. Instead, all loaders shard |
| 23 | +on one shared **canonical grid** — the least common multiple of the module DP sizes. |
| 24 | +A rank whose module has DP size ``d`` covers ``grid // d`` consecutive canonical |
| 25 | +groups and concatenates their windows, so concatenating any module's rank batches |
| 26 | +reproduces the identical ordered global micro-batch under any deterministic sampler |
| 27 | +(``single`` and ``cyclic`` included; the shuffle seed derives from the epoch alone). |
| 28 | +""" |
| 29 | + |
| 30 | +from __future__ import annotations |
| 31 | + |
| 32 | +import math |
| 33 | +from typing import Callable, Iterator |
| 34 | + |
| 35 | +from torch.utils.data import DataLoader, Dataset |
| 36 | + |
| 37 | +from megatron.bridge.data.samplers import MegatronPretrainingRandomSampler, MegatronPretrainingSampler |
| 38 | + |
| 39 | + |
| 40 | +def canonical_grid_size(module_dp_sizes: list[int]) -> int: |
| 41 | + """Return the shared sampler grid size: the LCM of every module's DP size.""" |
| 42 | + if not module_dp_sizes or any(dp is None or dp < 1 for dp in module_dp_sizes): |
| 43 | + raise ValueError(f"module DP sizes must be positive integers (got {module_dp_sizes}).") |
| 44 | + return math.lcm(*module_dp_sizes) |
| 45 | + |
| 46 | + |
| 47 | +def covered_canonical_groups(dp_rank: int, dp_size: int, grid_size: int) -> list[int]: |
| 48 | + """Return the canonical groups this rank reads. |
| 49 | +
|
| 50 | + The groups are the ``grid_size // dp_size`` consecutive slots matching the |
| 51 | + contiguous batch-dim chunk the ``BridgeCommunicator`` routes to this DP rank. |
| 52 | + """ |
| 53 | + if grid_size % dp_size != 0: |
| 54 | + raise ValueError( |
| 55 | + f"canonical grid size ({grid_size}) is not divisible by the module DP size ({dp_size}); " |
| 56 | + "module DP sizes must divide their least common multiple." |
| 57 | + ) |
| 58 | + span = grid_size // dp_size |
| 59 | + return list(range(dp_rank * span, (dp_rank + 1) * span)) |
| 60 | + |
| 61 | + |
| 62 | +class CanonicalGroupBatchSampler: |
| 63 | + """Concatenate per-canonical-group Megatron samplers into one batch sampler. |
| 64 | +
|
| 65 | + Holds one flat sampler per covered canonical group, all built with the same |
| 66 | + ``(micro_batch // grid, grid)`` geometry and the same global ``consumed_samples``. |
| 67 | + Each yield emits the groups' current windows concatenated in group order. Group |
| 68 | + streams are functions of ``(group, grid, micro_batch, consumed, epoch seed)`` only, |
| 69 | + so every rank covering group ``g`` — in any module — sees the identical stream. |
| 70 | + """ |
| 71 | + |
| 72 | + def __init__(self, samplers: list) -> None: |
| 73 | + if not samplers: |
| 74 | + raise ValueError("CanonicalGroupBatchSampler needs at least one group sampler.") |
| 75 | + self.samplers = samplers |
| 76 | + |
| 77 | + def __len__(self) -> int: |
| 78 | + """Match the flat Megatron samplers' convention of reporting total samples.""" |
| 79 | + return min(len(sampler) for sampler in self.samplers) |
| 80 | + |
| 81 | + def __iter__(self) -> Iterator[list[int]]: |
| 82 | + """Yield one concatenated index window per micro-batch.""" |
| 83 | + iterators = [iter(sampler) for sampler in self.samplers] |
| 84 | + while True: |
| 85 | + window: list[int] = [] |
| 86 | + for iterator in iterators: |
| 87 | + group_batch = next(iterator, None) |
| 88 | + if group_batch is None: |
| 89 | + # Groups share one truncated geometry, so they exhaust on the same window. |
| 90 | + return |
| 91 | + window.extend(group_batch) |
| 92 | + yield window |
| 93 | + |
| 94 | + |
| 95 | +def build_canonical_group_batch_sampler( |
| 96 | + *, |
| 97 | + dataloader_type: str, |
| 98 | + dataset: Dataset, |
| 99 | + consumed_samples: int, |
| 100 | + micro_batch_size: int, |
| 101 | + grid_size: int, |
| 102 | + groups: list[int], |
| 103 | + data_sharding: bool, |
| 104 | + drop_last: bool = True, |
| 105 | +) -> CanonicalGroupBatchSampler: |
| 106 | + """Build this rank's canonical-group batch sampler for scalable MIMO reads. |
| 107 | +
|
| 108 | + Args: |
| 109 | + dataloader_type: ``"single"`` or ``"cyclic"``; other types have no shard |
| 110 | + assignment that is consistent across modules and are rejected. |
| 111 | + dataset: The dataset the loader reads. |
| 112 | + consumed_samples: Global consumed-sample count, exactly as the flat samplers |
| 113 | + expect (used for resume / epoch derivation). |
| 114 | + micro_batch_size: The global micro-batch size (not the per-rank share). |
| 115 | + grid_size: Canonical grid size from :func:`canonical_grid_size`. |
| 116 | + groups: This rank's groups from :func:`covered_canonical_groups`. |
| 117 | + data_sharding: Passed through to the cyclic sampler. |
| 118 | + drop_last: Must stay ``True``: a partial final window gives the groups |
| 119 | + unequal shares and breaks the positional routing. |
| 120 | +
|
| 121 | + Returns: |
| 122 | + The merged batch sampler for ``torch.utils.data.DataLoader(batch_sampler=...)``. |
| 123 | + """ |
| 124 | + if not drop_last: |
| 125 | + raise ValueError("megatron_mimo_scalable_dp requires drop_last=True (partial windows misalign modules).") |
| 126 | + if micro_batch_size % grid_size != 0: |
| 127 | + raise ValueError( |
| 128 | + f"micro_batch_size ({micro_batch_size}) must be divisible by the canonical grid size ({grid_size})." |
| 129 | + ) |
| 130 | + group_micro_batch_size = micro_batch_size // grid_size |
| 131 | + # Truncate to whole global micro-batches: the flat samplers round their active range at |
| 132 | + # per-group granularity, which diverges per group for a non-multiple dataset size (the |
| 133 | + # cyclic data_sharding=False stride would give groups unequal window counts). |
| 134 | + total_samples = (len(dataset) // micro_batch_size) * micro_batch_size |
| 135 | + if total_samples <= 0: |
| 136 | + raise ValueError(f"dataset ({len(dataset)} samples) is smaller than one micro-batch ({micro_batch_size}).") |
| 137 | + |
| 138 | + samplers = [] |
| 139 | + for group in groups: |
| 140 | + if dataloader_type == "single": |
| 141 | + samplers.append( |
| 142 | + MegatronPretrainingSampler( |
| 143 | + total_samples=total_samples, |
| 144 | + consumed_samples=consumed_samples, |
| 145 | + micro_batch_size=group_micro_batch_size, |
| 146 | + data_parallel_rank=group, |
| 147 | + data_parallel_size=grid_size, |
| 148 | + drop_last=True, |
| 149 | + ) |
| 150 | + ) |
| 151 | + elif dataloader_type == "cyclic": |
| 152 | + samplers.append( |
| 153 | + MegatronPretrainingRandomSampler( |
| 154 | + dataset, |
| 155 | + total_samples=total_samples, |
| 156 | + consumed_samples=consumed_samples, |
| 157 | + micro_batch_size=group_micro_batch_size, |
| 158 | + data_parallel_rank=group, |
| 159 | + data_parallel_size=grid_size, |
| 160 | + data_sharding=data_sharding, |
| 161 | + ) |
| 162 | + ) |
| 163 | + else: |
| 164 | + raise ValueError( |
| 165 | + f"megatron_mimo_scalable_dp supports dataloader_type 'single' or 'cyclic' (got {dataloader_type!r})." |
| 166 | + ) |
| 167 | + return CanonicalGroupBatchSampler(samplers) |
| 168 | + |
| 169 | + |
| 170 | +def build_canonical_mimo_data_loader( |
| 171 | + dataset: Dataset | None, |
| 172 | + *, |
| 173 | + consumed_samples: int, |
| 174 | + dataloader_type: str, |
| 175 | + micro_batch_size: int, |
| 176 | + module_dp_sizes: list[int], |
| 177 | + dp_rank: int, |
| 178 | + dp_size: int, |
| 179 | + data_sharding: bool, |
| 180 | + drop_last: bool, |
| 181 | + num_workers: int, |
| 182 | + pin_memory: bool, |
| 183 | + collate_fn: Callable | None, |
| 184 | + persistent_workers: bool, |
| 185 | +) -> DataLoader | None: |
| 186 | + """Build this rank's read-sharded DataLoader for scalable MegatronMIMO reads. |
| 187 | +
|
| 188 | + Computes the canonical grid from ``module_dp_sizes``, derives this rank's covered |
| 189 | + groups from its module-local ``(dp_rank, dp_size)``, and wraps the merged batch |
| 190 | + sampler in a ``DataLoader``. Returns ``None`` when ``dataset`` is ``None``. |
| 191 | + """ |
| 192 | + if dataset is None: |
| 193 | + return None |
| 194 | + grid = canonical_grid_size(module_dp_sizes) |
| 195 | + groups = covered_canonical_groups(dp_rank, dp_size, grid) |
| 196 | + batch_sampler = build_canonical_group_batch_sampler( |
| 197 | + dataloader_type=dataloader_type, |
| 198 | + dataset=dataset, |
| 199 | + consumed_samples=consumed_samples, |
| 200 | + micro_batch_size=micro_batch_size, |
| 201 | + grid_size=grid, |
| 202 | + groups=groups, |
| 203 | + data_sharding=data_sharding, |
| 204 | + drop_last=drop_last, |
| 205 | + ) |
| 206 | + return DataLoader( |
| 207 | + dataset, |
| 208 | + batch_sampler=batch_sampler, |
| 209 | + num_workers=num_workers, |
| 210 | + pin_memory=pin_memory, |
| 211 | + collate_fn=collate_fn, |
| 212 | + persistent_workers=persistent_workers, |
| 213 | + ) |
0 commit comments