Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / batching / runtime_input.py: 76%
162 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"""Resolve sequence metadata and model-owned runtime inputs."""
17from __future__ import annotations
19from abc import ABC, abstractmethod
20from collections.abc import Mapping, Sequence
21from dataclasses import dataclass
22from numbers import Integral
23from typing import Any
25import torch
28class OnlineBoundaryResolver:
29 """Read global cumulative sequence boundaries emitted by Online packing."""
31 @staticmethod
32 def resolve(canonical_batch: Mapping[str, Any]) -> Any:
33 """Read leading-zero ``cu_seq_lens`` from an Online batch."""
34 raw_cu_seq_lens = canonical_batch["cu_seq_lens"]
35 cu_seq_lens = raw_cu_seq_lens.to(torch.int32)
36 return cu_seq_lens
39class IndexedBoundaryResolver:
40 """Resolve global cumulative sequence boundaries for Indexed batches."""
42 def __init__(self, eod_token_id: int | None) -> None:
43 """Store the token separating packed Indexed sequences."""
44 self.eod_token_id = eod_token_id
46 def resolve(self, canonical_batch: Mapping[str, Any]) -> torch.Tensor:
47 """Read explicit boundaries or recover them from EOD tokens."""
48 input_ids = canonical_batch["input_ids"]
49 batch_size, seq_len = input_ids.shape
51 if "cu_seq_lens" in canonical_batch:
52 cu_seq_lens = self._merge_cu_seqlens_across_micro_batch(
53 canonical_batch["cu_seq_lens"], batch_size, seq_len
54 )
55 return cu_seq_lens
57 token_indices = torch.arange(seq_len, dtype=input_ids.dtype, device=input_ids.device)
58 seq_ends = []
60 for batch_idx in range(batch_size):
61 if self.eod_token_id is None:
62 eod_indices = token_indices[:0]
63 else:
64 eod_indices = token_indices[input_ids[batch_idx] == self.eod_token_id]
66 for eod_idx in eod_indices:
67 seq_end = batch_idx * seq_len + int(eod_idx.item()) + 1
68 seq_ends.append(seq_end)
70 row_end = (batch_idx + 1) * seq_len
71 if not seq_ends or seq_ends[-1] != row_end:
72 seq_ends.append(row_end)
74 cu_seq_lens = torch.tensor([0, *seq_ends], dtype=torch.int32)
76 return cu_seq_lens
78 @staticmethod
79 def _merge_cu_seqlens_across_micro_batch(
80 cu_seqlens: Sequence[Any] | torch.Tensor, micro_batch_size: int, seq_length: int
81 ) -> torch.Tensor:
82 """Merge per-sample boundaries into offsets over the entire batch.
84 Adapted from Megatron-LM's megatron/core/utils.py. See MEGATRON_LICENSE.txt.
85 """
86 if isinstance(cu_seqlens, torch.Tensor) and cu_seqlens.ndim == 1:
87 merged_cu_seqlens = cu_seqlens.to(torch.int32)
89 return merged_cu_seqlens
91 if len(cu_seqlens) != micro_batch_size:
92 raise ValueError("cu_seq_lens must have one boundary array per batch row")
94 if micro_batch_size == 0:
95 merged_cu_seqlens = torch.zeros(1, dtype=torch.int32, device="cpu")
97 return merged_cu_seqlens
99 def _strip_padding(row: torch.Tensor) -> torch.Tensor:
100 """Return the valid prefix ending at the first occurrence of seq_length."""
101 hits = (row == seq_length).nonzero(as_tuple=True)[0]
103 if hits.numel() > 0:
104 valid = row[:hits[0].item() + 1]
106 return valid
108 return row
110 def _prepare_row(row: Any) -> torch.Tensor:
111 """Validate the sample boundaries and remove terminal padding."""
112 row = torch.as_tensor(row, device="cpu")
114 if row.ndim != 1 or row.dtype not in (torch.int32, torch.int64) or row.numel() < 2:
115 raise ValueError("Each cu_seq_lens row must be a 1D integer array with at least two entries")
117 if row[0] != 0 or row[-1] != seq_length:
118 raise ValueError("Each cu_seq_lens row must start at zero and end at the sequence length")
120 valid = _strip_padding(row)
122 if torch.any(valid[1:] <= valid[:-1]) or torch.any(row[valid.numel():] != seq_length):
123 raise ValueError("cu_seq_lens must strictly increase before terminal padding")
125 return valid
127 if micro_batch_size == 1:
128 merged_cu_seqlens = _prepare_row(cu_seqlens[0]).to(dtype=torch.int32, copy=True)
129 return merged_cu_seqlens
131 parts = [_prepare_row(cu_seqlens[0])]
132 for i in range(1, micro_batch_size):
133 offset = i * seq_length
134 valid = _prepare_row(cu_seqlens[i])
135 parts.append(valid[1:] + offset)
137 merged_cu_seqlens = torch.cat(parts).to(torch.int32)
139 return merged_cu_seqlens
142@dataclass(frozen=True)
143class RuntimeInputContext:
144 """Framework execution facts available to a model runtime adapter.
146 ``options`` deliberately carries feature-specific policy. The framework
147 owns batch movement and parallel coordinates, while a model adapter may
148 translate those facts into attention metadata, modality routing inputs,
149 cache descriptors, or another forward-only contract.
150 """
152 local_input_shape: Sequence[int]
153 parallel_ranks: Mapping[str, int]
154 parallel_sizes: Mapping[str, int]
155 options: Mapping[str, Any]
157 @classmethod
158 def from_batch(
159 cls,
160 *,
161 batch: Mapping[str, Any],
162 parallel_context: Any,
163 options: Mapping[str, Any] | None = None,
164 ) -> RuntimeInputContext:
165 """Build runtime context from one parallel-local batch."""
166 runtime_context = cls(
167 local_input_shape=batch["input_ids"].shape,
168 parallel_ranks={
169 "tp": parallel_context.tp_rank,
170 "cp": parallel_context.cp_rank,
171 },
172 parallel_sizes={
173 "tp": parallel_context.tp_world_size,
174 "cp": parallel_context.cp_world_size,
175 },
176 options={} if options is None else options,
177 )
178 return runtime_context
181class RuntimeInputAdapter(ABC):
182 """Extend a generic batch with model-owned forward inputs."""
184 def build(
185 self,
186 *,
187 batch: Mapping[str, Any],
188 parallel_context: Any,
189 options: Mapping[str, Any] | None = None,
190 ) -> dict[str, Any]:
191 """Build runtime context and produce one runtime's model inputs."""
192 runtime_context = RuntimeInputContext.from_batch(
193 batch=batch,
194 parallel_context=parallel_context,
195 options=options,
196 )
197 runtime_inputs = self.build_runtime_inputs(
198 batch=batch,
199 context=runtime_context,
200 )
201 if not isinstance(runtime_inputs, Mapping):
202 raise TypeError(
203 "RuntimeInputAdapter.build_runtime_inputs must return a mapping, "
204 f"got {type(runtime_inputs).__name__}"
205 )
206 return dict(runtime_inputs)
208 def prepare_graph_inputs(self, model_inputs: dict[str, Any]) -> dict[str, Any]:
209 """Return inputs unchanged unless the model needs graph-only metadata.
211 Args:
212 model_inputs: Real model inputs immediately before graph execution.
214 Returns:
215 Inputs used for both graph capture and replay. Eager never calls this hook.
216 """
217 return model_inputs
219 def runtime_input_fields(self) -> tuple[str, ...]:
220 """Return the forward fields exclusively owned by this adapter.
222 Dynamic values may vary by batch, but field ownership must be stable so
223 diagnostics can reject collisions before interpreting precision runs.
224 """
225 return ()
227 @abstractmethod
228 def build_runtime_inputs(
229 self,
230 *,
231 batch: Mapping[str, Any],
232 context: RuntimeInputContext,
233 ) -> Mapping[str, Any]:
234 """Build additional model inputs without mutating ``batch``.
236 Args:
237 batch: Device-resident, parallel-local batch. Global metadata such
238 as ``cu_seq_lens`` remains available when required.
239 context: Local geometry, parallel coordinates, and feature-specific
240 recipe options.
242 Returns:
243 Mapping merged into the model forward inputs. Keys must not replace
244 fields already owned by the generic batch path.
245 """
246 raise NotImplementedError
249class PackedAttentionRuntime(RuntimeInputAdapter):
250 """Share global document boundaries across attention layers without a dense mask.
252 The selected attention implementation must consume cumulative lengths and
253 bypass model-side dense mask construction. Position IDs and loss ownership
254 remain with TextParallelBatch; this adapter does not shard document bounds.
255 """
257 def runtime_input_fields(self) -> tuple[str, ...]:
258 """Declare the two leading-zero FA length arguments."""
259 return ("cu_seq_lens_q", "cu_seq_lens_k")
261 def build_runtime_inputs(self, *, batch: Mapping[str, Any], context: RuntimeInputContext) -> Mapping[str, Any]:
262 """Read boundaries once per batch and preserve their global batch-major coordinates."""
263 if context.options.get("attention_mode") != "compressed":
264 raise ValueError("PackedAttentionRuntime requires attention_mode='compressed'")
265 shape = context.local_input_shape
266 if len(shape) != 2:
267 raise ValueError("Packed attention requires input_ids with shape [batch, local_sequence]")
268 boundaries = batch.get("cu_seq_lens")
269 if isinstance(boundaries, torch.Tensor):
270 if boundaries.ndim != 1:
271 raise ValueError("Packed attention requires one-dimensional global cu_seq_lens")
272 boundaries = boundaries.tolist()
273 if boundaries is None or any(isinstance(value, bool) or not isinstance(value, Integral)
274 for value in boundaries):
275 raise ValueError("Packed attention requires integer global cu_seq_lens")
276 boundaries = tuple(int(value) for value in boundaries)
277 if len(boundaries) < 2 or boundaries[0] != 0:
278 raise ValueError("Packed attention cu_seq_lens must start with zero and contain a document")
279 if any(end <= start for start, end in zip(boundaries, boundaries[1:])):
280 raise ValueError("Packed attention cu_seq_lens must be strictly increasing")
281 tokens = shape[0] * shape[1] * context.parallel_sizes["cp"]
282 if boundaries[-1] != tokens:
283 raise ValueError("Packed attention cu_seq_lens must cover the global batch token count")
284 return {"cu_seq_lens_q": boundaries, "cu_seq_lens_k": boundaries}
287class AttentionRuntime(RuntimeInputAdapter):
288 """Build dense attention fields from common runtime context."""
290 def __init__(
291 self,
292 *,
293 mode: str,
294 create_mask: bool,
295 reset_mask: bool,
296 sliding_window: int | None,
297 ) -> None:
298 """Store the attention representation and mask policy."""
299 self.mode = mode
300 self.create_mask = create_mask
301 self.reset_mask = reset_mask
302 self.sliding_window = sliding_window
304 def build_runtime_inputs(
305 self,
306 *,
307 batch: Mapping[str, Any],
308 context: RuntimeInputContext,
309 ) -> Mapping[str, Any]:
310 """Build attention fields without owning model-specific packed metadata."""
311 attention_inputs = {"attention_mask": None}
312 if not self.create_mask or self.mode == "compressed":
313 return attention_inputs
315 micro_batch_size, local_sequence_length = batch["input_ids"].shape
316 cp_size = context.parallel_sizes["cp"]
317 global_sequence_length = local_sequence_length * cp_size
318 attention_mask, sliding_window_mask = self._build_dense_attention_masks(
319 cu_seq_lens=batch["cu_seq_lens"],
320 micro_batch_size=micro_batch_size,
321 seq_length=global_sequence_length,
322 device=batch["input_ids"].device,
323 )
324 attention_inputs["attention_mask"] = attention_mask
325 if sliding_window_mask is not None:
326 attention_inputs["swa_mask"] = sliding_window_mask
328 return attention_inputs
330 def _build_dense_attention_masks(
331 self,
332 *,
333 cu_seq_lens: Any,
334 micro_batch_size: int,
335 seq_length: int,
336 device: Any,
337 ) -> tuple[Any, Any | None]:
338 """Build global dense attention and optional sliding-window masks."""
339 boundaries = [int(boundary) for boundary in cu_seq_lens.tolist()]
340 if len(boundaries) < 2 or boundaries[0] != 0:
341 raise ValueError("cu_seq_lens must contain a leading zero and at least one sequence")
343 if any(end <= start for start, end in zip(boundaries[:-1], boundaries[1:])):
344 raise ValueError("cu_seq_lens must be strictly increasing")
346 physical_sequence_length = micro_batch_size * seq_length
347 if boundaries[-1] != physical_sequence_length:
348 raise ValueError(
349 "cu_seq_lens must cover the physical batch length "
350 f"({physical_sequence_length}), but got {boundaries[-1]}"
351 )
353 attention_batch_size = micro_batch_size if self.reset_mask else 1
354 attention_mask = torch.ones(
355 (attention_batch_size, seq_length, seq_length),
356 dtype=torch.bool,
357 device=device,
358 ).tril()
359 attention_mask = attention_mask.view(attention_batch_size, 1, seq_length, seq_length)
361 if self.reset_mask:
362 for sequence_start in boundaries[:-1]:
363 batch_index, row_sequence_start = divmod(sequence_start, seq_length)
364 attention_mask[batch_index, 0, row_sequence_start:, :row_sequence_start] = False
366 sliding_window_mask = None
367 if self.sliding_window is not None:
368 positions = torch.arange(seq_length, dtype=torch.int64, device=device)
369 outside_window = positions.unsqueeze(1) - positions.unsqueeze(0) > self.sliding_window
370 sliding_window_mask = attention_mask & ~outside_window.unsqueeze(0).unsqueeze(0)
372 return attention_mask, sliding_window_mask
375__all__ = [
376 "AttentionRuntime",
377 "IndexedBoundaryResolver",
378 "OnlineBoundaryResolver",
379 "PackedAttentionRuntime",
380 "RuntimeInputAdapter",
381 "RuntimeInputContext",
382]