Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / batching / get_batch.py: 87%
225 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 one model and loss batch from a DataLoader iterator."""
17from __future__ import annotations
19from collections.abc import Mapping
20from typing import Any
22import torch
24from hyper_parallel.data.batching.runtime_input import (
25 AttentionRuntime,
26 IndexedBoundaryResolver,
27 OnlineBoundaryResolver,
28 RuntimeInputAdapter,
29)
30from hyper_parallel.data.parallel.batch_parallel import broadcast_batch_mapping
31from hyper_parallel.data.constants import (
32 OMNI_CP_TOKEN_FIELDS,
33 OMNI_INTERNAL_FIELDS,
34 OMNI_LOSS_INPUT_FIELDS,
35)
36from hyper_parallel.data.dataset_logging import get_dataset_logger
37from hyper_parallel.data.offline.data_config import resolve_dataset_type
38from hyper_parallel.data.offline.dataset import SFTFromMRDataset
39from hyper_parallel.data.parallel import (
40 CPBatchSharder,
41 DataLoaderParallelContext,
42 TPBatchBroadcaster,
43 create_dataloader_parallel_context,
44)
46logger = get_dataset_logger(__name__)
49class OmniParallelBatch:
50 """Validate collate-aligned Omni batches, shard over CP, and broadcast over TP."""
52 def __init__(
53 self,
54 *,
55 mesh_context: Any,
56 device: Any,
57 pp_shared_data: bool = False,
58 mpipe: bool = False,
59 runtime_input_adapter: RuntimeInputAdapter | None = None,
60 dataloader_context: DataLoaderParallelContext | None = None,
61 data_config: Mapping[str, Any] | None = None,
62 ) -> None:
63 """Create the DataLoader ownership and TP/CP transport context.
65 Args:
66 mesh_context: Trainer mesh exposing TP, CP, and PP sizes.
67 device: Destination model device.
68 pp_shared_data: Whether pipeline stages share the source batch.
69 mpipe: Read vision payloads on their MPipe owner and share decoder fields.
70 runtime_input_adapter: Provider of additional forward inputs.
71 data_config: Dataset cache settings used by DataLoader ownership.
72 dataloader_context: Shared ownership and transport policy from the Trainer.
73 """
74 # if encoder_dp:
75 # raise NotImplementedError("OmniParallelBatch encoder_dp image-bucket distribution is not implemented")
77 if runtime_input_adapter is not None and not isinstance(runtime_input_adapter, RuntimeInputAdapter):
78 raise TypeError("OmniParallelBatch runtime_input_adapter must be a RuntimeInputAdapter")
80 if pp_shared_data:
81 raise NotImplementedError("OmniParallelBatch does not support pp_shared_data")
82 # Each PP coordinate reads the same deterministic DP sample stream;
83 # TP broadcast and CP slicing remain local to that physical stage.
85 source_config = data_config or {}
86 self.parallel_context = dataloader_context or create_dataloader_parallel_context(
87 mesh_context,
88 data_index_cache=bool(source_config.get("data_index_cache", False)),
89 shared_storage=not bool(source_config.get("no_shared_storage", False)),
90 )
91 if not self.parallel_context.distributed_enabled and (
92 int(getattr(mesh_context, "tp_size", 1)) > 1 or int(getattr(mesh_context, "cp_size", 1)) > 1
93 ):
94 raise ValueError("OmniParallelBatch requires an initialized process group for TP or CP")
96 self.mpipe_mesh = mesh_context.pp_mesh if mpipe else None
97 self.device = device
98 self.sequence_parallel = bool(mesh_context.sequence_parallel)
99 self.runtime_input_adapter = runtime_input_adapter
100 self.cp_sharder = CPBatchSharder(self.parallel_context, token_fields=OMNI_CP_TOKEN_FIELDS)
101 self.tp_broadcaster = TPBatchBroadcaster(self.parallel_context, device)
102 self.batch_transport = None
103 self._batch_index = 0
105 def __call__(
106 self,
107 data_iterator: Any,
108 *,
109 external_batch: Mapping[str, Any] | None = None,
110 mpipe_owner: int | None = None,
111 ) -> tuple[dict[str, Any], dict[str, Any]]:
112 """Read on source owners, slice for CP, and distribute only if needed."""
113 self._batch_index += 1
114 local_batch = None
116 if self.parallel_context.build_on_rank():
117 logger.debug("Omni get_batch: batch=%d source_read_begin", self._batch_index, enabled=True)
118 source_batch = external_batch if external_batch is not None else next(data_iterator)
120 if not isinstance(source_batch, Mapping):
121 raise TypeError("Omni DataLoader must yield a mapping batch")
123 if self.mpipe_mesh is not None:
124 if mpipe_owner is None:
125 raise ValueError("MPipe batch requires its visual owner rank")
126 fields = None
127 pixels = None
128 if self.mpipe_mesh.get_local_rank() == mpipe_owner:
129 fields = dict(source_batch)
130 pixels = fields.pop("pixel_values", None)
131 source_batch = broadcast_batch_mapping(fields, self.mpipe_mesh.get_group(), mpipe_owner, self.device)
132 if pixels is not None:
133 source_batch["pixel_values"] = pixels
134 normalized_batch = self._normalize_source_batch(source_batch)
135 local_batch = self.cp_sharder.shard(normalized_batch)
136 logger.debug(
137 "Omni get_batch: batch=%d source_ready global_shape=%s local_shape=%s tp=%d cp=%d cp_rank=%d",
138 self._batch_index, tuple(normalized_batch["input_ids"].shape),
139 tuple(local_batch["input_ids"].shape), self.parallel_context.tp_world_size,
140 self.parallel_context.cp_world_size, self.parallel_context.cp_rank, enabled=True,
141 )
143 transport_inputs = {}
145 if self.batch_transport is None:
146 device_batch = self.tp_broadcaster.broadcast(local_batch, broadcast_all_fields=True)
147 else:
148 device_batch, transport_inputs = self.batch_transport(local_batch, self.tp_broadcaster)
150 runtime_inputs = self._build_runtime_inputs(device_batch)
151 model_inputs, loss_inputs = self._split_model_and_loss_inputs(device_batch)
153 if set(transport_inputs).intersection((*device_batch, *runtime_inputs)):
154 raise ValueError("batch transport cannot replace Omni model or runtime inputs")
156 model_inputs.update(runtime_inputs)
157 model_inputs.update(transport_inputs)
158 # Shapes are host metadata; inspecting device tensor values here can stall collectives.
159 logger.debug(
160 "Omni get_batch: batch=%d transport_ready fields=%s runtime_fields=%s",
161 self._batch_index,
162 {field: tuple(value.shape) for field, value in device_batch.items() if torch.is_tensor(value)},
163 list(runtime_inputs), enabled=True,
164 )
166 return model_inputs, loss_inputs
168 @staticmethod
169 def _normalize_source_batch(source_batch: Mapping[str, Any]) -> dict[str, Any]:
170 """Validate required fields and derive the default loss mask."""
171 batch = dict(source_batch)
172 if "input_ids" not in batch:
173 raise ValueError("Omni batch must contain input_ids")
175 if "labels" not in batch:
176 raise ValueError("Omni batch must contain labels")
178 if "loss_mask" not in batch:
179 batch["loss_mask"] = batch["labels"] >= 0
180 if "cu_seq_lens" in batch:
181 batch["cu_seq_lens"] = batch["cu_seq_lens"].reshape(-1)
182 return batch
184 def _build_runtime_inputs(self, batch: Mapping[str, Any]) -> dict[str, Any]:
185 """Call the configured model hook after TP/CP batch transport."""
186 if self.runtime_input_adapter is None:
187 return {}
189 runtime_inputs = self.runtime_input_adapter.build(
190 batch=batch, parallel_context=self.parallel_context,
191 options={"sequence_parallel": self.sequence_parallel},
192 )
193 collisions = set(batch).intersection(runtime_inputs)
194 if collisions:
195 raise ValueError(
196 "runtime inputs cannot replace Omni model inputs: "
197 f"{sorted(collisions)}"
198 )
200 return runtime_inputs
202 @staticmethod
203 def _split_model_and_loss_inputs(
204 batch: Mapping[str, Any],
205 ) -> tuple[dict[str, Any], dict[str, Any]]:
206 """Keep processor fields as model inputs and isolate internal metadata."""
207 model_inputs = {}
208 loss_inputs = {}
209 for field, value in batch.items():
210 if field not in OMNI_INTERNAL_FIELDS:
211 model_inputs[field] = value
212 if field in OMNI_LOSS_INPUT_FIELDS:
213 loss_inputs[field] = value
214 return model_inputs, loss_inputs
217class TextParallelBatch:
218 """Define the DataLoader-to-forward-batch processing boundary.
220 The runtime reads data only on TP rank zero at every CP coordinate, keeps
221 global sequence boundaries, shards token fields for CP, broadcasts the
222 local fields across TP, and then builds common attention inputs.
223 """
225 def __init__(
226 self,
227 mesh_context: Any,
228 device: Any,
229 tokenizer: Any,
230 data_config: Mapping[str, Any],
231 pp_shared_data: bool,
232 *,
233 source_type: str,
234 attention_mode: str = "dense",
235 causal: bool = True,
236 sliding_window: int | None = None,
237 reset_position_ids: bool = False,
238 reset_attention_mask: bool = False,
239 eod_mask_loss: bool = False,
240 runtime_input_adapter: RuntimeInputAdapter | None = None,
241 dataloader_context: DataLoaderParallelContext | None = None,
242 ) -> None:
243 """Initialize the batch runtime and its parallel execution context.
245 Args:
246 mesh_context: Trainer mesh used to create DataLoader parallel state.
247 device: Device receiving the DataLoader batch.
248 tokenizer: Tokenizer providing EOD and padding token semantics.
249 data_config: Dataset options used to build runtime LTR fields.
250 pp_shared_data: Whether pipeline stages share the prepared batch.
251 source_type: ``online``, ``offline``, or ``packed_text`` batch contract.
252 Packed text provides input_ids, shifted labels, and explicit cu_seq_lens.
253 attention_mode: ``dense`` or ``compressed`` attention representation.
254 causal: Whether attention uses left-to-right causal semantics.
255 sliding_window: Sliding-window size, or ``None`` for full attention.
256 reset_position_ids: Whether positions restart at sequence boundaries.
257 reset_attention_mask: Whether EOD starts an independent attention sequence.
258 eod_mask_loss: Whether EOD tokens are excluded from the loss.
259 runtime_input_adapter: Optional model-owned forward-input extension.
260 dataloader_context: Shared ownership and transport policy from the Trainer.
261 """
262 # pylint: disable=too-many-locals
264 self.parallel_context = dataloader_context or create_dataloader_parallel_context(
265 mesh_context,
266 data_index_cache=bool(data_config.get("data_index_cache", False)),
267 shared_storage=not bool(data_config.get("no_shared_storage", False)),
268 )
269 self.device = device
270 self.tokenizer = tokenizer
271 self.data_config = dict(data_config)
272 self.source_type = source_type
273 dataset_spec = data_config.get("low_level_dataset")
274 self.is_sft_dataset = (source_type == "offline" and dataset_spec is not None
275 and issubclass(resolve_dataset_type(dataset_spec), SFTFromMRDataset))
276 self.causal = causal
277 self.sliding_window = sliding_window
279 if runtime_input_adapter is not None and not isinstance(
280 runtime_input_adapter, RuntimeInputAdapter
281 ):
282 raise TypeError("TextParallelBatch runtime_input_adapter must be a RuntimeInputAdapter")
284 self.runtime_input_adapter = runtime_input_adapter
285 self._batch_flow_logged = False
287 self.boundary_resolver = self._build_boundary_resolver(source_type, tokenizer)
289 self.pp_shared_data = pp_shared_data
290 self.labels_are_shifted = bool(self.data_config.get("labels_are_shifted", True))
291 create_attention_mask = bool(
292 self.data_config.get("create_attention_mask_in_dataloader", attention_mode == "dense")
293 )
294 self.eod_mask_loss = eod_mask_loss or bool(self.data_config.get("eod_mask_loss", False))
295 self._validate_attention_inputs(attention_mode, create_attention_mask)
296 self.cp_sharder = CPBatchSharder(self.parallel_context)
297 self.tp_broadcaster = TPBatchBroadcaster(self.parallel_context, device)
299 self.reset_position_ids = (
300 reset_position_ids or bool(self.data_config.get("reset_position_ids", False))
301 or source_type == "packed_text"
302 or bool(self.data_config.get("inter_document_masking", False))
303 )
304 resolved_reset_attention_mask = (
305 reset_attention_mask
306 or bool(self.data_config.get("reset_attention_mask", False))
307 or source_type in {"online", "packed_text"}
308 or self.is_sft_dataset
309 or bool(self.data_config.get("inter_document_masking", False))
310 )
311 self.attention_runtime = AttentionRuntime(
312 mode=attention_mode,
313 create_mask=create_attention_mask,
314 reset_mask=resolved_reset_attention_mask,
315 sliding_window=sliding_window,
316 )
318 @staticmethod
319 def _build_boundary_resolver(source_type: str, tokenizer: Any) -> OnlineBoundaryResolver | IndexedBoundaryResolver:
320 """Select sequence-boundary handling for the source's input_ids batch."""
322 if source_type in {"online", "packed_text"}:
323 boundary_resolver = OnlineBoundaryResolver()
324 return boundary_resolver
326 if source_type == "offline":
327 boundary_resolver = IndexedBoundaryResolver(getattr(tokenizer, "eod", None))
328 return boundary_resolver
330 raise ValueError(f"Unsupported batch source type: {source_type!r}")
332 def _validate_attention_inputs(self, attention_mode: str, create_attention_mask: bool) -> None:
333 """Require shifted labels and document isolation for prepared text records."""
335 if self.source_type == "packed_text":
336 if not self.labels_are_shifted:
337 raise ValueError("Packed text batches require shifted labels; labels_are_shifted must be True")
338 if not create_attention_mask or (attention_mode == "compressed" and self.runtime_input_adapter is None):
339 raise ValueError(
340 "Packed text batches require document-boundary attention: enable "
341 "create_attention_mask_in_dataloader and supply a runtime_input_adapter for compressed attention"
342 )
344 if self.is_sft_dataset:
345 if not self.labels_are_shifted or self.eod_mask_loss or not self.causal:
346 raise ValueError("Prepared records require shifted labels, causal attention and eod_mask_loss=False")
348 if (attention_mode == "compressed" or not create_attention_mask) and self.runtime_input_adapter is None:
349 raise ValueError("Prepared records without a dense mask require a boundary-aware runtime adapter")
351 def __call__(
352 self,
353 data_iterator: Any,
354 ) -> tuple[Mapping[str, Any], Mapping[str, Any]]:
355 """Build model and loss inputs for one forward-backward step.
357 Args:
358 data_iterator: Iterator yielding one collated Indexed or Online batch.
360 Returns:
361 Model inputs and loss inputs for one forward-backward step.
362 """
363 canonical_batch = self._read_source_batch(data_iterator)
364 cu_seq_lens = self._resolve_sequence_boundaries(canonical_batch)
365 cp_local_batch = self.cp_sharder.shard(canonical_batch)
366 parallel_batch = self.tp_broadcaster.broadcast(
367 cp_local_batch,
368 cu_seq_lens,
369 )
370 self._log_batch_flow(canonical_batch, parallel_batch)
372 position_ids = self._build_local_position_ids(
373 parallel_batch["input_ids"],
374 parallel_batch["cu_seq_lens"],
375 )
376 parallel_batch["position_ids"] = position_ids
378 loss_mask = self._build_loss_mask(parallel_batch)
379 parallel_batch["loss_mask"] = loss_mask
380 runtime_inputs = self._build_runtime_inputs(parallel_batch)
382 model_inputs, loss_inputs = self._split_model_and_loss_inputs(
383 parallel_batch,
384 runtime_inputs,
385 )
387 return model_inputs, loss_inputs
389 def _build_runtime_inputs(
390 self,
391 parallel_batch: Mapping[str, Any],
392 ) -> dict[str, Any]:
393 """Build common attention inputs plus a model-owned extension."""
394 runtime_inputs = self.attention_runtime.build(
395 batch=parallel_batch,
396 parallel_context=self.parallel_context,
397 )
398 if self.runtime_input_adapter is None:
399 return runtime_inputs
401 model_runtime_inputs = self.runtime_input_adapter.build(
402 batch=parallel_batch,
403 parallel_context=self.parallel_context,
404 options={
405 "source_type": self.source_type,
406 "attention_mode": self.attention_runtime.mode,
407 "causal": self.causal,
408 "sliding_window": self.sliding_window,
409 },
410 )
411 collisions = set(runtime_inputs).intersection(model_runtime_inputs)
412 if collisions:
413 raise ValueError(
414 "model runtime inputs cannot replace common attention inputs: "
415 f"{sorted(collisions)}"
416 )
418 runtime_inputs.update(model_runtime_inputs)
419 return runtime_inputs
421 def _log_batch_flow(
422 self,
423 canonical_batch: Mapping[str, Any] | None,
424 parallel_batch: Mapping[str, Any],
425 ) -> None:
426 """Log the resolved source and parallel batch shapes once."""
427 if not self._batch_flow_logged:
428 source_shape = None if canonical_batch is None else tuple(canonical_batch["input_ids"].shape)
429 local_shape = tuple(parallel_batch["input_ids"].shape)
430 num_boundaries = 0 if parallel_batch["cu_seq_lens"] is None else parallel_batch["cu_seq_lens"].numel()
431 logger.debug(
432 "Parallel batch flow: source=%s, tp_rank=%d/%d, cp_rank=%d/%d, "
433 "source_owner=%s, source_shape=%s, local_shape=%s, global_boundaries=%d",
434 self.source_type,
435 self.parallel_context.tp_rank,
436 self.parallel_context.tp_world_size,
437 self.parallel_context.cp_rank,
438 self.parallel_context.cp_world_size,
439 canonical_batch is not None,
440 source_shape,
441 local_shape,
442 num_boundaries,
443 enabled=True,
444 )
445 self._batch_flow_logged = True
447 def _read_source_batch(self, data_iterator: Any) -> Mapping[str, Any] | None:
448 """Advance the source only on ranks selected by the shared context."""
449 if self.parallel_context.build_on_rank():
450 source_batch = next(data_iterator)
451 else:
452 source_batch = None
454 return source_batch
456 def _resolve_sequence_boundaries(
457 self,
458 canonical_batch: Mapping[str, Any] | None,
459 ) -> Any:
460 """Resolve global leading-zero cumulative sequence boundaries."""
461 if canonical_batch is None:
462 cu_seq_lens = None
463 else:
464 cu_seq_lens = self.boundary_resolver.resolve(canonical_batch)
466 return cu_seq_lens
468 def _build_local_position_ids(
469 self,
470 input_ids: Any,
471 cu_seq_lens: Any,
472 ) -> Any:
473 """Build position IDs for the current CP slice on every TP rank.
475 Packed boundaries define the position semantics. CP only determines
476 which global sequence interval is materialized by this rank.
477 """
478 # pylint: disable=too-many-locals
479 batch_size, local_seq_len = input_ids.shape
480 cp_size = self.parallel_context.cp_world_size
481 global_seq_len = local_seq_len * cp_size
482 cp_rank = self.parallel_context.cp_rank
483 cp_seq_start = cp_rank * local_seq_len
484 cp_seq_end = cp_seq_start + local_seq_len
486 # This produces the same values as building global [B, S] positions
487 # and then taking the CP slice, without allocating the global tensor.
488 position_ids = torch.arange(
489 cp_seq_start, cp_seq_end, dtype=torch.int64, device=input_ids.device
490 )
491 local_position_ids = position_ids.unsqueeze(0).expand(batch_size, -1)
493 if self.reset_position_ids:
494 local_position_ids = local_position_ids.clone()
495 boundaries = cu_seq_lens.tolist()
496 for seq_start, seq_end in zip(boundaries[:-1], boundaries[1:]):
497 seq_len = seq_end - seq_start
498 batch_idx, seq_start_in_batch = divmod(seq_start, global_seq_len)
499 seq_end_in_batch = seq_start_in_batch + seq_len
500 # Intersect the sequence with the current CP slice.
501 slice_start = max(seq_start_in_batch, cp_seq_start)
502 slice_end = min(seq_end_in_batch, cp_seq_end)
503 if slice_start >= slice_end:
504 continue
506 local_start = slice_start - cp_seq_start
507 local_end = slice_end - cp_seq_start
508 local_position_ids[batch_idx, local_start:local_end] -= seq_start_in_batch
510 local_position_ids = local_position_ids.contiguous()
512 return local_position_ids
514 def _build_loss_mask(self, parallel_batch: Mapping[str, Any]) -> Any:
515 """Build the local loss mask from labels and input IDs."""
516 loss_mask = (parallel_batch["labels"] >= 0).to(dtype=torch.int64)
518 if self.eod_mask_loss:
519 eod_token_id = getattr(self.tokenizer, "eod", None)
521 if eod_token_id is not None:
522 loss_mask = loss_mask.masked_fill(parallel_batch["input_ids"] == eod_token_id, 0)
524 return loss_mask
526 def _split_model_and_loss_inputs(
527 self,
528 parallel_batch: Mapping[str, Any],
529 runtime_inputs: Mapping[str, Any] | None = None,
530 ) -> tuple[Mapping[str, Any], Mapping[str, Any]]:
531 """Split forward fields from loss and token-accounting fields."""
532 model_inputs = {
533 "input_ids": parallel_batch["input_ids"],
534 "labels": parallel_batch["labels"],
535 "position_ids": parallel_batch["position_ids"],
536 }
537 if self.labels_are_shifted:
538 model_inputs["shift_labels"] = parallel_batch["labels"]
540 runtime_inputs = runtime_inputs or {}
541 collisions = set(model_inputs).intersection(runtime_inputs)
542 if collisions:
543 raise ValueError(
544 "runtime inputs cannot replace framework-owned model inputs: "
545 f"{sorted(collisions)}"
546 )
548 model_inputs.update(runtime_inputs)
550 loss_inputs = {
551 "labels": parallel_batch["labels"],
552 "loss_mask": parallel_batch["loss_mask"],
553 }
554 if self.labels_are_shifted:
555 loss_inputs["shift_labels"] = parallel_batch["labels"]
557 return model_inputs, loss_inputs