Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / online / iterable.py: 19%
242 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 streaming Online sources and their local/global blend policy."""
17from __future__ import annotations
19import random
20from collections.abc import Callable, Mapping, Sequence
21from copy import deepcopy
22from dataclasses import replace
23from typing import Any
25from torch.utils.data import IterableDataset
27from hyper_parallel.data.constants import ONLINE_BLEND_STRATEGIES
28from hyper_parallel.data.online.source import OnlineDataPath, _OnlineSourceBuilder
29from hyper_parallel.data.parallel import (
30 DataLoaderParallelContext,
31 build_dataset_for_dataloader,
32 split_iterable_dataset_by_dp,
33)
35SampleTransform = Callable[[Any], list[Any]]
38def build_online_iterable_source(
39 *,
40 data_config: Mapping[str, Any],
41 data_path: OnlineDataPath | None = None,
42 dataloader_context: DataLoaderParallelContext | None = None,
43 sample_filter: Callable[[Mapping[str, Any]], bool] | None = None,
44) -> Any:
45 """Build a locally shuffled and optionally DP-sharded Online stream.
47 Args:
48 data_config: Online streaming source options.
49 data_path: Local path or Hub dataset ID. Use ``data_config.sources``
50 instead for multiple sources.
51 dataloader_context: Optional DataLoader ownership and DP policy.
52 sample_filter: Optional raw-sample predicate applied before shuffling.
54 Returns:
55 One Iterable Dataset on each DataLoader-owning rank.
56 """
57 normalized_context = dataloader_context or DataLoaderParallelContext()
58 if normalized_context.data_index_cache:
59 normalized_context = replace(normalized_context, data_index_cache=False)
61 dataset_builder = _OnlineIterableSourceBuilder(data_path, data_config, normalized_context)
63 def dataset_factory() -> Any:
64 """Build the configured single-source or multi-source stream."""
65 iterable_dataset = dataset_builder.build_source(sample_filter=sample_filter)
66 return iterable_dataset
68 iterable_source = build_dataset_for_dataloader(
69 dataset_factory,
70 normalized_context,
71 barrier_needed=False,
72 )
73 return iterable_source
76def _supports_output_index_for_resume(dataset: Any) -> bool:
77 """Return whether a Dataset can emit and rebuild stable output indices."""
78 get_item = getattr(dataset, "get_item", None)
79 supports_output_index = callable(get_item) and hasattr(dataset, "output_index_for_resume")
80 return supports_output_index
83class IterableTransformDataset(IterableDataset):
84 """Apply a sample transform lazily while preserving streaming source state."""
86 @classmethod
87 def apply(cls, source_dataset: Any, transform: SampleTransform) -> Any:
88 """Transform one Iterable Dataset built on a DataLoader-owning rank.
90 Args:
91 source_dataset: Iterable Dataset, or ``None`` on a non-owning rank.
92 transform: Transform from one RawSample to zero, one, or many ModelSamples.
94 Returns:
95 A transformed Iterable Dataset, or ``None`` on a non-owning rank.
96 """
97 if source_dataset is None:
98 return None
100 iterable_dataset = cls(source_dataset, transform)
101 return iterable_dataset
103 def __init__(self, source_dataset: Any, transform: SampleTransform) -> None:
104 """Store the streaming source and its lazy sample transform."""
105 self.source_dataset = source_dataset
106 self.transform = transform
107 self._source_start_state = deepcopy(self.state_dict())
108 self._source_was_restored = False
110 @property
111 def output_index_for_resume(self) -> bool:
112 """Return whether the upstream source emits stable output indices."""
113 if not _supports_output_index_for_resume(self.source_dataset):
114 raise AttributeError("The upstream iterable does not support output-index resume")
116 output_index_enabled = bool(self.source_dataset.output_index_for_resume)
117 return output_index_enabled
119 @output_index_for_resume.setter
120 def output_index_for_resume(self, value: bool) -> None:
121 """Forward output-index mode to a replayable upstream source."""
122 if not _supports_output_index_for_resume(self.source_dataset):
123 raise ValueError("The upstream iterable does not support output-index resume")
125 self.source_dataset.output_index_for_resume = value
127 def get_item(self, output_index: Any) -> list[Any]:
128 """Rebuild and transform one upstream item from its stable output index."""
129 if not _supports_output_index_for_resume(self.source_dataset):
130 raise AttributeError("The upstream iterable does not support get_item")
132 raw_sample = self.source_dataset.get_item(output_index)
133 transformed_samples = self._transform_sample(raw_sample)
134 return transformed_samples
136 def __iter__(self) -> Any:
137 """Transform source records lazily while preserving source order."""
138 output_index_enabled = (
139 _supports_output_index_for_resume(self.source_dataset)
140 and bool(self.source_dataset.output_index_for_resume)
141 )
142 for source_item in self.source_dataset:
143 if output_index_enabled:
144 raw_sample, output_index = source_item
145 else:
146 raw_sample = source_item
148 transformed_samples = self._transform_sample(raw_sample)
149 if not transformed_samples:
150 continue
151 if output_index_enabled:
152 yield transformed_samples, output_index
153 elif len(transformed_samples) == 1:
154 yield transformed_samples[0]
155 else:
156 yield transformed_samples
158 def state_dict(self) -> dict[str, Any]:
159 """Forward checkpoint state to a stateful upstream stream."""
160 state_builder = getattr(self.source_dataset, "state_dict", None)
161 source_state = {}
162 if callable(state_builder):
163 source_state = state_builder()
164 transform_state = {"source_dataset": source_state}
165 return transform_state
167 def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
168 """Restore checkpoint state through the upstream stream interface."""
169 state_loader = getattr(self.source_dataset, "load_state_dict", None)
170 if not callable(state_loader):
171 raise ValueError("Online iterable source does not support load_state_dict")
173 state_loader(state_dict["source_dataset"])
174 self._source_was_restored = True
176 def set_epoch(self, epoch: int) -> None:
177 """Forward deterministic epoch state when supported upstream."""
178 # HF streams retain their restore offset across iterations; use it for only the saved pass.
179 if self._source_was_restored:
180 self.load_state_dict(self._source_start_state)
181 self._source_was_restored = False
183 epoch_setter = getattr(self.source_dataset, "set_epoch", None)
185 if callable(epoch_setter):
186 epoch_setter(epoch)
188 def _transform_sample(self, raw_sample: Any) -> list[Any]:
189 """Transform one RawSample and enforce the zero/one/many contract."""
190 transformed_samples = self.transform(raw_sample)
191 if not isinstance(transformed_samples, list):
192 raise TypeError("Online Iterable sample transform must return a list")
194 return transformed_samples
197class _LocalWeightedIterableDataset(IterableDataset):
198 """Choose among already-sharded Iterable sources on the local rank."""
200 def __init__(
201 self,
202 source_datasets: Sequence[Any],
203 weights: Sequence[float],
204 *,
205 random_seed: int,
206 stopping_strategy: str,
207 vary_by_epoch: bool,
208 ) -> None:
209 """Store the rank-local sources and weighted selection policy."""
210 self.source_datasets = tuple(source_datasets)
211 self.weights = tuple(weights)
212 self.random_seed = random_seed
213 self.stopping_strategy = stopping_strategy
214 self.vary_by_epoch = vary_by_epoch
215 self.epoch = 0
216 self._random_state = None
217 self._active_indices = None
218 self._exhausted_once = None
220 def __iter__(self) -> Any:
221 """Yield samples according to the configured local source weights."""
222 source_epoch = getattr(self.source_datasets[0], "epoch", self.epoch)
223 epoch = 0
224 if self.vary_by_epoch:
225 epoch = int(source_epoch)
227 random_generator = random.Random(self.random_seed + epoch)
228 if self._random_state is not None:
229 random_generator.setstate(self._random_state)
231 source_iterators = []
232 for source_dataset in self.source_datasets:
233 source_iterators.append(iter(source_dataset))
235 if self._active_indices is None:
236 active_indices = list(range(len(source_iterators)))
237 else:
238 active_indices = list(self._active_indices)
240 if self._exhausted_once is None:
241 exhausted_once = set()
242 else:
243 exhausted_once = set(self._exhausted_once)
245 while active_indices:
246 active_weights = []
247 for active_index in active_indices:
248 active_weights.append(self.weights[active_index])
250 source_index = random_generator.choices(active_indices, weights=active_weights, k=1)[0]
251 try:
252 source_sample = next(source_iterators[source_index])
253 except StopIteration:
254 if self.stopping_strategy == "first_exhausted":
255 self._clear_iteration_state()
256 return
258 exhausted_once.add(source_index)
259 if self.stopping_strategy == "all_exhausted_without_replacement":
260 active_indices.remove(source_index)
261 self._save_iteration_state(random_generator, active_indices, exhausted_once)
262 continue
264 if len(exhausted_once) == len(source_iterators):
265 self._clear_iteration_state()
266 return
268 source_iterators[source_index] = iter(self.source_datasets[source_index])
269 self._save_iteration_state(random_generator, active_indices, exhausted_once)
270 continue
272 self._save_iteration_state(random_generator, active_indices, exhausted_once)
273 yield source_sample
275 self._clear_iteration_state()
277 def set_epoch(self, epoch: int) -> None:
278 """Set the local blend epoch and forward it to every source."""
279 self.epoch = epoch
280 self._clear_iteration_state()
281 for source_dataset in self.source_datasets:
282 epoch_setter = getattr(source_dataset, "set_epoch", None)
283 if callable(epoch_setter):
284 epoch_setter(epoch)
286 def state_dict(self) -> dict[str, Any]:
287 """Save source cursors and the local weighted-selection cursor."""
288 source_states = []
289 for source_dataset in self.source_datasets:
290 state_builder = getattr(source_dataset, "state_dict", None)
291 source_state = None
292 if callable(state_builder):
293 source_state = state_builder()
294 source_states.append(source_state)
296 source_epoch = getattr(self.source_datasets[0], "epoch", self.epoch)
297 dataset_state = {
298 "epoch": int(source_epoch),
299 "random_state": self._random_state,
300 "active_indices": self._active_indices,
301 "exhausted_once": self._exhausted_once,
302 "sources": source_states,
303 }
304 return dataset_state
306 def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
307 """Restore source cursors and the local weighted-selection cursor."""
308 source_states = state_dict["sources"]
309 if len(source_states) != len(self.source_datasets):
310 raise ValueError("Online source count does not match the saved local blend state")
312 for source_dataset, source_state in zip(self.source_datasets, source_states):
313 if source_state is None:
314 continue
315 state_loader = getattr(source_dataset, "load_state_dict", None)
316 if not callable(state_loader):
317 raise ValueError("Online iterable source does not support load_state_dict")
318 state_loader(source_state)
320 self.epoch = int(state_dict["epoch"])
321 self._random_state = state_dict["random_state"]
322 self._active_indices = state_dict["active_indices"]
323 self._exhausted_once = state_dict["exhausted_once"]
325 def _save_iteration_state(
326 self,
327 random_generator: random.Random,
328 active_indices: Sequence[int],
329 exhausted_once: set[int],
330 ) -> None:
331 """Record the local source-selection cursor after one decision."""
332 self._random_state = random_generator.getstate()
333 self._active_indices = tuple(active_indices)
334 self._exhausted_once = tuple(sorted(exhausted_once))
336 def _clear_iteration_state(self) -> None:
337 """Reset the local source-selection cursor for a new epoch."""
338 self._random_state = None
339 self._active_indices = None
340 self._exhausted_once = None
343class _OnlineIterableSourceBuilder(_OnlineSourceBuilder):
344 """Build the rank-local or globally interleaved streaming source graph."""
346 def __init__(
347 self,
348 data_path: OnlineDataPath | None,
349 data_config: Mapping[str, Any],
350 dataloader_context: DataLoaderParallelContext,
351 ) -> None:
352 """Store source configuration and DataLoader ownership."""
353 super().__init__(data_path, data_config)
354 self.dataloader_context = dataloader_context
356 def build_source(
357 self,
358 *,
359 sample_filter: Callable[[Mapping[str, Any]], bool] | None = None,
360 ) -> Any:
361 """Load Iterable sources and apply their shard, shuffle, and blend policy."""
362 source_loaders, weights = self._create_source_loaders()
363 source_datasets = []
364 for source_loader in source_loaders:
365 source_dataset = source_loader.load(streaming=True, sample_filter=sample_filter)
366 if isinstance(source_dataset, tuple):
367 raise ValueError("Online Iterable Dataset requires one train source per entry")
368 source_datasets.append(source_dataset)
370 if len(source_datasets) == 1:
371 iterable_dataset = self._prepare_local_source(source_datasets[0])
372 return iterable_dataset
374 blend_strategy = str(self.data_config.get("blend_strategy", "local_weighted"))
375 if blend_strategy not in ONLINE_BLEND_STRATEGIES:
376 raise ValueError(
377 f"Unsupported Online blend_strategy {blend_strategy!r}; "
378 f"expected one of {ONLINE_BLEND_STRATEGIES!r}"
379 )
381 if blend_strategy == "local_weighted":
382 local_sources = []
383 for source_dataset in source_datasets:
384 local_source = self._prepare_local_source(source_dataset)
385 local_sources.append(local_source)
387 iterable_dataset = _LocalWeightedIterableDataset(
388 local_sources,
389 weights,
390 random_seed=self._random_seed,
391 stopping_strategy=self._stopping_strategy,
392 vary_by_epoch=self._shuffle_enabled,
393 )
394 return iterable_dataset
396 shuffled_sources = []
397 for source_dataset in source_datasets:
398 shuffled_source = self._shuffle(source_dataset)
399 shuffled_sources.append(shuffled_source)
401 iterable_dataset = self._interleave_sources(shuffled_sources, weights)
402 if self._shuffle_enabled:
403 # buffer_size=1 preserves output order while making set_epoch reseed the full source graph.
404 iterable_dataset = iterable_dataset.shuffle(seed=self._random_seed, buffer_size=1)
405 if self._split_by_data_parallel:
406 iterable_dataset = split_iterable_dataset_by_dp(iterable_dataset, self.dataloader_context)
407 return iterable_dataset
409 @property
410 def _shuffle_enabled(self) -> bool:
411 """Return whether Iterable sources use local buffer shuffle."""
412 return bool(self.data_config.get("shuffle", True))
414 @property
415 def _split_by_data_parallel(self) -> bool:
416 """Return whether Iterable sources own DP sharding."""
417 return bool(self.data_config.get("split_by_data_parallel", True))
419 def _prepare_local_source(self, source_dataset: Any) -> Any:
420 """Apply per-source DP sharding before local buffer shuffle."""
421 if self._split_by_data_parallel:
422 source_dataset = split_iterable_dataset_by_dp(source_dataset, self.dataloader_context)
423 local_dataset = self._shuffle(source_dataset)
424 return local_dataset
426 def _shuffle(self, source_dataset: Any) -> Any:
427 """Apply deterministic buffer shuffle when configured."""
428 if not self._shuffle_enabled:
429 return source_dataset
431 buffer_size = int(self.data_config.get("shuffle_buffer_size", 10_000))
432 if buffer_size <= 0:
433 raise ValueError("Online shuffle_buffer_size must be positive")
435 shuffled_dataset = source_dataset.shuffle(seed=self._random_seed, buffer_size=buffer_size)
436 return shuffled_dataset
439__all__ = [
440 "IterableTransformDataset",
441 "build_online_iterable_source",
442]