Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / encoder_parallel / planning.py: 93%
111 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"""Pure topology, token ownership, and image work planning."""
17from __future__ import annotations
19from dataclasses import dataclass
20from math import isfinite, lcm
21from typing import Any, Mapping, Sequence
23import torch
25from hyper_parallel.distributed.encoder_parallel.contracts import EncoderSegment, EncoderWorkItem
28def required_omni_global_alignment(mesh_context: Any) -> int:
29 """Return the shared compact-attention and decoder-SP alignment.
31 Args:
32 mesh_context: Decoder CP, TP, and sequence-parallel topology.
33 """
34 cp_size = int(mesh_context.cp_size)
35 tp_parts = int(mesh_context.tp_size) if mesh_context.sequence_parallel else 1
36 return lcm(2 * cp_size, cp_size * tp_parts)
39@dataclass(frozen=True)
40class DecoderSequenceLayout:
41 """The exact decoder hidden-token interval on one CP/TP rank."""
43 sequence_parallel: bool
44 cp_rank: int
45 cp_size: int
46 tp_rank: int
47 tp_size: int
48 cp_local_length: int
49 global_sequence_length: int
50 cp_local_start: int
51 cp_local_stop: int
52 global_start: int
53 global_stop: int
55 @classmethod
56 def build(cls, *, mesh_context: Any, cp_local_length: int,
57 cp_rank: int | None = None, tp_rank: int | None = None) -> "DecoderSequenceLayout":
58 """Derive the token interval after embedding's TP reduce-scatter."""
59 cp_size = int(mesh_context.cp_size)
60 tp_size = int(mesh_context.tp_size)
61 cp_rank = int(mesh_context.cp_rank if cp_rank is None else cp_rank)
62 tp_rank = int(mesh_context.tp_rank if tp_rank is None else tp_rank)
63 sp = bool(mesh_context.sequence_parallel)
64 if not 0 <= cp_rank < cp_size or not 0 <= tp_rank < tp_size:
65 raise ValueError(
66 "decoder CP/TP coordinate is outside topology; "
67 f"cp_rank={cp_rank}; cp_size={cp_size}; tp_rank={tp_rank}; tp_size={tp_size}"
68 )
69 if cp_local_length < 1 or (sp and cp_local_length % tp_size):
70 raise ValueError(
71 "invalid decoder sequence layout; "
72 f"sequence_parallel={sp}; cp_local_length={cp_local_length}; tp_size={tp_size}; "
73 "constraint=cp_local_length % tp_size == 0 when SP is enabled"
74 )
75 local_length = cp_local_length // (tp_size if sp else 1)
76 local_start = (tp_rank if sp else 0) * local_length
77 global_start = cp_rank * cp_local_length + local_start
78 return cls(sp, cp_rank, cp_size, tp_rank, tp_size, cp_local_length,
79 cp_size * cp_local_length, local_start, local_start + local_length,
80 global_start, global_start + local_length)
82 def localize(self, value: torch.Tensor, *, sequence_dim: int = 1) -> torch.Tensor:
83 """Slice a CP-local auxiliary tensor to this hidden-token interval.
85 Args:
86 value: Auxiliary tensor replicated across decoder TP ranks.
87 sequence_dim: Dimension containing CP-local token rows.
88 """
89 if value.shape[sequence_dim] != self.cp_local_length:
90 raise ValueError(
91 "CP-local token tensor length mismatch; "
92 f"actual={value.shape[sequence_dim]}; expected={self.cp_local_length}; "
93 f"cp_rank={self.cp_rank}; tp_rank={self.tp_rank}"
94 )
95 return value.narrow(sequence_dim, self.cp_local_start,
96 self.cp_local_stop - self.cp_local_start).contiguous()
98 def validate_hidden(self, hidden: torch.Tensor, *, sequence_dim: int = 1) -> None:
99 """Fail before merging against an unexpected decoder hidden layout.
101 Args:
102 hidden: Decoder hidden tensor after embedding redistribution.
103 sequence_dim: Dimension containing decoder token rows.
104 """
105 expected = self.global_stop - self.global_start
106 if hidden.shape[sequence_dim] != expected:
107 raise ValueError(
108 "decoder hidden does not match planned CP/SP shard; "
109 f"actual={hidden.shape[sequence_dim]}; expected={expected}; "
110 f"global_interval=({self.global_start},{self.global_stop}); "
111 f"cp_rank={self.cp_rank}; tp_rank={self.tp_rank}"
112 )
115def assign_lpt(items: Sequence[EncoderWorkItem], encoder_dp_size: int,
116 encoder_cp_size: int, *, costs: Mapping[int, float] | None = None
117 ) -> tuple[tuple[EncoderWorkItem, ...], ...]:
118 """Assign image work by stable largest-processing-time-first scheduling.
120 Args:
121 items: Images with valid patch counts and stable IDs.
122 encoder_dp_size: Number of visual work buckets.
123 encoder_cp_size: Sequence-sharding degree of each bucket.
124 costs: Optional model-owned cost per image ID. None retains patch-square scheduling.
125 """
126 if encoder_dp_size < 1 or encoder_cp_size < 1:
127 raise ValueError("encoder DP and CP sizes must be positive")
128 buckets: list[list[EncoderWorkItem]] = [[] for _ in range(encoder_dp_size)]
129 loads = [0] * encoder_dp_size
130 weights = {item.item_id: item.sequence_length ** 2 if costs is None else costs[item.item_id] for item in items}
131 if any(not isfinite(value) or value <= 0 for value in weights.values()):
132 raise ValueError("encoder work costs must be finite and positive")
133 for item in sorted(items, key=lambda value: (-weights[value.item_id], value.batch_index, value.item_id)):
134 bucket = min(range(encoder_dp_size), key=lambda rank: (loads[rank], rank))
135 buckets[bucket].append(item)
136 loads[bucket] += weights[item.item_id] // encoder_cp_size if costs is None else weights[item.item_id]
137 return tuple(tuple(bucket) for bucket in buckets)
140def build_segments(items: Sequence[EncoderWorkItem], encoder_cp_rank: int,
141 encoder_cp_size: int, *, packed: bool = False) -> tuple[EncoderSegment, ...]:
142 """Build equal-size padded sequence shards for one Encoder-CP rank.
144 Args:
145 items: Images assigned to this Encoder-DP bucket.
146 encoder_cp_rank: Sequence-shard coordinate within the bucket.
147 encoder_cp_size: Number of shards per image.
148 packed: Split the concatenated image sequence with only one tail pad.
149 """
150 if not 0 <= encoder_cp_rank < encoder_cp_size:
151 raise ValueError("invalid encoder CP rank")
152 if packed:
153 return _build_packed_segments(items, encoder_cp_rank, encoder_cp_size)
154 segments = []
155 offset = 0
156 for item in items:
157 if item.sequence_length < 1:
158 raise ValueError("image patch count must be positive")
159 local_length = (item.sequence_length + encoder_cp_size - 1) // encoder_cp_size
160 start = encoder_cp_rank * local_length
161 valid = max(0, min(local_length, item.sequence_length - start))
162 segments.append(EncoderSegment(item, start, valid, local_length, offset))
163 offset += local_length
164 if not segments:
165 segments.append(EncoderSegment(None, 0, 1, 1, 0))
166 return tuple(segments)
169def _build_packed_segments(items: Sequence[EncoderWorkItem], rank: int, size: int) -> tuple[EncoderSegment, ...]:
170 """Intersect each image with one equal shard of the concatenated bucket."""
171 if any(item.sequence_length < 1 for item in items):
172 raise ValueError("image patch count must be positive")
173 total = sum(item.sequence_length for item in items)
174 shard = max(1, (total + size - 1) // size)
175 left, right = rank * shard, (rank + 1) * shard
176 segments = []
177 image_start = offset = 0
178 for item in items:
179 start, stop = max(left, image_start), min(right, image_start + item.sequence_length)
180 if start < stop:
181 length = stop - start
182 segments.append(EncoderSegment(item, start - image_start, length, length, offset))
183 offset += length
184 image_start += item.sequence_length
185 if offset < shard:
186 segments.append(EncoderSegment(None, 0, 0, shard - offset, offset))
187 return tuple(segments)
190def build_destinations(items: Sequence[EncoderWorkItem], layouts: Mapping[int, DecoderSequenceLayout]
191 ) -> dict[int, tuple[int, ...]]:
192 """Find every CP/TP rank whose decoder hidden intersects each image span.
194 Args:
195 items: Images carrying their global decoder token spans.
196 layouts: Decoder token interval for every rank in the parent group.
197 """
198 lengths = {layout.global_sequence_length for layout in layouts.values()}
199 if len(lengths) != 1:
200 raise ValueError("inconsistent decoder global lengths")
201 global_length = next(iter(lengths))
202 result = {}
203 for item in items:
204 start = item.decoder_token_start
205 stop = start + item.decoder_token_length
206 if item.decoder_token_length <= 0 or start < 0 or stop > global_length:
207 raise ValueError(
208 "image span is outside the decoder domain; "
209 f"item_id={item.item_id}; span=({start},{stop}); global_sequence_length={global_length}"
210 )
211 owners = tuple(rank for rank, layout in layouts.items()
212 if max(start, layout.global_start) < min(stop, layout.global_stop))
213 if not owners:
214 raise ValueError(f"image span has no decoder token owner; item_id={item.item_id}")
215 result[item.item_id] = owners
216 return result