Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / distributed / external_source.py: 90%
163 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"""Process-owned preparation of externally selected raw-sample steps."""
17from __future__ import annotations
19import math
20from collections.abc import Sequence
21from dataclasses import dataclass, replace
22from itertools import chain
23from typing import Any
25from hyper_parallel.data.distributed.schema import DistributedPackingPlan, SampleKey, SampleMetadata, WorkloadCost
26from hyper_parallel.data.distributed.transport import DataPlaneTransport, PayloadExchangeWork
29@dataclass(frozen=True)
30class LocalBatch:
31 """Retain a collated CPU step and its balancing statistics."""
33 data: Any
34 stats: dict[str, Any] | None = None
35 host_batch: Any = None
38@dataclass(frozen=True)
39class _PendingBatch:
40 """A planned step whose payload exchange may still be in flight."""
42 plan: DistributedPackingPlan
43 stats: dict[str, Any]
44 retained_payloads: dict[SampleKey, Any]
45 payload_work: PayloadExchangeWork | None
48class ExternalStepProducer:
49 """Keep source iteration, planning, collation and communication in one process."""
51 def __init__(self, source: Any, *, config: Any, metadata_fn: Any, pack_fn: Any,
52 collate_fn: Any, planner: Any, global_rank: int, ranks: tuple[int, ...]) -> None:
53 """Capture an unstarted external source and its CPU callbacks."""
54 self._source = source
55 self.config = config
56 self._metadata_fn = metadata_fn
57 self._pack_fn = pack_fn
58 self._collate_fn = collate_fn
59 self._planner = planner
60 self._global_rank = global_rank
61 self.group_ranks = ranks
62 self._data_rank = ranks.index(global_rank)
63 self._transport = None
64 self._iterator = None
65 self._step = 0
67 @property
68 def global_rank(self) -> int:
69 """Return the logical source rank in the training mesh."""
70 return self._global_rank
72 def bind_transport(self, transport: DataPlaneTransport) -> None:
73 """Bind collectives reconstructed in the owning process.
75 Args:
76 transport: Data-plane collectives owned by this source process.
77 """
78 self._transport = transport
80 def __next__(self) -> LocalBatch:
81 """Construct one selected step without changing sample membership."""
82 if self._iterator is None:
83 self._iterator = iter(self._source)
84 result = self._construct_batch(next(self._iterator), self._step)
85 self._step += 1
86 return result
88 def reset_iteration(self) -> None:
89 """Discard the exhausted iterator while retaining the original source object."""
90 self._iterator = None
91 self._step = 0
93 def set_epoch(self, epoch: int) -> None:
94 """Select the external source epoch before constructing its next iterator.
96 Args:
97 epoch: Non-negative epoch to select before the next source read.
98 """
99 self.reset_iteration()
100 setter = getattr(self._source, "set_epoch", None)
101 if callable(setter):
102 setter(epoch)
104 def close(self) -> None:
105 """Drop source iterators in the process that owns their workers."""
106 self._iterator = None
108 def _construct_batch(
109 self,
110 raw_bins: Sequence[Sequence[Any]],
111 step: int,
112 ) -> LocalBatch:
113 metadata, local_payloads = self._read_step(raw_bins, step)
114 gathered = self._transport.all_gather_object(metadata)
115 plan, stats = self._plan_step(gathered, step)
116 return self._finish_batch(self._begin_batch(local_payloads, plan, stats))
118 def _begin_batch(
119 self, local_payloads: dict[SampleKey, Any], plan: DistributedPackingPlan, stats: dict[str, Any],
120 ) -> _PendingBatch:
121 """Start payload exchange for moved samples while retaining local destinations."""
122 if stats["moved_samples"]:
123 outgoing: dict[int, list[tuple[SampleKey, Any]]] = {}
124 retained_payloads = {}
125 for data_rank, local_batch in enumerate(plan.local_batches):
126 target_rank = self.group_ranks[data_rank]
127 owned = [
128 (key, local_payloads[key])
129 for packing_bin in local_batch
130 for key in packing_bin.sample_keys
131 if key.reader_rank == self._global_rank
132 ]
133 if target_rank == self._global_rank:
134 retained_payloads.update(owned)
135 else:
136 outgoing[target_rank] = owned
137 prepared = self._transport.prepare_exchange(outgoing)
138 work = self._transport.begin_exchange_prepared(prepared)
139 else:
140 # Every rank sees the same plan and skips an unchanged exchange.
141 retained_payloads = local_payloads
142 work = None
143 return _PendingBatch(plan, stats, retained_payloads, work)
145 def _finish_batch(self, pending: _PendingBatch) -> LocalBatch:
146 """Complete payload exchange, pack and collate the local batch, return CPU tensors."""
147 received = pending.retained_payloads
148 if pending.payload_work is not None:
149 received.update(pending.payload_work.wait())
150 target = pending.plan.local_batch_for(self._data_rank)
151 host_batch = self._collate_fn([
152 self._pack_fn([received[key] for key in packing_bin.sample_keys], self.config.seq_len)
153 for packing_bin in target
154 ])
155 return LocalBatch(host_batch, pending.stats, host_batch)
157 def _read_step(self, raw_bins: Sequence[Sequence[Any]], step: int) -> tuple[tuple[Any, ...], dict[SampleKey, Any]]:
158 """Bind raw source bins to keyed metadata and cached payloads for one step."""
159 if len(raw_bins) != self.config.local_batch_size or any(not raw_bin for raw_bin in raw_bins):
160 raise ValueError("Each source step must contain local_batch_size non-empty raw-sample bins.")
161 key_bins = []
162 entries = []
163 payloads = {}
164 for raw_bin in raw_bins:
165 keys = []
166 for sample in raw_bin:
167 item_metadata = self._metadata_fn(sample)
168 if not isinstance(item_metadata, SampleMetadata):
169 raise ValueError("metadata_fn must return SampleMetadata.")
170 key = SampleKey(self._global_rank, step, len(entries))
171 entries.append(replace(item_metadata, key=key))
172 payloads[key] = sample
173 keys.append(key)
174 key_bins.append(tuple(keys))
175 return (tuple(key_bins), tuple(entries)), payloads
177 def _plan_step(self, gathered: Sequence[Any], step: int) -> tuple[DistributedPackingPlan, dict[str, Any]]:
178 planned = self._make_plan(gathered, step)
179 return self._transport.broadcast_from_planner(planned) if self.config.broadcast_plan else planned
181 def _make_plan(self, gathered: Sequence[Any], step: int) -> Any:
182 """Build a plan and balancing statistics on the designated planning ranks."""
183 if self.config.broadcast_plan and self._global_rank != self._transport.planner_rank:
184 return None
185 rank_bins, rank_entries = zip(*gathered)
186 metadata = {item.key: item for item in chain.from_iterable(rank_entries)}
187 if self.config.balance_window_size == 1:
188 plan = self._planner.plan(
189 tuple(metadata.values()), reference_bins=list(chain.from_iterable(rank_bins)), step=step,
190 )
191 costs, decision = self._planner.last_sample_costs, self._planner.last_balance_decision
192 else:
193 plan, costs, decision = self._plan_windows(rank_bins, metadata, step)
194 bin_stats = self._bin_statistics(rank_bins, metadata, plan, costs)
195 stats = self._statistics(plan, step, bin_stats["bins_before"])
196 stats.update(decision)
197 if self._transport.planner_rank == 0:
198 stats.update(bin_stats)
199 return plan, stats
201 def _plan_windows(
202 self, rank_bins: Sequence[Sequence[Sequence[SampleKey]]],
203 metadata: dict[SampleKey, SampleMetadata], step: int,
204 ) -> tuple[DistributedPackingPlan, dict[SampleKey, WorkloadCost], dict[str, Any]]:
205 """Plan consecutive bins inside this source yield, retaining one physical destination per rank."""
206 rounds = list(zip(*rank_bins, strict=True))
207 plans = []
208 windows = []
209 costs = {}
210 width = self.config.balance_window_size
211 for start in range(0, len(rounds), width):
212 bins = list(chain.from_iterable(rounds[start:start + width]))
213 selected = [metadata[key] for packing_bin in bins for key in packing_bin]
214 plans.extend(self._planner.plan_window(selected, reference_bins=bins, step=step * len(rounds) + start))
215 costs.update(self._planner.last_sample_costs)
216 windows.append({
217 **self._planner.last_balance_decision, "first_micro_batch": start + 1, "last_micro_batch": len(plans),
218 })
220 ranks = range(len(rank_bins))
221 local_batches = tuple(tuple(plan.local_batch_for(rank)[0] for plan in plans) for rank in ranks)
222 rank_costs = tuple(sum((plan.rank_costs[rank] for plan in plans), WorkloadCost()) for rank in ranks)
223 combined = DistributedPackingPlan(step, self.config.seq_len, local_batches, rank_costs, validate=False)
224 original = math.fsum(window["original_objective"] for window in windows)
225 candidate = math.fsum(window["candidate_objective"] for window in windows)
226 return combined, costs, {
227 "windows": windows, "original_objective": original, "candidate_objective": candidate,
228 "accepted_objective": math.fsum(window["accepted_objective"] for window in windows),
229 "relative_gain": (original - candidate) / original if original else 0.0,
230 "min_balance_gain": self.config.min_balance_gain, "accepted": any(window["accepted"] for window in windows),
231 }
233 def _bin_statistics(
234 self, rank_bins: Sequence[Sequence[Sequence[SampleKey]]], metadata_by_key: dict[SampleKey, SampleMetadata],
235 plan: DistributedPackingPlan, sample_costs: dict[SampleKey, WorkloadCost],
236 ) -> dict[str, Any]:
237 """Summarize original and accepted bins using the planner's estimates, including padding."""
239 def _describe(keys: Sequence[SampleKey]) -> dict[str, Any]:
240 tokens = sum(metadata_by_key[key].pack_tokens for key in keys)
241 padding = max(0, self._planner.seq_len - tokens)
242 return {
243 "samples": len(keys), "seq_len": tokens, "padding": padding,
244 "cost": math.fsum(sample_costs[key].llm for key in keys) + self._planner.padding_cost(padding).llm,
245 }
247 before = tuple(tuple(_describe(keys) for keys in key_bins) for key_bins in rank_bins)
248 after = tuple(
249 tuple(_describe(packing_bin.sample_keys) for packing_bin in local_batch)
250 for local_batch in plan.local_batches
251 )
252 return {"bins_before": before, "bins_after": after}
254 def _statistics(
255 self, plan: DistributedPackingPlan, step: int, bins_before: Sequence[Sequence[dict[str, Any]]],
256 ) -> dict[str, Any]:
257 """Count cross-rank raw-sample transfers, excluding locally retained samples."""
258 before = [math.fsum(packing_bin["cost"] for packing_bin in bins) for bins in bins_before]
259 after = [cost.llm for cost in plan.rank_costs]
260 send_samples = [0] * len(self.group_ranks)
261 recv_samples = [0] * len(self.group_ranks)
262 moved = 0
263 source_indices = {rank: index for index, rank in enumerate(self.group_ranks)}
264 for data_rank, local_batch in enumerate(plan.local_batches):
265 for packing_bin in local_batch:
266 for key in packing_bin.sample_keys:
267 source_index = source_indices[key.reader_rank]
268 if source_index != data_rank:
269 send_samples[source_index] += 1
270 recv_samples[data_rank] += 1
271 moved += 1
272 mean_before = math.fsum(before) / len(before)
273 mean_after = math.fsum(after) / len(after)
274 max_before, max_after = max(before), max(after)
275 return {
276 "step": step,
277 "scope": "node",
278 "objective": self._planner.objective,
279 "group_ranks": self.group_ranks,
280 "cost_before": tuple(before),
281 "cost_after": tuple(after),
282 "max_cost_before": max_before,
283 "max_cost_after": max_after,
284 "relative_spread_before": (max_before - min(before)) / mean_before if mean_before else 0.0,
285 "relative_spread_after": (max_after - min(after)) / mean_after if mean_after else 0.0,
286 "moved_samples": moved,
287 "send_samples": tuple(send_samples),
288 "recv_samples": tuple(recv_samples),
289 }