Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/distributed_data/api.py 16.7% 806-807,819-821
hyper_parallel/distributed_data/balance_logging.py 0.0% 79-80
hyper_parallel/distributed_data/batch_sampler.py 16.7% 225-227,317,330
hyper_parallel/distributed_data/device_prefetch.py 20.0% 167-168,191-192
hyper_parallel/distributed_data/distributed_dataloader.py 10.1% 150-152,159-164,166,169,182,198-203,216,218,237-239,242-243,253-257,262,269-271,273-276,278,281,285,287-291,293-295,300-303,312,333,369-370,375-384,387-389,392,399,437-438,441,461-463,465,474
hyper_parallel/distributed_data/external_source.py 22.7% 54-65,70,78,82-86,90-91,99-102,106,113-116,122-127,133-134,136-138,141-143,147-151,155,159-175,178-179,183-188,191,193-199,206-216,220-226,239-242,247-248,252,258-275
hyper_parallel/distributed_data/locality.py 6.7% 107-108,110-111,152-158,163-165
hyper_parallel/distributed_data/metadata.py 20.0% 118-121
hyper_parallel/distributed_data/native_source.py 18.1% 57-76,81,89,101-102,106,110-114,122-131,135-140,143-145,149,152-162,164-165,171-176,180-182,186,194-196,198,208-216,224-229,233-246,255,260,266,270-280,286-297,306-308,312-321,328-341,345-348,350,353-356,360-361,363-365,373-374,376-378,382-391,393-397,401-404,411-412,416,420-425,429-430,436-439,443-448,455,460-463,465,471-473,478-483,494,501,509-512,518-520,524-526
hyper_parallel/distributed_data/packed_balancing.py 11.2% 55-57,61,65-73,76-79,83-92,94-98,100,104-108,112,121,125-140,144-150,154-164,172-176,178-182,184,201-210,212-216,286-287,299
hyper_parallel/distributed_data/process_data.py 17.9% 52-57,64-71,76-87,92-99,102-104,106-108,111-112,118-140,142-148,150-156,158-160,162-164,169-174,176-179,187,189-199,204-207,209-210,212-216,219-224,228-237,240-249,253-269,273-277,285-293,297-304,307-311,314-321,329,333,337-348,350-351,359-363,365,369,373-376,378-379,389-392
hyper_parallel/distributed_data/transport.py 17.4% 55-58,63-67,71-78,106-107,169,215-217,223-225,308-310,319-323,326,428,435,466,470,713,715,719,748,753,796,803,914,953,960,966,1005,1017,1022-1032,1037-1046,1064-1066
hyper_parallel/distributed_data/api.py
802
803
804
805
806
807
808
809
810
811
            "input_ids": TensorFieldSpec(shape, torch.int64),
            "labels": TensorFieldSpec(shape, torch.int64),
            "cu_seq_lens": TensorFieldSpec((None,), torch.int32),
        }
    if model_batch_spec is None and len(state.topology.model_parallel_ranks) > 1:
        raise ValueError("Model-parallel loading requires the same model_batch_spec on every rank.")
    groups = create_data_groups(
        state.topology,
        state.dataset_reader_ranks,
        state.planner_rank,
815
816
817
818
819
820
821
822
823
824
825
        enable_payload_exchange=not config.metadata_mode,
        model_device=device,
    )

    with groups.close_on_error():
        accumulation_steps = batch_sampler.global_batch_size // batch_sampler.global_micro_batch_size
        return DistributedDataLoader(
            groups=groups,
            accumulation_steps=accumulation_steps,
            balance_window_size=config.balance_window_size,
            device_prefetch_depth=config.device_prefetch_depth,
hyper_parallel/distributed_data/balance_logging.py
75
76
77
78
79
80
81
82
83
84
            f"min_balance_gain={stats['min_balance_gain']:.12g}, accepted={stats['accepted']}"
        )
        if "accepted_objective" in stats:
            lines.append(f"  accepted_objective={stats['accepted_objective']:.12g}")
    for window in stats.get("windows", ()):
        lines.append(
            f"  micro_batches={window['first_micro_batch']}-{window['last_micro_batch']}, "
            f"original={window['original_objective']:.12g}, candidate={window['candidate_objective']:.12g}, "
            f"relative_gain={window['relative_gain']:.12g}, accepted={window['accepted']}"
        )
hyper_parallel/distributed_data/batch_sampler.py
221
222
223
224
225
226
227
228
229
230
231
        return payloads, tuple(original_batches)

    def close(self) -> None:
        """Release buffers and workers after the owning loader has drained its producer."""
        self._reset_window()
        if self._sample_loader is not None:
            self._sample_loader.close()

    def _reset_window(self) -> None:
        """Discard speculative reads without shutting down reusable workers."""
        self._window = None
313
314
315
316
317
318
319
320
321
        if (state.get("sample_loader") is None) != (self._sample_loader is None):
            raise ValueError("Native BatchSampler checkpoint payload reader ownership changed.")
        if "window" in state or sampler_optimizer_step_progress(sampler_state):
            raise ValueError("Native BatchSampler checkpoint must align to a complete optimizer step.")
        self._reset_window()
        self._sampler.load_state_dict(sampler_state)
        if self._sample_loader is not None:
            self._sample_loader.load_state_dict(state["sample_loader"])
        self._committed_state = copy.deepcopy(self._sampler.state_dict())
326
327
328
329
330
331
332
333
334

        Args:
            epoch: Epoch to apply to the sampler and sample loader.
        """
        self._reset_window()
        self._sampler.load_state_dict(self._committed_state)
        self._sampler.set_epoch(epoch)
        if self._sample_loader is not None:
            self._sample_loader.set_epoch(epoch)
hyper_parallel/distributed_data/device_prefetch.py
163
164
165
166
167
168
169
170
171
172
            Device batch with a copy-completion event. The
            caller does not wait for that event; the consumer stream
            orders itself with ``wait_event`` in ``take_batch``.
        """
        self._device_module.set_device(self.device)
        return self._enqueue(self.prepare_host(cpu_batch))

    @staticmethod
    def prepare_host(cpu_batch: Any) -> Any:
        """Pin a constructed CPU batch before device staging.
187
188
189
190
191
192
193
194
195
196

        Returns:
            Device input and its copy event. This prefetcher retains pending Host sources.
        """
        self._device_module.set_device(self.device)
        return self._enqueue(staging)

    def _enqueue(self, staging: Any) -> DevicePrefetchedStep:
        """Copy pinned input on the stream owned by the selected device."""
        device_module = self._device_module
hyper_parallel/distributed_data/distributed_dataloader.py
146
147
148
149
150
151
152
153
154
155
156
                raise ValueError(f"{name} must be a positive integer.")
        if (isinstance(device_prefetch_depth, bool) or not isinstance(device_prefetch_depth, int)
                or device_prefetch_depth < 0):
            raise ValueError("device_prefetch_depth must be a non-negative integer.")
        if not isinstance(use_data_process, bool):
            raise ValueError("use_data_process must be boolean.")
        self._source = NativeWindowSource(
            topology=topology, dataset_reader_ranks=dataset_reader_ranks, dataset_reader=dataset_reader,
            metadata_reader=metadata_reader, direct_sample_loader=direct_sample_loader, metadata_mode=metadata_mode,
            planner=planner, data_constructor=data_constructor, initial_epoch=initial_epoch,
            initial_consumed_samples=initial_consumed_samples, broadcast_plan=broadcast_plan,
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
            planner=planner, data_constructor=data_constructor, initial_epoch=initial_epoch,
            initial_consumed_samples=initial_consumed_samples, broadcast_plan=broadcast_plan,
            log_balance=log_balance, accumulation_steps=accumulation_steps, balance_window_size=balance_window_size,
        )
        self._topology = topology
        self._data_plane = data_plane
        self._groups = groups
        self._model_transport = model_transport
        self._device_prefetch = device_prefetch
        self._worker = None
        self._device_prefetch_depth = device_prefetch_depth
        self._use_data_process = use_data_process
        self._device = torch.device(device)
        self._current: _PreparedWindow | None = None
        self._host_request: DataRequest | None = None
        self._device_batches: deque[_PreparedBatch] = deque()
        self._prefetch_target = 0
        self._consumer_stream: Any = None
        # Each staged batch spends one input slot; advancing returns it with the
178
179
180
181
182
183
184
185
186
        self._batch_error: BaseException | None = None
        self._last_ready_event: Any = None
        self._has_delivered = False
        self._closed = False
        self._delivered_state = self._source.snapshot()

    def __iter__(self) -> DistributedDataLoader:
        """Return the rank-local iterator."""
        return self
194
195
196
197
198
199
200
201
202
203
204
205
206
207
        self._record_consumption()
        if self._device.type in ("npu", "cuda"):
            prepared = self._next_device_batch()
        else:
            try:
                prepared = self._next_host_batch()
            except BaseException as error:
                self._model_transport.broadcast(None, error=error)
                raise
            prepared.batch = self._broadcast_batch(prepared.batch)
        if prepared.batch is None:
            self._delivered_state["stopped"] = True
            raise StopIteration
        batch = prepared.batch
212
213
214
215
216
217
218
219
220
221
        if prepared.checkpoint is not None:
            self._delivered_state = prepared.checkpoint
        for message in prepared.balance_logs:
            balance_logger.info("%s", message)
        if (not self._has_delivered and self._device_prefetch_depth and self._topology.is_constructor
                and self._device.type in ("npu", "cuda")):
            self._prefetch_device_batches(1, blocking=True)
        self._has_delivered = True
        self.prefetch()
        return batch
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
        """Pop one Host batch and its delivery state, prefetching the following window."""
        if self._current is None or not self._current.batches:
            if self._current is not None and self._current.exhausted:
                return _PreparedBatch(None)
            self._request_host_window()
            self._current = self._host_request.result()
            self._host_request = None
            if not self._current.batches:
                return _PreparedBatch(None)
            if self._use_data_process:
                self._request_host_window()
        batch = self._current.batches.popleft()
        logs, self._current.balance_logs = self._current.balance_logs, []
        checkpoint = self._current.checkpoint if not self._current.batches else None
        return _PreparedBatch(batch, checkpoint, logs)
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
    def prefetch(self) -> None:
        """Prefetch Constructor H2D without any model-peer communication."""
        if self._closed or self._delivered_state["stopped"] or self._batch_error is not None:
            return
        if self._use_data_process:
            self._request_host_window()
        if self._device.type in ("npu", "cuda") and self._topology.is_constructor:
            self._prefetch_target = self._device_prefetch_depth
            self._prefetch_device_batches(self._prefetch_target)

    def _host_batch_ready(self) -> bool:
        if self._current is not None and (self._current.batches or self._current.exhausted):
            return True
        return self._host_request is not None and self._host_request.is_ready()

    def _prefetch_device_batches(self, count: int, *, blocking: bool = False, on_demand: bool = False) -> None:
        """Fill available slots; only warmup, demand and explicit drains can wait."""
        while len(self._device_batches) < count and self._prefetch_slots and not self._device_stopped:
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
        """Fill available slots; only warmup, demand and explicit drains can wait."""
        while len(self._device_batches) < count and self._prefetch_slots and not self._device_stopped:
            # Only delivery is collective across data ranks. A Constructor may
            # stage buffered inputs alone, but cannot open a synchronous window alone.
            if not self._use_data_process and not on_demand and not (self._current and self._current.batches):
                break
            event = self._prefetch_slots[0]
            try:
                if not blocking and (not self._host_batch_ready() or (event is not None and not event.query())):
                    break
                prepared = self._stage_device_batch(event if blocking else None)
            except BaseException as error:  # pylint: disable=broad-exception-caught
                # A failed speculative copy or read belongs after earlier queued batches.
                prepared = _PreparedBatch(None, error=error)
            self._prefetch_slots.popleft()
            self._device_batches.append(prepared)
            self._device_stopped = prepared.batch is None

    def _request_host_window(self) -> None:
        """Request one Host window from the configured source owner."""
        if self._host_request is not None or (self._current is not None and self._current.exhausted):
            return
        if self._worker is None:
            if self._device.type in ("npu", "cuda"):
                getattr(torch, self._device.type).set_device(self._device)
            if self._use_data_process:
                self._worker = create_data_worker(self._source, self._data_plane)
            else:
                self._source.bind_transport(self._data_plane)
                self._worker = self._source
        self._host_request = DataRequest(self._worker)

    def _stage_device_batch(self, event: Any) -> _PreparedBatch:
        """Retire a previous input before allocating its replacement on the copy stream."""
        prepared = self._next_host_batch()
        if event is not None:
            event.synchronize()
        if prepared.batch is not None and self._device_prefetch is not None:
            prepared.batch = self._device_prefetch(prepared.batch)
        if isinstance(prepared.batch, DevicePrefetchedStep):
            prepared.ready_event = prepared.batch.ready_event
        return prepared
308
309
310
311
312
313
314
315
316
    def _next_device_batch(self) -> _PreparedBatch:
        """Broadcast on the training stream after waiting for only the current copy."""
        try:
            if self._topology.is_constructor:
                self._prefetch_device_batches(1, blocking=True, on_demand=True)
                prepared = self._device_batches.popleft()
            else:
                prepared = self._next_host_batch()
                prefetch_wait_event = self._prefetch_slots.popleft()
329
330
331
332
333
334
335
336
337
                self._model_transport.broadcast(None, error=prepared.error)
            )
        except BaseException as exc:
            self._batch_error = exc
            self._device_stopped = True
            self._device_batches.clear()
            raise
        finally:
            # Explicit drains must cover partially submitted broadcasts on errors
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
        # Queued events belong to the copy stream, independently of the last
        # delivered batch's training-stream marker. Neither drain broadcasts ahead.
        if ready_event is not None:
            ready_event.synchronize()
        if self._host_request is not None:
            self._host_request.result()

    def close(self) -> None:
        """Drain the producer before releasing buffered inputs and reader resources."""
        try:
            with ExitStack() as cleanup:
                if self._groups is not None:
                    cleanup.callback(self._groups.close)
                if self._closed:
                    return
                cleanup.callback(self._source.close)
                if self._worker is not None and self._worker is not self._source:
                    cleanup.callback(self._worker.close)
                if self._device_prefetch is not None:
                    cleanup.callback(self._device_prefetch.close)
                # Ranks can stage different amounts during next(). Catch up to the same
                # lookahead before any child exits its outstanding data collectives.
                self._fill_requested_device_prefetch()
                if self._last_ready_event is not None:
                    self._last_ready_event.synchronize()
        finally:
            self._current = None
            self._host_request = None
            self._device_batches.clear()
            self._consumer_stream = None
            self._prefetch_slots.clear()
            self._batch_error = None
395
396
397
398
399
400
401
402
403
            self._prefetch_slots.clear()
            self._batch_error = None
            self._last_ready_event = None
            self._closed = True
            self._worker = None

    def __enter__(self) -> "DistributedDataLoader":
        """Support deterministic cleanup on early loop exit."""
        return self
433
434
435
436
437
438
439
440
441
442
443
444
445
        Args:
            state_dict: Saved native cursor at a complete optimizer-step boundary.
        """
        self._validate_restore_boundary()
        self._source.load_state_dict(state_dict)
        self._delivered_state = self._source.snapshot()

    def _validate_restore_boundary(self) -> None:
        if self._last_ready_event is not None or self._worker is not None or self._has_delivered:
            raise ValueError("load_state_dict must run before distributed iteration starts.")

    def set_epoch(self, epoch: int) -> None:
        """Reset the native source while retaining the data worker and copy stream.
457
458
459
460
461
462
463
464
465
466
467
468
469
            return
        self.wait_for_prefetch()
        if self._device_prefetch is not None:
            self._device_prefetch.close()
        self._source.set_epoch(epoch)
        if self._worker is not None and self._worker is not self._source:
            self._worker.set_epoch(epoch)
        self._current = None
        self._host_request = None
        self._device_batches.clear()
        self._consumer_stream = None
        self._prefetch_slots = deque([None] * (self._device_prefetch_depth + 1))
        self._device_stopped = False
470
471
472
473
474
475
476
477
        self._prefetch_target = 0
        self._batch_error = None
        self._last_ready_event = None
        self._has_delivered = False
        self._delivered_state = self._source.snapshot()


__all__ = ["DistributedDataLoader"]
hyper_parallel/distributed_data/external_source.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

    def __init__(self, source: Any, *, config: Any, metadata_fn: Any, pack_fn: Any,
                 collate_fn: Any, planner: Any, global_rank: int, ranks: tuple[int, ...]) -> None:
        """Capture an unstarted external source and its CPU callbacks."""
        self._source = source
        self.config = config
        self._metadata_fn = metadata_fn
        self._pack_fn = pack_fn
        self._collate_fn = collate_fn
        self._planner = planner
        self._global_rank = global_rank
        self.group_ranks = ranks
        self._data_rank = ranks.index(global_rank)
        self._transport = None
        self._iterator = None
        self._step = 0

    @property
    def global_rank(self) -> int:
        """Return the logical source rank in the training mesh."""
        return self._global_rank

    def bind_transport(self, transport: DataPlaneTransport) -> None:
        """Bind collectives reconstructed in the owning process.
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

        Args:
            transport: Data-plane collectives owned by this source process.
        """
        self._transport = transport

    def __next__(self) -> LocalBatch:
        """Construct one selected step without changing sample membership."""
        if self._iterator is None:
            self._iterator = iter(self._source)
        result = self._construct_batch(next(self._iterator), self._step)
        self._step += 1
        return result

    def reset_iteration(self) -> None:
        """Discard the exhausted iterator while retaining the original source object."""
        self._iterator = None
        self._step = 0

    def set_epoch(self, epoch: int) -> None:
        """Select the external source epoch before constructing its next iterator.
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110

        Args:
            epoch: Non-negative epoch to select before the next source read.
        """
        self.reset_iteration()
        setter = getattr(self._source, "set_epoch", None)
        if callable(setter):
            setter(epoch)

    def close(self) -> None:
        """Drop source iterators in the process that owns their workers."""
        self._iterator = None

    def _construct_batch(
            self,
            raw_bins: Sequence[Sequence[Any]],
109
110
111
112
113
114
115
116
117
118
119
120
            self,
            raw_bins: Sequence[Sequence[Any]],
            step: int,
    ) -> LocalBatch:
        metadata, local_payloads = self._read_step(raw_bins, step)
        gathered = self._transport.all_gather_object(metadata)
        plan, stats = self._plan_step(gathered, step)
        return self._finish_batch(self._begin_batch(local_payloads, plan, stats))

    def _begin_batch(
            self, local_payloads: dict[SampleKey, Any], plan: DistributedPackingPlan, stats: dict[str, Any],
    ) -> _PendingBatch:
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    def _begin_batch(
            self, local_payloads: dict[SampleKey, Any], plan: DistributedPackingPlan, stats: dict[str, Any],
    ) -> _PendingBatch:
        """Start payload exchange for moved samples while retaining local destinations."""
        if stats["moved_samples"]:
            outgoing: dict[int, list[tuple[SampleKey, Any]]] = {}
            retained_payloads = {}
            for data_rank, local_batch in enumerate(plan.local_batches):
                target_rank = self.group_ranks[data_rank]
                owned = [
                    (key, local_payloads[key])
                    for packing_bin in local_batch
                    for key in packing_bin.sample_keys
                    if key.reader_rank == self._global_rank
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
                    for packing_bin in local_batch
                    for key in packing_bin.sample_keys
                    if key.reader_rank == self._global_rank
                ]
                if target_rank == self._global_rank:
                    retained_payloads.update(owned)
                else:
                    outgoing[target_rank] = owned
            prepared = self._transport.prepare_exchange(outgoing)
            work = self._transport.begin_exchange_prepared(prepared)
        else:
            # Every rank sees the same plan and skips an unchanged exchange.
            retained_payloads = local_payloads
            work = None
        return _PendingBatch(plan, stats, retained_payloads, work)

    def _finish_batch(self, pending: _PendingBatch) -> LocalBatch:
        """Complete payload exchange, pack and collate the local batch, return CPU tensors."""
        received = pending.retained_payloads
        if pending.payload_work is not None:
            received.update(pending.payload_work.wait())
        target = pending.plan.local_batch_for(self._data_rank)
        host_batch = self._collate_fn([
            self._pack_fn([received[key] for key in packing_bin.sample_keys], self.config.seq_len)
            for packing_bin in target
        ])
        return LocalBatch(host_batch, pending.stats, host_batch)

    def _read_step(self, raw_bins: Sequence[Sequence[Any]], step: int) -> tuple[tuple[Any, ...], dict[SampleKey, Any]]:
        """Bind raw source bins to keyed metadata and cached payloads for one step."""
        if len(raw_bins) != self.config.local_batch_size or any(not raw_bin for raw_bin in raw_bins):
            raise ValueError("Each source step must contain local_batch_size non-empty raw-sample bins.")
        key_bins = []
        entries = []
        payloads = {}
        for raw_bin in raw_bins:
            keys = []
            for sample in raw_bin:
                item_metadata = self._metadata_fn(sample)
                if not isinstance(item_metadata, SampleMetadata):
                    raise ValueError("metadata_fn must return SampleMetadata.")
                key = SampleKey(self._global_rank, step, len(entries))
                entries.append(replace(item_metadata, key=key))
                payloads[key] = sample
                keys.append(key)
            key_bins.append(tuple(keys))
        return (tuple(key_bins), tuple(entries)), payloads

    def _plan_step(self, gathered: Sequence[Any], step: int) -> tuple[DistributedPackingPlan, dict[str, Any]]:
        planned = self._make_plan(gathered, step)
        return self._transport.broadcast_from_planner(planned) if self.config.broadcast_plan else planned

    def _make_plan(self, gathered: Sequence[Any], step: int) -> Any:
        """Build a plan and balancing statistics on the designated planning ranks."""
        if self.config.broadcast_plan and self._global_rank != self._transport.planner_rank:
            return None
        rank_bins, rank_entries = zip(*gathered)
        metadata = {item.key: item for item in chain.from_iterable(rank_entries)}
        if self.config.balance_window_size == 1:
            plan = self._planner.plan(
                tuple(metadata.values()), reference_bins=list(chain.from_iterable(rank_bins)), step=step,
            )
            costs, decision = self._planner.last_sample_costs, self._planner.last_balance_decision
        else:
            plan, costs, decision = self._plan_windows(rank_bins, metadata, step)
        bin_stats = self._bin_statistics(rank_bins, metadata, plan, costs)
        stats = self._statistics(plan, step, bin_stats["bins_before"])
        stats.update(decision)
        if self._transport.planner_rank == 0:
            stats.update(bin_stats)
        return plan, stats

    def _plan_windows(
            self, rank_bins: Sequence[Sequence[Sequence[SampleKey]]],
            metadata: dict[SampleKey, SampleMetadata], step: int,
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
            self, rank_bins: Sequence[Sequence[Sequence[SampleKey]]],
            metadata: dict[SampleKey, SampleMetadata], step: int,
    ) -> tuple[DistributedPackingPlan, dict[SampleKey, WorkloadCost], dict[str, Any]]:
        """Plan consecutive bins inside this source yield, retaining one physical destination per rank."""
        rounds = list(zip(*rank_bins, strict=True))
        plans = []
        windows = []
        costs = {}
        width = self.config.balance_window_size
        for start in range(0, len(rounds), width):
            bins = list(chain.from_iterable(rounds[start:start + width]))
            selected = [metadata[key] for packing_bin in bins for key in packing_bin]
            plans.extend(self._planner.plan_window(selected, reference_bins=bins, step=step * len(rounds) + start))
            costs.update(self._planner.last_sample_costs)
            windows.append({
                **self._planner.last_balance_decision, "first_micro_batch": start + 1, "last_micro_batch": len(plans),
            })

        ranks = range(len(rank_bins))
        local_batches = tuple(tuple(plan.local_batch_for(rank)[0] for plan in plans) for rank in ranks)
        rank_costs = tuple(sum((plan.rank_costs[rank] for plan in plans), WorkloadCost()) for rank in ranks)
        combined = DistributedPackingPlan(step, self.config.seq_len, local_batches, rank_costs, validate=False)
        original = math.fsum(window["original_objective"] for window in windows)
        candidate = math.fsum(window["candidate_objective"] for window in windows)
        return combined, costs, {
            "windows": windows, "original_objective": original, "candidate_objective": candidate,
            "accepted_objective": math.fsum(window["accepted_objective"] for window in windows),
            "relative_gain": (original - candidate) / original if original else 0.0,
            "min_balance_gain": self.config.min_balance_gain, "accepted": any(window["accepted"] for window in windows),
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
            plan: DistributedPackingPlan, sample_costs: dict[SampleKey, WorkloadCost],
    ) -> dict[str, Any]:
        """Summarize original and accepted bins using the planner's estimates, including padding."""

        def _describe(keys: Sequence[SampleKey]) -> dict[str, Any]:
            tokens = sum(metadata_by_key[key].pack_tokens for key in keys)
            padding = max(0, self._planner.seq_len - tokens)
            return {
                "samples": len(keys), "seq_len": tokens, "padding": padding,
                "cost": math.fsum(sample_costs[key].llm for key in keys) + self._planner.padding_cost(padding).llm,
            }

        before = tuple(tuple(_describe(keys) for keys in key_bins) for key_bins in rank_bins)
        after = tuple(
            tuple(_describe(packing_bin.sample_keys) for packing_bin in local_batch)
            for local_batch in plan.local_batches
        )
        return {"bins_before": before, "bins_after": after}

    def _statistics(
            self, plan: DistributedPackingPlan, step: int, bins_before: Sequence[Sequence[dict[str, Any]]],
    ) -> dict[str, Any]:
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    def _statistics(
            self, plan: DistributedPackingPlan, step: int, bins_before: Sequence[Sequence[dict[str, Any]]],
    ) -> dict[str, Any]:
        """Count cross-rank raw-sample transfers, excluding locally retained samples."""
        before = [math.fsum(packing_bin["cost"] for packing_bin in bins) for bins in bins_before]
        after = [cost.llm for cost in plan.rank_costs]
        send_samples = [0] * len(self.group_ranks)
        recv_samples = [0] * len(self.group_ranks)
        moved = 0
        source_indices = {rank: index for index, rank in enumerate(self.group_ranks)}
        for data_rank, local_batch in enumerate(plan.local_batches):
            for packing_bin in local_batch:
                for key in packing_bin.sample_keys:
                    source_index = source_indices[key.reader_rank]
                    if source_index != data_rank:
                        send_samples[source_index] += 1
                        recv_samples[data_rank] += 1
                        moved += 1
        mean_before = math.fsum(before) / len(before)
        mean_after = math.fsum(after) / len(after)
        max_before, max_after = max(before), max(after)
        return {
            "step": step,
            "scope": "node",
            "objective": self._planner.objective,
            "group_ranks": self.group_ranks,
hyper_parallel/distributed_data/locality.py
103
104
105
106
107
108
109
110
111
112
113
114
115
        return [status]
    startup_group = None
    if backend == "gloo":
        startup_group = dist.new_group(ranks=list(range(dist.get_world_size())), backend="gloo")
    try:
        return list(all_gather_control_object(status, group=startup_group, device=device, backend=backend))
    finally:
        if startup_group is not None:
            dist.destroy_process_group(startup_group)


def _create_locality_groups(
        mesh: Any,
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
        )
        rank_groups = _node_rank_groups(topology, dict(statuses))
    else:
        rank_groups = _fixed_rank_groups(topology, balance_group_size)
    own_ranks = next(ranks for ranks in rank_groups if rank in ranks)
    own_groups = DataGroups(own_ranks, None, None, None, min(own_ranks), distributed)
    if not distributed:
        return topology, own_groups
    with own_groups.close_on_error():
        for ranks in rank_groups:
            control, payload = _create_data_plane_process_groups(
                groups=own_groups, topology=topology, data_plane_ranks=ranks,
                cpu_backend=communication_backend, payload_backend=communication_backend,
                reuse_control_group=communication_backend == "gloo", enable_payload_exchange=True,
            )
            if rank in ranks:
                own_groups.control_group = control
                own_groups.payload_group = payload
    return topology, own_groups
hyper_parallel/distributed_data/metadata.py
114
115
116
117
118
119
120
121
122
123
124
125
    def close(self) -> None:
        """Stop owned persistent workers after the caller has drained sample reads."""
        # PyTorch exposes no public close API; persistent workers are retained
        # by the native loader's iterator even after all requested samples arrive.
        iterator = self._data_loader._iterator
        if iterator is not None:
            iterator._shutdown_workers()
            self._data_loader._iterator = None

    def state_dict(self) -> dict[str, Any]:
        """Return the epoch required to seed future plan-aware workers."""
        return {
hyper_parallel/distributed_data/native_source.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
                 data_constructor: Any, initial_epoch: int, initial_consumed_samples: int,
                 broadcast_plan: bool, log_balance: bool, accumulation_steps: int,
                 balance_window_size: int) -> None:
        """Capture CPU-only components before any dataset workers are started."""
        self._topology = topology
        self._dataset_reader_ranks = frozenset(dataset_reader_ranks)
        self._dataset_reader = dataset_reader
        self._metadata_reader = metadata_reader
        self._direct_sample_loader = direct_sample_loader
        self._metadata_mode = metadata_mode
        self._planner = planner
        self._data_constructor = data_constructor
        self._broadcast_plan = broadcast_plan
        self._log_balance = log_balance
        self._accumulation_steps = accumulation_steps
        self._balance_window_size = balance_window_size
        self._epoch = initial_epoch
        self._initial_consumed_samples = initial_consumed_samples
        self._step = 0
        self._stopped = False
        self._pending_local_keys = set()
        self._window_plans = deque()
        self._balance_logs = []
        self._data_plane = None

    @property
    def global_rank(self) -> int:
        """Return the logical sample-owner rank in the training mesh."""
        return self._topology.global_rank

    def bind_transport(self, transport: DataPlaneTransport) -> None:
        """Attach the child-owned data group after deserializing CPU components.
85
86
87
88
89
90
91
92

        Args:
            transport: Data-plane collectives owned by this source process.
        """
        self._data_plane = transport

    def prefetch(self) -> None:
        """In-process sources prepare their window when the caller requests the result."""
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

        Args:
            timeout: Maximum seconds to wait for a ready result.
        """
        del timeout
        return True

    def __next__(self) -> PreparedWindow:
        """Prepare one window; only parent delivery commits its checkpoint."""
        return self._prepare_window()

    def close(self) -> None:
        """Release source DataLoader workers in their owning process."""
        reader = self._planning_reader()
        if reader is not None:
            reader.close()
        if self._direct_sample_loader is not None:
            self._direct_sample_loader.close()

    def set_epoch(self, epoch: int) -> None:
        """Reset sampling after the parent has drained the previous epoch.
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

        Args:
            epoch: Non-negative epoch to select before the next source read.
        """
        for reader in (self._dataset_reader, self._metadata_reader, self._direct_sample_loader):
            if reader is not None:
                reader.set_epoch(epoch)
        self._epoch = epoch
        self._step = 0
        self._initial_consumed_samples = 0
        self._stopped = False
        self._pending_local_keys.clear()
        self._window_plans.clear()
        self._balance_logs = []

    def _prepare_batch(self) -> Any:
        """Construct one CPU round; model peers receive batches only at parent delivery."""
        if self._stopped:
            raise StopIteration
        batch = self._prepare_next_batch()
        if self._stopped:
            raise StopIteration
        return self._consume_batch(batch)

    def _prepare_next_batch(self) -> Any:
        if self._data_plane.is_member:
            return self._produce_on_data_plane()
        return None

    def _prepare_window(self) -> PreparedWindow:
        """Prepare Host batches up to the window, optimizer-step or epoch boundary."""
        window_micro_batch_num = min(
            self._balance_window_size, self._accumulation_steps - self._step % self._accumulation_steps,
        )
        self._balance_logs = []
        self._prepare_local_metadata(window_micro_batch_num)
        batches = deque()
        exhausted = False
        for _ in range(window_micro_batch_num):
            try:
                batch = self._prepare_batch()
            except StopIteration:
                exhausted = True
                break
            batches.append(batch)
        # Intermediate windows must replay from the optimizer step's beginning.
        checkpoint = self.snapshot() if not exhausted and self._step % self._accumulation_steps == 0 else None
        return PreparedWindow(batches, exhausted, checkpoint, balance_logs=self._balance_logs)

    def _consume_batch(self, received: Any) -> Any:
        """Commit Host preparation; delivery publishes checkpoints only after broadcast."""
        # Non-Constructors hold placeholders; the caller receives both
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    def _consume_batch(self, received: Any) -> Any:
        """Commit Host preparation; delivery publishes checkpoints only after broadcast."""
        # Non-Constructors hold placeholders; the caller receives both
        # real batches and the EOF sentinel from their Constructor's broadcast.
        planning_reader = self._planning_reader()
        if planning_reader is not None:
            planning_reader.commit(self._pending_local_keys)
        self._pending_local_keys.clear()
        self._step += 1
        return received

    def snapshot(self) -> dict[str, Any]:
        """Capture producer progress at an optimizer-step boundary."""
        reader = self._planning_reader()
        reader_state = reader.state_dict() if reader is not None else None
        payload_state = (
            self._direct_sample_loader.state_dict() if self._direct_sample_loader is not None
            else (reader_state or {}).get("sample_loader")
        )
        state = {
            "epoch": self._epoch,
            "step": self._step,
            "stopped": self._stopped,
            "dataset_state": (
190
191
192
193
194
195
196
197
198
199
200
201
202
            "dataset_state": (
                {key: payload_state[key] for key in ("dataset_size", "seed")} if payload_state is not None else None
            ),
        }
        if reader_state is not None:
            state["_index_sampler_state"] = reader_state["sampler"]
        elif self._initial_consumed_samples is not None:
            # Model peers have no Reader; advance their cursor from the known initial position.
            state["_index_sampler_state"] = {
                "consumed_samples": self._initial_consumed_samples + (
                    self._step * self._planner.local_batch_size * self._topology.data_parallel_size
                ),
                "epoch": self._epoch,
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
                    self._accumulation_steps * self._planner.local_batch_size * self._topology.data_parallel_size
                ),
                "dp_world_size": self._topology.data_parallel_size,
            }
            sampler = state["_index_sampler_state"]
            offset = self._initial_consumed_samples % sampler["global_batch_size"]
            if offset:
                sampler["optimizer_step_offset"] = offset
        try:
            copied_state = copy.deepcopy(state)
        except Exception as exc:
            raise ValueError(f"Distributed DataLoader state is not checkpointable: {exc}") from exc
        return copied_state

    def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
        """Restore a shared native cursor or a legacy rank-local checkpoint.
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250

        Args:
            state_dict: A complete-step cursor; legacy rank-local state must match this rank.
        """
        try:
            state = copy.deepcopy(dict(state_dict))
        except Exception as exc:
            raise ValueError(f"Distributed DataLoader state is not copyable: {exc}") from exc
        if state.get("global_rank") not in (None, self._topology.global_rank):
            raise ValueError(
                f"Distributed DataLoader checkpoint global_rank={state.get('global_rank')!r} "
                f"does not match {self._topology.global_rank!r}."
            )
        epoch, step, stopped = self._validate_checkpoint_values(state)
        sampler = get_sampler_checkpoint_state(state)
        self._validate_optimizer_boundary(state, sampler, step)
        if sampler is not None:
            epoch, step = self._progress_from_sampler(sampler)
        elif self._dataset_reader is not None or self._metadata_reader is not None or state.get("global_rank") is None:
            raise ValueError("Distributed DataLoader checkpoint has no native sampler cursor.")
        self._restore_component_states(state, sampler, epoch)
        self._epoch = epoch
        self._step = step
        self._stopped = stopped
        self._initial_consumed_samples = None
        if sampler is not None:
            self._initial_consumed_samples = sampler["consumed_samples"] - (
                step * self._planner.local_batch_size * self._topology.data_parallel_size
            )

    def _validate_optimizer_boundary(self, state: Mapping[str, Any], sampler: Mapping[str, Any] | None,
251
252
253
254
255
256
257
258
259
260
261
262
263
264
                                     step: int) -> None:
        """Reject speculative or incomplete optimizer-step checkpoints."""
        # Legacy step counters use the source accumulation size. The sampler
        # cursor validates complete steps independently of the target GBS/DP.
        layout_changed = sampler is not None and (
            sampler["global_batch_size"] != (
                self._accumulation_steps * self._planner.local_batch_size * self._topology.data_parallel_size
            ) or sampler["dp_world_size"] != self._topology.data_parallel_size
        )
        if (
                (not layout_changed and step % self._accumulation_steps) or state.get("window_plans")
                or state.get("optimizer_step_remaining", self._accumulation_steps) != self._accumulation_steps
                or any(isinstance(state.get(key), Mapping) and "window" in state[key]
                       for key in ("dataset_reader", "metadata_reader", "sidecar_reader"))
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
                or state.get("optimizer_step_remaining", self._accumulation_steps) != self._accumulation_steps
                or any(isinstance(state.get(key), Mapping) and "window" in state[key]
                       for key in ("dataset_reader", "metadata_reader", "sidecar_reader"))
        ):
            raise ValueError("Distributed DataLoader checkpoint must align to a complete optimizer step.")

    def _progress_from_sampler(self, sampler: Mapping[str, Any]) -> tuple[int, int]:
        """Validate the shared cursor and derive the epoch and micro-batch position."""
        global_micro_batch_size = self._planner.local_batch_size * self._topology.data_parallel_size
        global_batch_size = self._accumulation_steps * global_micro_batch_size
        consumed, epoch = sampler["consumed_samples"], sampler["epoch"]
        if any(isinstance(value, bool) or not isinstance(value, int) for value in (consumed, epoch)):
            raise ValueError("Sampler consumed_samples and epoch must be integers")
        if sampler_optimizer_step_progress(sampler) or epoch < 0:
            raise ValueError("Sampler cursor must align to a complete optimizer step")
        if sampler["global_batch_size"] != global_batch_size:
            return epoch, 0
        offset = sampler.get("optimizer_step_offset") or 0
        return epoch, (consumed - offset) // global_micro_batch_size


    @staticmethod
    def _validate_checkpoint_values(state: Mapping[str, Any]) -> tuple[int, int, bool]:
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301

    @staticmethod
    def _validate_checkpoint_values(state: Mapping[str, Any]) -> tuple[int, int, bool]:
        """Validate and return the saved epoch, micro-batch index and stopped flag."""
        epoch = state.get("epoch", 0)
        step = state.get("step", 0)
        stopped = state.get("_iterator_finished")
        if stopped is None:
            stopped = state.get("stopped", False)
        if not isinstance(epoch, int) or isinstance(epoch, bool) or epoch < 0:
            raise ValueError("Distributed DataLoader checkpoint epoch must be non-negative.")
        if not isinstance(step, int) or isinstance(step, bool) or step < 0:
            raise ValueError("Distributed DataLoader checkpoint step must be non-negative.")
        if not isinstance(stopped, bool):
            raise ValueError("Distributed DataLoader checkpoint stopped must be boolean.")
        return epoch, step, stopped

    def _restore_component_states(
            self,
            state: Mapping[str, Any],
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
            sampler_state: Mapping[str, Any] | None,
            epoch: int,
    ) -> None:
        """Rebuild current Readers from shared progress and optional Dataset checks."""
        reader = self._planning_reader()
        reader_state = reader.state_dict() if reader is not None else None
        payload_state = (
            self._direct_sample_loader.state_dict() if self._direct_sample_loader is not None
            else (reader_state or {}).get("sample_loader")
        )
        self._validate_dataset_state(state, payload_state)
        if payload_state is not None:
            payload_state["epoch"] = epoch
        if reader is not None:
            reader_state.update(epoch=epoch, sampler=sampler_state)
            if reader_state["sample_loader"] is not None:
                reader_state["sample_loader"] = payload_state
            reader.load_state_dict(reader_state)
        if self._direct_sample_loader is not None:
            self._direct_sample_loader.load_state_dict(payload_state)

    @staticmethod
    def _validate_dataset_state(state: Mapping[str, Any], payload_state: Mapping[str, Any] | None) -> None:
        """Validate balanced-reader metadata without interpreting user Dataset state."""
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    def _validate_dataset_state(state: Mapping[str, Any], payload_state: Mapping[str, Any] | None) -> None:
        """Validate balanced-reader metadata without interpreting user Dataset state."""
        # Native torchdata Dataset state belongs to the user's Dataset. Only
        # cursor-only and legacy balanced states carry our Dataset compatibility fields.
        if not has_torchdata_state(state):
            candidates = [state.get("dataset_state"), state.get("direct_sample_loader")]
            for key in ("dataset_reader", "metadata_reader", "sidecar_reader"):
                legacy_reader = state.get(key)
                if isinstance(legacy_reader, Mapping):
                    candidates.append(legacy_reader.get("sample_loader"))
            for saved in candidates:
                if saved is None or payload_state is None:
                    continue
                if not isinstance(saved, Mapping):
                    raise ValueError("Dataset checkpoint state must be a mapping.")
                for key in ("dataset_size", "seed"):
                    if saved.get(key) is not None and saved[key] != payload_state[key]:
                        raise ValueError(f"Dataset checkpoint {key} does not match the current loader.")

    def _produce_on_data_plane(self) -> Any:
        """Execute one plan through direct reads or payload exchange, then construct the batch."""
        plan = self._next_plan_control()
        if plan is None:
            self._stopped = True
            return None

        self._pending_local_keys = {
            key for key in plan.selected_keys if key.reader_rank == self._topology.global_rank
        }
        if self._metadata_mode:
            if not self._topology.is_constructor:
                return None
            received_payloads = self._direct_sample_loader.fetch_samples(
                plan.local_sample_keys(self._topology.data_rank)
            )
        else:
            prepared_exchange = self._prepare_outgoing(plan, self._pending_local_keys)
            received_payloads = self._data_plane.exchange_prepared(prepared_exchange)
            # Reader-only ranks must finish routing before leaving this round.
            if not self._topology.is_constructor:
                return None
        return self._construct_received_payloads(plan, received_payloads)

    def _construct_received_payloads(
            self,
            plan: DistributedPackingPlan,
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
            plan: DistributedPackingPlan,
            received_payloads: dict[SampleKey, Any],
    ) -> Any:
        """Construct one local batch; the caller must be a Data Constructor."""
        local_batch_plan = plan.local_batch_for(self._topology.data_rank)
        local_batch = self._data_constructor.construct(local_batch_plan, received_payloads)
        # None is reserved for distributed end-of-stream.
        if local_batch is None:
            raise ValueError("The Data Constructor must return a non-None batch.")
        return local_batch

    def _next_plan_control(self) -> DistributedPackingPlan | None:
        """Pop one micro-batch plan, planning a new window only when the cache is empty."""
        if self._window_plans:
            return self._window_plans.popleft()
        planning_reader = self._planning_reader()
        local_input = planning_reader.planning_input() if planning_reader is not None else _ReaderPlanInput()
        if self._broadcast_plan:
            gathered_inputs = self._data_plane.gather_object_to_planner(local_input)
            plan = None
            if self._topology.global_rank == self._data_plane.planner_rank:
                plan = self._build_plan_control(gathered_inputs)
            plan = self._data_plane.broadcast_from_planner(plan)
        else:
            plan = self._build_plan_control(self._data_plane.all_gather_object(local_input))
        if isinstance(plan, tuple):
            self._window_plans.extend(plan)
            return self._window_plans.popleft()
        return plan

    def _prepare_local_metadata(self, window_micro_batch_num: int) -> None:
        """Read one explicitly sized source window before constructing its batches."""
        if self._topology.global_rank not in self._dataset_reader_ranks:
            return
        planning_reader = self._planning_reader()
        planning_reader.prepare_next_step(window_micro_batch_num)

    def _build_plan_control(
            self, gathered_inputs: tuple[_ReaderPlanInput, ...],
    ) -> _PlanControl:
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
            self, gathered_inputs: tuple[_ReaderPlanInput, ...],
    ) -> _PlanControl:
        """Return the native window's plans; None means end of stream."""
        # Collective rank order can differ from the mesh's logical DP order.
        inputs_by_rank = dict(zip(self._data_plane.ranks, gathered_inputs))
        reader_inputs = [
            inputs_by_rank[rank] for rank in self._topology.constructor_ranks
            if rank in self._dataset_reader_ranks
        ]
        return self._plan_native_batch(reader_inputs)

    def _native_window_micro_batch_num(self, reader_inputs: list[_ReaderPlanInput]) -> int:
        """Validate complete synchronized source rounds before constructing reference bins."""
        if all(not item.original_batches for item in reader_inputs):
            return 0
        if any(not item.original_batches for item in reader_inputs):
            raise ValueError("Native BatchSampler ranks exhausted at different forward/backward rounds.")
        counts = {len(item.original_batches) for item in reader_inputs}
        if len(counts) != 1 or any(
                len(batch) != self._planner.local_batch_size
                for item in reader_inputs for batch in item.original_batches
        ):
            raise ValueError("Native BatchSampler ranks must provide equal complete micro-batch windows.")
        return next(iter(counts))

    def _plan_native_batch(
            self, reader_inputs: list[_ReaderPlanInput],
    ) -> _PlanControl:
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
    def _plan_native_batch(
            self, reader_inputs: list[_ReaderPlanInput],
    ) -> _PlanControl:
        """Plan the native sampler window, returning one plan per training round."""
        window_micro_batch_num = self._native_window_micro_batch_num(reader_inputs)
        if not window_micro_batch_num:
            return None
        reference_bins = tuple(
            keys for batches in zip(*(item.original_batches for item in reader_inputs))
            for batch in batches for keys in batch
        )
        metadata_by_key = {metadata.key: metadata for item in reader_inputs for metadata in item.metadata}
        samples = tuple(metadata_by_key[key] for keys in reference_bins for key in keys)
        plan = self._planner.plan if window_micro_batch_num == 1 else self._planner.plan_window
        plans = plan(samples, reference_bins=reference_bins, step=self._step)
        self._capture_balance_log(samples, reference_bins, plans)
        return plans

    def _capture_balance_log(
            self, samples: tuple[SampleMetadata, ...], reference_bins: tuple[tuple[SampleKey, ...], ...],
            plans: DistributedPackingPlan | tuple[DistributedPackingPlan, ...],
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
            self, samples: tuple[SampleMetadata, ...], reference_bins: tuple[tuple[SampleKey, ...], ...],
            plans: DistributedPackingPlan | tuple[DistributedPackingPlan, ...],
    ) -> None:
        """Freeze scalar window statistics before the producer advances to another plan."""
        if (
            not self._log_balance
            or self._topology.global_rank != self._data_plane.planner_rank
            or not balance_logger.isEnabledFor(logging.INFO)
        ):
            return
        plans = plans if isinstance(plans, tuple) else (plans,)
        metadata = {item.key: item for item in samples}
        costs = self._planner.last_sample_costs

        def describe(keys: tuple[SampleKey, ...]) -> dict[str, Any]:
            """Combine evaluated document costs with this layout's constructor padding.

            Args:
                keys: Sample occurrences assigned to one pack.
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487

            Args:
                keys: Sample occurrences assigned to one pack.
            """
            tokens = sum(metadata[key].pack_tokens for key in keys)
            padding = max(0, self._planner.seq_len - tokens)
            return {
                "seq_len": tokens, "samples": len(keys), "padding": padding,
                "cost": math.fsum(costs[key].llm for key in keys) + self._planner.padding_cost(padding).llm,
            }

        local_size = self._planner.local_batch_size
        bin_count = self._planner.distributed_bin_count
        rounds = []
        for offset, plan in enumerate(plans):
            original = reference_bins[offset * bin_count:(offset + 1) * bin_count]
            rounds.append({
                "micro_batch": plan.step % self._accumulation_steps + 1,
                "bins_before": tuple(
                    tuple(describe(keys) for keys in original[start:start + local_size])
                    for start in range(0, bin_count, local_size)
490
491
492
493
494
495
496
497
498
                    tuple(describe(packing_bin.sample_keys) for packing_bin in local_batch)
                    for local_batch in plan.local_batches
                ),
            })
        stats = {
            **self._planner.last_balance_decision,
            "objective": self._planner.objective, "epoch": self._epoch,
            "planner_rank": self._data_plane.planner_rank,
            "constructor_ranks": self._topology.constructor_ranks,
497
498
499
500
501
502
503
504
505
            "planner_rank": self._data_plane.planner_rank,
            "constructor_ranks": self._topology.constructor_ranks,
            "group_ranks": tuple(range(self._topology.data_parallel_size)), "rounds": rounds,
        }
        self._balance_logs.append(format_balance_stats(stats, self._step // self._accumulation_steps + 1))

    def _prepare_outgoing(
            self,
            plan: DistributedPackingPlan,
505
506
507
508
509
510
511
512
513
514
515
516
            plan: DistributedPackingPlan,
            local_selected_keys: set[SampleKey],
    ) -> PreparedPayloadExchange:
        """Group source-owned payloads by destination Constructor for transport encoding."""
        payloads_by_target_rank: dict[int, list[tuple[SampleKey, Any]]] = {}
        if local_selected_keys:
            payloads = self._dataset_reader.selected_payloads(local_selected_keys)
            target_by_key = {
                key: self._topology.constructor_ranks[data_rank]
                for data_rank, local_batch in enumerate(plan.local_batches)
                for packing_bin in local_batch
                for key in packing_bin.sample_keys
514
515
516
517
518
519
520
521
522
523
524
525
526
                for data_rank, local_batch in enumerate(plan.local_batches)
                for packing_bin in local_batch
                for key in packing_bin.sample_keys
            }
            for key, payload in payloads:
                payloads_by_target_rank.setdefault(target_by_key[key], []).append((key, payload))
        return self._data_plane.prepare_exchange(payloads_by_target_rank)

    def _planning_reader(self) -> Any | None:
        """Return this rank's online or metadata-only Dataset Reader."""
        if self._dataset_reader is not None:
            return self._dataset_reader
        return self._metadata_reader
hyper_parallel/distributed_data/packed_balancing.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        self.local_dataloader = local_dataloader
        self.config = config
        self.group_ranks = transport.ranks
        self.prefetches_to_device = device_prefetch is not None
        self.last_balance_stats = None
        self.last_host_batch = None
        self._source = ExternalStepProducer(local_dataloader, config=config, metadata_fn=metadata_fn,
                                            pack_fn=pack_fn, collate_fn=collate_fn, planner=planner,
                                            global_rank=global_rank, ranks=transport.ranks)
        self._transport = transport
        self._groups = groups
        self._global_rank = global_rank
        self._device_prefetch = device_prefetch
        self._balance_stats_callback = balance_stats_callback
        self._worker = None
        if not config.use_data_process:
            self._source.bind_transport(transport)
            self._worker = self._source
        self._host_request: DataRequest | None = None
        self._staged: LocalBatch | BaseException | None = None
        self._step = 0
        self._finished = False
        self._closed = False

    def _request_host(self) -> None:
        if self._host_request is None:
            if self._worker is None:
                self._worker = create_data_worker(self._source, self._transport)
            self._host_request = DataRequest(self._worker)

    def _stage_next(self, *, blocking: bool) -> None:
        """Receive one CPU result and launch its successor before submitting H2D."""
        if self._staged is not None:
            return
        if self.config.use_data_process:
            self._request_host()
        try:
            if self._host_request is not None:
                if not blocking and not self._host_request.is_ready():
                    return
                result = self._host_request.result()
                self._host_request = DataRequest(self._worker)
            else:
                result = next(self._source)
            if self._device_prefetch is not None:
                result = replace(result, data=self._device_prefetch(result.data))
            self._staged = result
        except BaseException as error:  # pylint: disable=broad-exception-caught
            # Deliver a callback or copy failure at its own step, after any preceding batch.
            self._staged = error

    def prefetch(self) -> None:
        """Start CPU lookahead and stage an available successor on the caller."""
        if self._closed or self._finished or not self.config.use_data_process:
            return
        self._request_host()
        if self.prefetches_to_device:
            self._stage_next(blocking=False)

    def prefetch_plan(self) -> None:
        """Retain the existing hook as an idempotent request for the complete pipeline."""
        self.prefetch()

    def __len__(self) -> int:
        """Return the external source length when available."""
        return len(self.local_dataloader)
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167

    @property
    def step(self) -> int:
        """Return the number of delivered steps, excluding speculative progress."""
        return self._step

    def __next__(self) -> Any:
        """Consume one result and immediately request its successor."""
        if self._closed or self._finished:
            raise StopIteration
        self._stage_next(blocking=True)
        result, self._staged = self._staged, None
        if isinstance(result, BaseException):
            self._finished = True
            raise result
        self._step += 1
        self.last_balance_stats = result.stats
        self.last_host_batch = result.host_batch
        batch = result.data.take_batch() if self.prefetches_to_device else result.data
        if result.stats is not None and self._balance_stats_callback is not None and self._global_rank == 0:
            self._balance_stats_callback(result.stats, self._step)
        if self.prefetches_to_device and self.config.use_data_process:
            self._stage_next(blocking=self._step == 1)
        return batch

    def __iter__(self) -> LocalBalancingDataLoader:
        """Keep unfinished prefetch and re-enter an exhausted source in its owning process."""
        if self._finished and not self._closed:
            self._worker.reset_iteration()
            self._host_request = None
            self._staged = None
            self._finished = False
            self._step = 0
        return self

    def wait_for_prefetch(self) -> None:
        """Drain pending work without consuming or changing the delivered cursor."""
        if self._host_request is not None and self.prefetches_to_device and not self._finished:
            self._stage_next(blocking=True)
        if isinstance(self._staged, BaseException) and not isinstance(self._staged, StopIteration):
            raise self._staged
        if self._host_request is not None:
            try:
                self._host_request.result()
            except StopIteration:
                pass
        if self._device_prefetch is not None:
            self._device_prefetch.close()

    def set_epoch(self, epoch: int) -> None:
        """Reset external iteration after draining the previous source request.
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

        Args:
            epoch: Non-negative epoch to select before the next source read.
        """
        if self._closed:
            raise RuntimeError("Data loader is closed.")
        self.wait_for_prefetch()
        if self._worker is not None:
            self._worker.set_epoch(epoch)
        else:
            self._source.set_epoch(epoch)
        self._host_request = None
        self._staged = None
        self._finished = False
        self._step = 0
        self.last_host_batch = None
        self.last_balance_stats = None

    def state_dict(self) -> dict[str, Any]:
        """Preserve the external source's existing checkpoint ownership contract."""
        raise NotImplementedError("Local balancing does not yet support dataloader checkpoint/resume.")
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
        raise NotImplementedError("Local balancing does not yet support dataloader checkpoint/resume.")

    def close(self) -> None:
        """Drain device copies and release the data process."""
        with ExitStack() as cleanup:
            if self._groups is not None:
                cleanup.callback(self._groups.close)
            if self._closed:
                return
            self._closed = True
            if self._device_prefetch is not None:
                cleanup.callback(self._device_prefetch.close)
            if self._worker is not None:
                cleanup.callback(self._worker.close)
            # Delivery and explicit waits report speculative failures. Close must still release owned resources.
            with suppress(Exception):
                self.wait_for_prefetch()
            self._host_request = None
            self._staged = None
            self.last_host_batch = None


def build_local_balancing_dataloader(
        local_dataloader: Iterable[Sequence[Sequence[Any]]],
282
283
284
285
286
287
288
289
290
291
        balance_group_size=config.balance_group_size,
        communication_backend=config.communication_backend,
        communication_device=communication_device,
    )
    with groups.close_on_error():
        planner = DynamicPackingPlanner(
            data_parallel_size=len(groups.data_plane_ranks),
            seq_len=config.seq_len,
            # Window destinations are (micro-batch, rank), each holding one external bin.
            local_batch_size=config.local_batch_size if config.balance_window_size == 1 else 1,
295
296
297
298
299
300
301
302
303
            balancing_algorithm=balancing_algorithm,
            min_balance_gain=config.min_balance_gain,
            validate=False,
        )
        return LocalBalancingDataLoader(
            local_dataloader,
            groups=groups,
            config=config,
            metadata_fn=metadata_fn,
hyper_parallel/distributed_data/process_data.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61


def _serialize_source(value: tuple) -> bytes:
    """Capture callback globals for the fresh interpreter when dill is available."""
    if _SOURCE_PICKLE is not pickle:
        return _SOURCE_PICKLE.dumps(value, recurse=True)
    try:
        return pickle.dumps(value)
    except (AttributeError, pickle.PicklingError) as exc:
        raise TypeError("Use callbacks from an importable module when dill is unavailable. "
                        f"Could not serialize the data source: {exc}") from exc


def _store_descriptor() -> dict[str, Any]:
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116

def _store_descriptor() -> dict[str, Any]:
    """Reuse the launcher's rendezvous without reading launcher-specific variables."""
    # There is no public accessor for an initialized group's rendezvous store.
    store = dist.distributed_c10d._get_default_store()  # pylint: disable=protected-access
    while isinstance(store, dist.PrefixStore):
        store = store.underlying_store
    if isinstance(store, dist.TCPStore):
        return {"kind": "tcp", "address": store.host, "port": store.port}
    if isinstance(store, dist.FileStore):
        return {"kind": "file", "path": store.path}
    raise ValueError("Independent data processes require a TCPStore or FileStore rendezvous.")


def _child_environment(backends: tuple[str | None, ...]) -> dict[str, str]:
    """Build data-process environment overrides and validate its HCCL listener range."""
    env = {"OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1"}
    if "hccl" not in backends:
        return env
    selected = os.environ.get("HP_DATA_HCCL_SOCKET_PORT_RANGE", "50000-50031")
    match = re.fullmatch(r"(\d+)-(\d+)", selected)
    if match is None or not 1024 <= int(match[1]) <= int(match[2]) <= 65535:
        raise ValueError("HP_DATA_HCCL_SOCKET_PORT_RANGE must be an inclusive range within 1024-65535.")
    for start, end in re.findall(r"(\d+)-(\d+)", os.environ.get("HCCL_NPU_SOCKET_PORT_RANGE", "16666-16666")):
        if max(int(start), int(match[1])) <= min(int(end), int(match[2])):
            raise ValueError("HP_DATA_HCCL_SOCKET_PORT_RANGE overlaps the training HCCL listener range.")
    env["HCCL_NPU_SOCKET_PORT_RANGE"] = selected
    return env


def _child_transport(bootstrap: dict[str, Any]) -> DataPlaneTransport:
    """Rebuild collectives while retaining logical sample-owner rank identities."""
    device = bootstrap["device"]
    if device is not None and device.type != "cpu":
        getattr(torch, device.type).set_device(device)
    ranks = bootstrap["ranks"]
    control = payload = None
    if len(ranks) > 1:
        if bootstrap["kind"] == "tcp":
            store = dist.TCPStore(bootstrap["address"], bootstrap["port"], is_master=False,
                                  timeout=timedelta(seconds=_REPLY_TIMEOUT))
        else:
            store = dist.FileStore(bootstrap["path"])
        store = dist.PrefixStore(bootstrap["prefix"], store)
        dist.init_process_group(bootstrap["backend"], store=store, rank=bootstrap["rank"],
                                world_size=len(ranks), timeout=timedelta(seconds=_REPLY_TIMEOUT))
        control = dist.group.WORLD
        if bootstrap["payload_backend"] is not None:
            payload = control if bootstrap["payload_backend"] == bootstrap["backend"] else dist.new_group(
                backend=bootstrap["payload_backend"], timeout=timedelta(seconds=_REPLY_TIMEOUT),
            )
    groups = DataGroups(ranks, control, payload, None, bootstrap["planner_rank"], len(ranks) > 1)
    return DataPlaneTransport(groups, ranks[bootstrap["rank"]], device,
                              planner_process_rank=ranks.index(bootstrap["planner_rank"]))


def _worker_main(source_path: Path, bootstrap: dict[str, Any], connection: Connection) -> None:
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183


def _worker_main(source_path: Path, bootstrap: dict[str, Any], connection: Connection) -> None:
    """Initialize the spawned data rank and serve requests on its parent connection."""
    source = None
    try:
        os.setsid()
        os.environ.update(bootstrap["environment"])
        torch.set_num_threads(1)
        with source_path.open("rb") as handle:
            source, rng_state = _SOURCE_PICKLE.load(handle)
        balance_logger.setLevel(logging.INFO if bootstrap["balance_logging"] else logging.WARNING)
        random.setstate(rng_state[0])
        np.random.set_state(rng_state[1])
        torch.random.set_rng_state(rng_state[2])
        source.bind_transport(_child_transport(bootstrap))
        connection.send(("READY", os.getpid()))
        while True:
            command, value = connection.recv()
            if command == "CLOSE":
                connection.send(("CLOSED", None))
                break
            if command == "NEXT":
                try:
                    batch = next(source)
                except StopIteration:
                    connection.send(("EOF", None))
                else:
                    connection.send(("BATCH", batch))
            elif command == "EPOCH":
                source.set_epoch(value)
                connection.send(("EPOCH", None))
            elif command == "RESET":
                source.reset_iteration()
                connection.send(("RESET", None))
            else:
                raise ValueError(f"Unknown data process command: {command}.")
    except BaseException:
        try:
            connection.send(("ERROR", traceback.format_exc()))
        except (BrokenPipeError, EOFError, OSError):
            pass
        raise
    finally:
        try:
            if source is not None:
                source.close()
        finally:
            connection.close()
            if dist.is_initialized():
                dist.destroy_process_group()


def _reap_process(process: BaseProcess) -> None:
    """Stop the data process and any DataLoader workers still in its session."""
    if process.pid is None:
        return
    for sig, stop, timeout in ((signal.SIGTERM, process.terminate, 10), (signal.SIGKILL, process.kill, None)):
        try:
            os.killpg(process.pid, sig)
        except ProcessLookupError:
            # Spawn may fail or time out before the target creates its session.
            if not process.is_alive():
                return
            stop()
        process.join(timeout)


class ProcessDataWorker:
    """Keep one CPU result in flight on a private distributed producer."""
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    """Keep one CPU result in flight on a private distributed producer."""

    def __init__(self, source: Any, transport: DataPlaneTransport) -> None:
        """Serialize an unstarted source and capture its data-group rendezvous."""
        self._resources = ExitStack()
        # At interpreter shutdown multiprocessing joins non-daemonic children after running finalizers.
        self._finalize = Finalize(self, self._resources.close, exitpriority=10)
        directory = self._resources.enter_context(TemporaryDirectory(prefix="hp-data-process-"))
        self._process = None
        self._connection = None
        self._pending = False
        self._deadline = None
        self._closed = False
        self._failed = False
        self._source_path = Path(directory) / "source.pkl"
        try:
            bootstrap = {"ranks": transport.ranks, "planner_rank": transport.planner_rank,
                         "rank": transport.ranks.index(source.global_rank),
                         "backend": transport.communication_backend, "payload_backend": transport.payload_backend,
                         "device": transport.communication_device,
                         "balance_logging": balance_logger.isEnabledFor(logging.INFO)}
            rng = (random.getstate(), np.random.get_state(), torch.random.get_rng_state())
            error = None
            try:
                bootstrap["environment"] = _child_environment((bootstrap["backend"], bootstrap["payload_backend"]))
                # Keep large datasets out of spawn's synchronous startup pipe.
                self._source_path.write_bytes(_serialize_source((source, rng)))
            except Exception as exc:  # pylint: disable=broad-exception-caught
                # User-defined pickle hooks may raise any exception. All ranks must still enter the gather.
                error = f"{type(exc).__name__}: {exc}"
            statuses = transport.all_gather_object((uuid.uuid4().hex, error))
            errors = [message for _, message in statuses if message is not None]
            if errors:
                raise ValueError("Data processes require a valid environment and serializable, unstarted CPU sources "
                                 "and callbacks: "
                                 + "; ".join(errors))
            if len(transport.ranks) > 1:
                bootstrap.update(_store_descriptor(), prefix="hp-data-process-" + statuses[0][0])
            self._bootstrap = bootstrap
        except BaseException:
            self.close()
            raise

    def _start(self) -> None:
        """Spawn the producer once and wait until it has bound its data transport."""
        if self._closed or self._failed:
            raise RuntimeError("Data process is closed or failed.")
        if self._process is not None:
            return
        context = torch.multiprocessing.get_context("spawn")
        parent, child = context.Pipe()
        self._connection = self._resources.enter_context(parent)
        try:
            with child:
                self._process = context.Process(
                    target=_worker_main, args=(self._source_path, self._bootstrap, child), daemon=False,
                )
                self._resources.callback(self._process.close)
                self._resources.callback(_reap_process, self._process)
                self._process.start()
            status, _ = self._receive()
            if status != "READY":
                raise RuntimeError(f"Expected a ready data process, received {status}.")
        except BaseException:
            self._failed = True
            self.close()
            raise

    def _receive(self) -> tuple[str, Any]:
        """Wait for one reply and propagate a timeout, child exit or remote traceback."""
        deadline = time.monotonic() + _REPLY_TIMEOUT
        try:
            while not self._connection.poll(0.1):
                if self._process.exitcode is not None:
                    raise RuntimeError(f"Data process exited with status {self._process.exitcode}.")
                if time.monotonic() >= deadline:
                    raise TimeoutError("Data process did not reply within the data timeout.")
            status, value = self._connection.recv()
            if status == "ERROR":
                raise RuntimeError(f"Data process failed:\n{value}")
            return status, value
        except EOFError as exc:
            self._failed = True
            raise RuntimeError("Data process closed its connection before replying.") from exc
        except BaseException:
            self._failed = True
            raise

    def prefetch(self) -> None:
        """Start one CPU result without waiting for preparation or communication."""
        self._start()
        if not self._pending:
            self._send("NEXT")
            self._pending = True
            self._deadline = time.monotonic() + _REPLY_TIMEOUT

    def is_ready(self, timeout: float = 0.0) -> bool:
        """Poll delivery so staging can continue while another CPU window is prepared.
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324

        Args:
            timeout: Maximum seconds to wait for a ready result.
        """
        if self._connection.poll(timeout):
            return True
        if self._process.exitcode is not None:
            self._failed = True
            raise RuntimeError(f"Data process exited with status {self._process.exitcode}.")
        if time.monotonic() >= self._deadline:
            self._failed = True
            raise TimeoutError("Data process did not reply within the data timeout.")
        return False

    def __next__(self) -> Any:
        """Receive one result through PyTorch's CPU shared-storage reducers."""
        self.prefetch()
        status, result = self._receive()
        self._pending = False
        if status == "EOF":
            raise StopIteration
        if status != "BATCH":
            raise RuntimeError(f"Expected a CPU batch, received {status}.")
        return result

    def _send(self, command: str, value: Any = None) -> None:
        try:
            self._connection.send((command, value))
        except BaseException:
            self._failed = True
            raise

    def _command(self, command: str, value: Any = None) -> None:
        self._start()
        if self._pending:
            self._receive()
            self._pending = False
        self._send(command, value)
        status, _ = self._receive()
        if status != command:
            raise RuntimeError(f"Expected {command}, received {status}.")

    def set_epoch(self, epoch: int) -> None:
        """Reset the source after all prefetched results have been drained.
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355

        Args:
            epoch: Non-negative epoch to select before the next source read.
        """
        self._command("EPOCH", epoch)

    def reset_iteration(self) -> None:
        """Re-enter the external source without replacing its process-owned state."""
        self._command("RESET")

    def close(self) -> None:
        """Drain a published CPU result and terminate only the owned process session."""
        if self._closed:
            return
        self._closed = True
        try:
            if self._process is not None and not self._failed and self._process.is_alive():
                if self._pending:
                    self._receive()
                self._connection.send(("CLOSE", None))
                self._receive()
                self._process.join(timeout=30)
                if self._process.is_alive():
                    raise TimeoutError("Data process did not exit after acknowledging CLOSE.")
        finally:
            self._finalize()
            self._process = None


class DataRequest:
    """One child reply, received on demand and retained across explicit drains."""
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
    """One child reply, received on demand and retained across explicit drains."""

    def __init__(self, worker: Any) -> None:
        """Start one request on the persistent data worker."""
        self._worker = worker
        self._reply = Future()
        try:
            worker.prefetch()
        except BaseException as error:  # pylint: disable=broad-exception-caught
            # A successor's startup failure belongs to that request, after any batch already prepared.
            self._reply.set_exception(error)

    def is_ready(self) -> bool:
        """Poll without consuming the reply or waiting for the child."""
        return self._reply.done() or self._worker.is_ready()

    def result(self) -> Any:
        """Receive once, including EOF or a producer error."""
        if not self._reply.done():
            try:
                self._reply.set_result(next(self._worker))
            except BaseException as error:  # pylint: disable=broad-exception-caught
                # Cache the original failure so drains and delivery observe the same outcome.
                self._reply.set_exception(error)
        return self._reply.result()


def create_data_worker(source: Any, transport: DataPlaneTransport) -> Any:
    """Spawn data-plane members; model-only peers retain their empty local cursor.
385
386
387
388
389
390
391
392
    Args:
        source: Serializable, unstarted CPU source with native or external preparation.
        transport: Data-plane collectives owned by this source process.
    """
    if transport.is_member:
        return ProcessDataWorker(source, transport)
    source.bind_transport(transport)
    return source
hyper_parallel/distributed_data/transport.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
        Args:
            ranks: Global ranks in collective order.
            backend: Backend for the new subgroup.
        """
        group = dist.new_group(ranks=list(ranks), backend=backend)
        if group != dist.GroupMember.NON_GROUP_MEMBER:
            self._owned.append(group)
        return group

    @contextmanager
    def close_on_error(self) -> Iterator[None]:
        """Release acquired groups if construction fails before ownership transfers to the loader."""
        try:
            yield
        except BaseException:
            self.close()
            raise

    def close(self) -> None:
        """Destroy owned handles in creation order and drop all their transport aliases."""
        while self._owned:
            group = self._owned[0]
            if dist.is_initialized():
                dist.destroy_process_group(group)
            self._owned.pop(0)
            for name in ("control_group", "payload_group", "model_parallel_group", "model_parallel_tensor_group"):
                if getattr(self, name) is group:
                    setattr(self, name, None)


@dataclass(frozen=True)
class PreparedPayloadExchange:
102
103
104
105
106
107
108
109
110
        """Wait for gathered bytes and decode them with the launch device and stream bound."""
        if self.completed_values is None:
            if self.data_work is not None:
                self.data_work.wait()
            rows = self.gathered.cpu().view(len(self.sizes), -1).numpy()
            self.completed_values = tuple(pickle.loads(row[:size].tobytes())
                                          for row, size in zip(rows, self.sizes))
        return self.completed_values

165
166
167
168
169
170
171
172
173

def _encode_control(value: Any, device: Any) -> tuple[torch.Tensor, int]:
    encoded = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)
    resolved = torch.device(device)
    payload = torch.frombuffer(bytearray(encoded), dtype=torch.uint8).to(resolved)
    return payload, len(encoded)


def _decode_control(payload: torch.Tensor, size: int) -> Any:
211
212
213
214
215
216
217
218
219
220
221
        return ControlGatherWork(completed_values=tuple(gathered))
    resolved = _require_control_device(device, effective_backend)
    encoded, encoded_size = _encode_control(value, resolved)
    local_size = torch.tensor([encoded_size], dtype=torch.int64, device=resolved)
    sizes = torch.empty(dist.get_world_size(group), dtype=torch.int64, device=resolved)
    dist.all_gather_into_tensor(sizes, local_size, group=group)
    host_sizes = tuple(sizes.cpu().tolist())
    max_size = max(host_sizes)
    if encoded.numel() < max_size:
        padded = torch.zeros((max_size,), dtype=torch.uint8, device=resolved)
        padded[:encoded.numel()] = encoded
219
220
221
222
223
224
225
226
227
228
229
    if encoded.numel() < max_size:
        padded = torch.zeros((max_size,), dtype=torch.uint8, device=resolved)
        padded[:encoded.numel()] = encoded
        encoded = padded
    gathered = torch.empty(len(host_sizes) * max_size, dtype=torch.uint8, device=resolved)
    work = dist.all_gather_into_tensor(gathered, encoded, group=group, async_op=True)
    return ControlGatherWork(encoded=encoded, sizes=host_sizes, gathered=gathered, data_work=work)


def broadcast_control_object(
        value: Any,
304
305
306
307
308
309
310
311
312
313
314
        payload_backend=payload_backend,
        communication_device=communication_device,
        enable_payload_exchange=enable_payload_exchange,
    )
    groups = DataGroups(data_plane_ranks, None, None, None, planner_rank, True)
    with groups.close_on_error():
        groups.control_group, groups.payload_group = _create_data_plane_process_groups(
            groups=groups,
            topology=topology,
            data_plane_ranks=data_plane_ranks,
            cpu_backend=cpu_backend,
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
            payload_backend=effective_payload_backend,
            reuse_control_group=reuse_control_group,
            enable_payload_exchange=enable_payload_exchange,
        )
        tensor_backend = _resolve_model_tensor_backend(communication_device, payload_backend)
        model_device = torch.device(model_device) if model_device is not None else None
        if model_device is not None and model_device.type in ("cuda", "npu"):
            tensor_backend = "nccl" if model_device.type == "cuda" else "hccl"
        groups.model_parallel_group, groups.model_parallel_tensor_group = _create_model_parallel_process_groups(
            groups, topology, cpu_backend, tensor_backend,
        )
    return groups


def _single_rank_data_groups(
        topology: DataTopology,
424
425
426
427
428
429
430
431
432
) -> tuple[Any, Any]:
    """Create control and payload groups in common rank order, returning owned handles."""
    if len(data_plane_ranks) == 1:
        return None, None
    created_control_group = groups.new_group(data_plane_ranks, cpu_backend)
    is_member = topology.global_rank in data_plane_ranks
    control_group = created_control_group if is_member else None
    if not enable_payload_exchange:
        return control_group, None
431
432
433
434
435
436
437
438
439
    if not enable_payload_exchange:
        return control_group, None
    if reuse_control_group:
        return control_group, control_group
    created_payload_group = groups.new_group(data_plane_ranks, payload_backend)
    return control_group, created_payload_group if is_member else None


def _resolve_model_tensor_backend(communication_device: Any, payload_backend: str | None) -> str | None:
462
463
464
465
466
467
468
469
470
471
472
473
    for rank_group in topology.model_parallel_rank_groups:
        if len(rank_group) == 1:
            continue
        is_member = topology.global_rank in rank_group
        created_group = groups.new_group(rank_group, cpu_backend)
        if is_member:
            model_parallel_group = created_group
        if tensor_backend is not None:
            created_tensor_group = groups.new_group(rank_group, tensor_backend)
            if is_member:
                model_parallel_tensor_group = created_tensor_group
    return model_parallel_group, model_parallel_tensor_group
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
    def __init__(self, groups: DataGroups, global_rank: int, communication_device: Any = None,
                 *, planner_process_rank: int | None = None) -> None:
        """Store service-group membership."""
        self._ranks = groups.data_plane_ranks
        self._groups = groups
        self._planner_rank = groups.planner_rank
        self._planner_process_rank = groups.planner_rank if planner_process_rank is None else planner_process_rank
        self._global_rank = global_rank
        self._is_member = global_rank in self._ranks
        self._local_index = self._ranks.index(global_rank) if self._is_member else None
        if self._is_member and len(self._ranks) > 1 and (not groups.distributed or self._groups.control_group is None):
            raise ValueError("Multi-rank data-plane communication requires an initialized process group.")
        self._communication_device = (
            torch.device(communication_device) if communication_device is not None else None
        )
744
745
746
747
748
749
750
751
752
753
754
755
756

    @property
    def communication_backend(self) -> str:
        """Return the backend used by this data-plane control group."""
        return _control_backend(self._groups.control_group)

    @property
    def payload_backend(self) -> str | None:
        """Return the payload backend for rebuilding an independent data group."""
        return _control_backend(self._groups.payload_group) if self._groups.payload_group is not None else None

    def all_gather_object(self, value: Any) -> tuple[Any, ...]:
        """Gather small control objects on every data-plane rank.
792
793
794
795
796
797
798
799
800
            Whether every participating rank supplied ``True``.
        """
        if len(self._ranks) == 1:
            return value
        backend = _control_backend(self._groups.control_group)
        flag_device = (
            _require_control_device(self._communication_device, backend)
            if _is_accelerator_backend(backend)
            else torch.device("cpu")
799
800
801
802
803
804
805
806
807
            if _is_accelerator_backend(backend)
            else torch.device("cpu")
        )
        flag = torch.tensor([int(value)], dtype=torch.int32, device=flag_device)
        dist.all_reduce(flag, op=dist.ReduceOp.MIN, group=self._groups.control_group)
        return bool(flag.item())

    def gather_object_to_planner(self, value: Any) -> tuple[Any, ...] | None:
        """Gather Dataset Reader metadata only on the Planner rank.
910
911
912
913
914
915
916
917
918
                    prepared.local_segment,
                    prepared.input_splits,
                ),
            )
        if self._groups.payload_group is None:
            raise ValueError("Sample payload exchange requires a payload process group.")

        input_splits = list(prepared.input_splits)
        output_splits = _exchange_payload_sizes(
949
950
951
952
953
954
955
956
957
            *, model_batch_spec: Any = None, device: Any = None,
    ) -> None:
        """Bind model peers, communication devices and the local batch declaration."""
        self._ranks = topology.model_parallel_ranks
        self._groups = groups
        self._constructor_rank = topology.constructor_rank
        self._global_rank = topology.global_rank
        self._communication_device = torch.device(communication_device) if communication_device is not None else None
        self._device = torch.device(device or communication_device or "cpu")
956
957
958
959
960
961
962
963
        self._communication_device = torch.device(communication_device) if communication_device is not None else None
        self._device = torch.device(device or communication_device or "cpu")
        self._layout = None if model_batch_spec is None else ModelBatchLayout(model_batch_spec)
        if len(self._ranks) > 1:
            if not groups.distributed or self._groups.model_parallel_group is None:
                raise ValueError("Multi-rank model broadcast requires an initialized process group.")
            if self._layout is None:
                raise ValueError("Model-parallel loading requires the same model_batch_spec on every rank.")
962
963
964
965
966
967
968
969
970
            if self._layout is None:
                raise ValueError("Model-parallel loading requires the same model_batch_spec on every rank.")

    def _control_tensor(self, values: list[int]) -> torch.Tensor:
        backend = _control_backend(self._groups.model_parallel_group)
        device = (
            _require_control_device(self._communication_device, backend) if _is_accelerator_backend(backend) else "cpu"
        )
        return torch.tensor(values, dtype=torch.int64, device=device)
1001
1002
1003
1004
1005
1006
1007
1008
1009
                # Notify peers even on interrupts before re-raising the original failure.
                error = exc
                values[0] = -1
        header = self._control_tensor(values)
        dist.broadcast(header, src=self._constructor_rank, group=self._groups.model_parallel_group)
        if not is_constructor:
            values = header.cpu().tolist()
        if values[0] == -1:
            if error is not None:
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
            return None
        if values[0] != 1:
            raise ValueError("Invalid model batch status header.")
        shapes = self._layout.shapes(values[1:])
        received = self._broadcast_tensors(shapes, tensors)
        return self._layout.rebuild(received)

    def _broadcast_tensors(self, shapes: list[tuple[int, ...]], sources: list[torch.Tensor]) -> list[torch.Tensor]:
        """Coalesce fields with the same dtype and destination placement."""
        buckets = {}
        for index, field in enumerate(self._layout.fields):
            buckets.setdefault((field.dtype, field.device), []).append(index)
        received = [None] * len(shapes)
        for indices in buckets.values():
            field = self._layout.fields[indices[0]]
            bucket_shapes = [shapes[index] for index in indices]
            local = [sources[index] for index in indices] if sources else []
            for index, tensor in zip(indices, self._broadcast_bucket(field, bucket_shapes, local)):
                received[index] = tensor
        return received

    def _broadcast_bucket(self, field: Any, shapes: list[tuple[int, ...]],
                          sources: list[torch.Tensor]) -> list[torch.Tensor]:
        """Broadcast one packed payload while retaining independent leaf storage."""
        if len(shapes) == 1:
            return [self._broadcast_tensor(field, shapes[0], sources[0] if sources else None)]
        target = torch.device("cpu") if field.device == "cpu" else self._device
        local = [tensor.to(target).contiguous() for tensor in sources]
        sizes = [math.prod(shape) for shape in shapes]
        packed = torch.cat([tensor.reshape(-1) for tensor in local]) if local else None
        packed = self._broadcast_tensor(field, (sum(sizes),), packed)
        if local:
            return local
        return [part.reshape(shape).clone() for part, shape in zip(packed.split(sizes), shapes)]

    def _broadcast_tensor(self, field: Any, shape: tuple[int, ...], source: Any) -> torch.Tensor:
        """Broadcast one declared tensor using a backend-compatible transfer device."""
        target = torch.device("cpu") if field.device == "cpu" else self._device
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
            dist.broadcast(tensor, src=self._constructor_rank, group=group)
        return tensor.to(target)

    def _group_for_tensor(self, device_type: str) -> Any:
        if device_type == "cpu" or self._groups.model_parallel_tensor_group is None:
            return self._groups.model_parallel_group
        return self._groups.model_parallel_tensor_group


__all__ = [
    "DataGroups",