Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/distributed_data/api.py 83.3% 807
hyper_parallel/distributed_data/balance_logging.py 50.0% 80
hyper_parallel/distributed_data/batch_sampler.py 100%  
hyper_parallel/distributed_data/device_prefetch.py 100%  
hyper_parallel/distributed_data/distributed_dataloader.py 97.8% 151,202
hyper_parallel/distributed_data/external_source.py 89.6% 123-127,133-134,136-138,149,160,169,184,269-271
hyper_parallel/distributed_data/locality.py 100%  
hyper_parallel/distributed_data/metadata.py 100%  
hyper_parallel/distributed_data/native_source.py 95.0% 101-102,136,145,211,214-215,226-227,274,292,294,296,338,402
hyper_parallel/distributed_data/packed_balancing.py 90.5% 108,126,145-149,157,173,178,205
hyper_parallel/distributed_data/process_data.py 77.1% 64-71,79-87,94,98-99,102-104,106-108,146-148,150-156,164,170,178,220,229,245,257,259,287-293,303,309-311,316-317,321,333,348,363,365,391-392
hyper_parallel/distributed_data/transport.py 92.4% 78,322,466,470,796,803,1066
hyper_parallel/distributed_data/api.py
803
804
805
806
807
808
809
810
811
            "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,
hyper_parallel/distributed_data/balance_logging.py
76
77
78
79
80
81
82
83
84
        )
        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/distributed_dataloader.py
147
148
149
150
151
152
153
154
155
        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,
198
199
200
201
202
203
204
205
206
            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
hyper_parallel/distributed_data/external_source.py
119
120
121
122
123
124
125
126
127
128
129
130
131
            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
                    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
145
146
147
148
149
150
151
152
153
    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
156
157
158
159
160
161
162
163
164

    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:
165
166
167
168
169
170
171
172
173
            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)
180
181
182
183
184
185
186
187
188

    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(
265
266
267
268
269
270
271
272
273
274
275
            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 {
hyper_parallel/distributed_data/native_source.py
 97
 98
 99
100
101
102
103
104
105
106

        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()
132
133
134
135
136
137
138
139
140

    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)
141
142
143
144
145
146
147
148
149

    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(
207
208
209
210
211
212
213
214
215
216
217
218
219
            }
            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.
222
223
224
225
226
227
228
229
230
231
            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}."
270
271
272
273
274
275
276
277
278
        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
288
289
290
291
292
293
294
295
296
297
298
299
300
        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,
334
335
336
337
338
339
340
341
            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.")
398
399
400
401
402
403
404
405
406

    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(
hyper_parallel/distributed_data/packed_balancing.py
104
105
106
107
108
109
110
111
112
        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()
122
123
124
125
126
127
128
129
130

    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
141
142
143
144
145
146
147
148
149
150
151
152
153

    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."""
153
154
155
156
157
158
159
160
161
        """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:
169
170
171
172
173
174
175
176
177
178
179
180
181
182
        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
201
202
203
204
205
206
207
208
209
        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:
hyper_parallel/distributed_data/process_data.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

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."""
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
    """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."""
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
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,
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
                    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()
160
161
162
163
164
165
166
167
168
                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."""
166
167
168
169
170
171
172
173
174

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:
174
175
176
177
178
179
180
181
182
        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:
216
217
218
219
220
221
222
223
224
                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
225
226
227
228
229
230
231
232
233

    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()
241
242
243
244
245
246
247
248
249
                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
253
254
255
256
257
258
259
260
261
262
263
        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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
            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()
299
300
301
302
303
304
305
306
307
        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:
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324

    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.
329
330
331
332
333
334
335
336
337
        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:
344
345
346
347
348
349
350
351
                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
359
360
361
362
363
364
365
366
367
368
369
        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()
387
388
389
390
391
392
        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
74
75
76
77
78
79
80
81
82
                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:
318
319
320
321
322
323
324
325
326
        )
        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
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
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.
1062
1063
1064
1065
1066
1067
1068
1069
1070

    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",