Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/checkpoint/dcp_checkpointer.py 20.0% 542-545
hyper_parallel/core/activation_memory/pinned_memory_pool.py 12.5% 254-260
hyper_parallel/core/activation_memory/swap.py 2.9% 976-1008
hyper_parallel/core/context_parallel/async_context_parallel.py 33.3% 53-54,65-68,339,379
hyper_parallel/core/context_parallel/async_dsa_context_parallel.py 12.5% 61-64,180,204,226
hyper_parallel/core/distributed_checkpoint/api.py 6.2% 274,323-331,334,413,419,422-423
hyper_parallel/core/distributed_checkpoint/async_persist.py 15.5% 260-262,264-265,270,272-274,277-280,282-283,286,288,303-306,308-323,356-358,360-361,364,366,481,534,597,755-756
hyper_parallel/core/distributed_checkpoint/broadcast.py 16.7% 181-183,186,189
hyper_parallel/core/dtensor/dtensor.py 12.5% 382-383,385,1093,1096-1097,1099
hyper_parallel/core/fully_shard/hsdp_scheduler.py 8.3% 245-251,254-257
hyper_parallel/core/optimizer/muon.py 25.0% 308,311,313-315,323
hyper_parallel/core/optimizer/muon_shard.py 0.0% 198
hyper_parallel/core/optimizer/optimizer.py 16.7% 485-489
hyper_parallel/core/optimizer/sharding_category.py 100%  
hyper_parallel/core/optimizer/swap_adam.py 20.0% 297-299,305
hyper_parallel/core/optimizer/swap_optimizer_base.py 14.3% 1425-1433,1437-1439,1443-1444,1448-1461,1660,1700
hyper_parallel/data/batching/build_dataloader.py 0.0% 483-484,486
hyper_parallel/data/indexed/indexed_data_config.py 28.6% 189,329-332
hyper_parallel/data/parallel/dataloader_parallel.py 25.0% 208,210-211
hyper_parallel/data/tools/io.py 13.0% 177-187,189,198-203,205,207
hyper_parallel/high_availability/__init__.py 50.0% 31-35
hyper_parallel/high_availability/config.py 57.1% 37-42
hyper_parallel/high_availability/group_registry.py 23.6% 31,36-37,42-43,69-73,75-87,92-96,109-115,119,121-127,131-135,147-162,174-175,179-186,190-199
hyper_parallel/high_availability/model_recovery.py 26.1% 39-41,44-64,68-69,81-88
hyper_parallel/high_availability/recovery_session.py 14.8% 57-61,63-90,98,102-106,109-114,116-117,119-120,122-128,132-135,137-139,141-147,162-178,188-191,197,201-202,210-217,235-236,239-252,254,258-260,263,273-275,294-295,299-304,306-312,314-316,320-327,330-331,334-339,343-354,357-361,365-377,379-382,384,389-392,394-396,398-399,403-405,408-413,416-419,425-426
hyper_parallel/high_availability/recovery_state.py 16.5% 33,38-48,62-65,67-72,74-84,88-98,102-105,107-108,110,115-126,128,130,141,145,147,149,151,155,157-158,161-164,168-178,181-184,186-187,191-193,197,199-200,204-215,223-242,254-265,269-270,276-290,294-298,320-325,329-331,338,355-364,372-374,378-385
hyper_parallel/high_availability/replica_topology.py 20.0% 29-38,40-41,46-50,62-66,68-74,76-77,80-83,98-106,108-109,111-115,119-122,134-135,137-139,141-144,147,153-155
hyper_parallel/high_availability/replica_transport.py 22.1% 35-37,42,47,55-58,68-78,82-87,91-94,98-99,112-118,126-130,134-137,145-167,170-173,177-181,191-194,196-197,199-203,213-230
hyper_parallel/high_availability/validation.py 30.2% 58-69,78-97,111-135,145-146,148
hyper_parallel/trainer/base.py 50.0% 684-685,1209-1211,1215-1216,1236
hyper_parallel/trainer/callbacks/checkpoint_callback.py 20.0% 175,214-218,283-284
hyper_parallel/trainer/callbacks/profiler_callback.py 14.3% 63,74-75,106,110,119-128,144-146,152,256,308,332,335,337
hyper_parallel/trainer/callbacks/tqdm_callback.py 0.0% 211-212
hyper_parallel/trainer/config/trainer.py 100%  
hyper_parallel/trainer/runtime/memory_profiler.py 13.3% 77-78,103,114-116,125,130-131,134,154,161,242
hyper_parallel/trainer/runtime/process_recovery.py 32.2% 39-54,69-74,76,91-95,110-115,130-135,150-154,156-159,161-162,171,175-179,183-184,189-191,193-202,207-211,213-214,216
hyper_parallel/trainer/text_trainer.py 70.0% 328-329,333
hyper_parallel/trainer/vlm_trainer.py 70.0% 335-336,340
hyper_parallel/components/checkpoint/dcp_checkpointer.py
538
539
540
541
542
543
544
545
546
547
548

        Completed checkpoints remain published. The attempted save-step marker
        belongs to the callback and is retained even when persistence is dropped.
        """
        if self._async_save_response is None:
            return
        self._async_save_response.abort()
        self._async_save_response = None

    def raise_for_failed_async_save(self) -> None:
        """Re-raise an in-flight async save's failure as soon as it is known.
hyper_parallel/core/activation_memory/pinned_memory_pool.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264

        Old device events must not be queried after recovery. Checked-out buffers
        remain owned by their callers; only already-released blocks are recycled.
        """
        with self._lock:
            for blocks in self._pending.values():
                for block in blocks:
                    block.event = None
                    block.state = _AVAILABLE
                    self._available[block.capacity].append(block)
            self._pending.clear()

    def release(self, tensor: Any, event: Optional[Any] = None) -> None:
        """Return an acquired view to the pool, optionally after an async event."""
        key = _storage_key(tensor)
hyper_parallel/core/activation_memory/swap.py
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012

        Args:
            modules: This model's modules carrying registered swap-group names.
        """
        modules = tuple(modules)
        names = {vars(module)["_swap_group_name"] for module in modules}
        if not names:
            return
        _backend.get_device_handle().synchronize()
        pools = {}
        for module in modules:
            pool = vars(module).get("cpu_pool")
            if pool is not None:
                pools[id(pool)] = pool
        for name in names:
            group = self._groups.get(name)
            if group is None:
                continue
            for storage in group._storages:
                for tensor in storage.iter_swap_tensors():
                    if tensor.cpu_pool is not None:
                        pools[id(tensor.cpu_pool)] = tensor.cpu_pool
                storage.release_cpu_buffers()
                storage.clear()
            for bucket in group._packed_buckets.values():
                pool = bucket["cpu_pool"]
                if pool is not None:
                    pools[id(pool)] = pool
            group.release_cpu_buffers()
            replacement = SwapGroup(name)
            replacement.is_last_group = group.is_last_group
            self._groups[name] = replacement
        for pool in pools.values():
            pool.reset_after_device_restart()
        for module in modules:
            vars(module).pop("_swap_state", None)
        self._copy_stream = None

    def get_current_group_name(self) -> str:
        """Return the name of the currently active swap group."""
        return self._current_group_name.get()
hyper_parallel/core/context_parallel/async_context_parallel.py
49
50
51
52
53
54
55
56
57
    """Own the slot containers shared by projection and attention hooks."""

    def __init__(self, forward_slots: dict[str, Any], backward_slots: dict[str, list]) -> None:
        """Bind existing containers without changing the hook-owned identities."""
        self.forward_slots = forward_slots
        self.backward_slots = backward_slots

    def reset_after_device_restart(self) -> None:
        """Discard failed work after the caller has quiesced device communication.
61
62
63
64
65
66
67
68
69
70
71
72
        hold task lists captured by hook closures; clear each list in place
        because replacing it would leave the hook referencing the old tasks.
        Neither cleanup path waits on obsolete Work objects.
        """
        for key in self.forward_slots:
            self.forward_slots[key] = None
        for slots in self.backward_slots.values():
            slots.clear()


# ---------------------------------------------------------------------------
# All-to-all helpers
335
336
337
338
339
340
341
342
343
        co_submesh = _ensure_1d(device_mesh)
        group = co_submesh.get_group()
        fwd_ag_slots = {"k": None, "v": None}
        bwd_ag_slots = {"k": [], "v": []}
        setattr(module, "_context_parallel_async_state", _AsyncCPState(fwd_ag_slots, bwd_ag_slots))
        self._register_ag_proj_hooks(
            k_proj,
            v_proj,
            submesh=co_submesh,
375
376
377
378
379
380
381
382
383
    ) -> Module:
        """Register Pure Ulysses or Hybrid async A2A hooks."""
        fwd_slots = {"q": None, "k": None, "v": None}
        bwd_slots = {"q": [], "k": [], "v": []}
        setattr(module, "_context_parallel_async_state", _AsyncCPState(fwd_slots, bwd_slots))

        if co == 1:
            ds_submesh = _ensure_1d(device_mesh)
            group = ds_submesh.get_group()
hyper_parallel/core/context_parallel/async_dsa_context_parallel.py
57
58
59
60
61
62
63
64
65
66
67
68
        self._bwd_slots = {}

    def reset_after_device_restart(self) -> None:
        """Drop failed queues after communication has quiesced, preserving hook references."""
        for slots in self._slots.values():
            slots.clear()
        for slots in self._bwd_slots.values():
            slots.clear()

    @staticmethod
    def _extract_tensor_output(output: Any) -> Any:
        if _is_tensor_or_dtensor(output):
176
177
178
179
180
181
182
183
184
    def apply(self, module: Module, device_mesh: DeviceMesh, *, key_handoff: Optional[Module] = None) -> Module:
        """Register async DSA indexer CP hooks on ``module`` and optional producer."""
        cp_mesh = _ensure_1d(device_mesh)
        async_state = _AsyncSequenceReplicateSlot(cp_mesh, self.seq_dim)
        setattr(module, "_context_parallel_async_state", async_state)
        async_state.register_launch_hook(key_handoff, "key")
        specs = self._build_specs(
            cp_mesh,
            key_fn=lambda value: async_state.wait("key", value),
200
201
202
203
204
205
206
207
208
    ) -> Module:
        """Register async DSA sparse-attention CP hooks on ``module`` and producers."""
        cp_mesh = _ensure_1d(device_mesh)
        async_state = _AsyncSequenceReplicateSlot(cp_mesh, self.seq_dim)
        setattr(module, "_context_parallel_async_state", async_state)
        async_state.register_launch_hook(key_handoff, "key")
        async_state.register_launch_hook(value_handoff, "value")
        async_state.register_launch_hook(key_rope_handoff, "key_rope")
        return _apply_sparse_attention_boundary(self, module, device_mesh, async_state=async_state)
222
223
224
225
226
227
228
229
230
    ) -> Module:
        """Register async DSA indexer-loss CP hooks on ``module`` and producers."""
        cp_mesh = _ensure_1d(device_mesh)
        async_state = _AsyncSequenceReplicateSlot(cp_mesh, self.seq_dim)
        setattr(module, "_context_parallel_async_state", async_state)
        async_state.register_launch_hook(key_handoff, "key")
        async_state.register_launch_hook(key_indexer_handoff, "key_indexer")
        async_state.register_launch_hook(key_rope_handoff, "key_rope")
        specs = self._build_loss_specs(
hyper_parallel/core/distributed_checkpoint/api.py
270
271
272
273
274
275
276
277
278
    if not need_comm or not use_gloo:
        use_storage_comm = need_comm and not use_gloo
        if use_storage_comm:
            logger.info("use storage communication for dcp async save.")
            _cleanup_stale_communication_files(checkpoint_id, storage_writer)
        return mp.Process(
            target=execute_async_persist,
            args=(
                result_queue,
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    checkpoint_id: Optional[Union[Path, str]],
    storage_writer: Optional[StorageWriter],
) -> None:
    """Remove possible stale communication files before any new persist child starts."""
    directory = checkpoint_id if checkpoint_id is not None else getattr(storage_writer, "checkpoint_dir", None)
    if directory is None:
        raise ValueError("Storage-coordinated async save requires checkpoint_id or storage_writer.checkpoint_dir")
    rank = dist.get_rank()
    for file_type in FileType:
        try:
            os.remove(assemble_file_path(directory, file_type, rank))
        except FileNotFoundError:
            pass
    # Complete files from a previous attempt are indistinguishable from new
    # results until every rank has removed its own files. Admit writers together.
    dist.barrier()


@dcp_timer_decorator
def async_save(
409
410
411
412
413
414
415
416
417

    # Deliberately not a daemon: it has to outlive the training loop long enough to resolve
    # persist_completion and run callback, and killing it early would not let the process exit
    # any sooner because the persist child is joined at interpreter exit regardless.
    response = AsyncSaveResponse(persist_completion, process=proc, result_queue=result_queue)
    join_thread = threading.Thread(
        target=resolve_async_persist_result,
        args=(proc, result_queue, response, async_callback),
        name="AsyncCheckpointPersistJoin",
415
416
417
418
419
420
421
422
423
424
425
426
427
        target=resolve_async_persist_result,
        args=(proc, result_queue, response, async_callback),
        name="AsyncCheckpointPersistJoin",
    )
    response.join_thread = join_thread
    proc.start()
    join_thread.start()
    dist.barrier()
    return response


def _open_checkpoint(
    checkpoint_id: Optional[Path],
hyper_parallel/core/distributed_checkpoint/async_persist.py
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
281
282
283
284
285
286
287
288
289
290
291
292
    _finalize_lock: Any = dataclasses.field(default_factory=threading.Lock, repr=False)

    def finalize(self, result: Any, async_callback: Callable, exitcode: int) -> None:
        """Publish one persistence result under the same lock used by abort."""
        with self._finalize_lock:
            if self.persist_completion.done():
                return

            if result is None:
                self.persist_completion.set_exception(
                    RuntimeError(
                        f"async_persist process exited with code {exitcode} and no result on queue"
                    )
                )
                return

            status, payload = result
            if status == AsyncPersistStatus.SUCCESS:
                try:
                    # Future waiters can immediately start the next save, so publish
                    # and restore its reusable plans before signalling completion.
                    async_callback()
                    StandardSavePlanner.cached_save_result.update(payload[1])
                except Exception as exc:  # pylint: disable=broad-except
                    self.persist_completion.set_exception(exc)
                else:
                    self.persist_completion.set_result(payload[0])
            elif status == AsyncPersistStatus.FAILURE:
                # The child sends a formatted traceback rather than an exception
                # object; preserve that text in the error observed by Future waiters.
                self.persist_completion.set_exception(RuntimeError(payload))
            else:
                self.persist_completion.set_exception(
                    RuntimeError(f"async_persist queue returned unexpected status: {status!r}")
                )

    def abort(self, timeout: float = 5.0) -> None:
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
325
326
            RuntimeError: A process or result thread could not be stopped.
        """
        # Cancellation and publication share a lock: after this returns, no late
        # callback can publish latest or repopulate the plan cache during rollback.
        if not self._finalize_lock.acquire(timeout=timeout):
            raise RuntimeError("async checkpoint publication did not finish before recovery")
        try:
            self.persist_completion.cancel()
        finally:
            self._finalize_lock.release()
        if self.process is not None:
            if self.process.is_alive():
                self.process.terminate()
                self.process.join(timeout)
            if self.process.is_alive():
                self.process.kill()
                self.process.join(timeout)
            if self.process.is_alive():
                raise RuntimeError("async checkpoint process did not stop")
        if self.join_thread is not None:
            self.join_thread.join(timeout)
            if self.join_thread.is_alive():
                raise RuntimeError("async checkpoint result thread did not stop")
        if self.result_queue is not None:
            self.result_queue.close()

    def get_result(self, timeout: int = None) -> Optional[Metadata]:
        """Wait for the save to be persisted and return its metadata.
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370


def _start_parent_monitor() -> None:
    """Exit an orphaned persist child when its training worker dies."""
    parent = mp.parent_process()
    if parent is None:
        return

    def _watch() -> None:
        wait([parent.sentinel])
        # The worker may have been SIGKILLed, so Python finalizers cannot be
        # relied on to stop a child blocked on another rank's checkpoint files.
        os._exit(1)

    threading.Thread(target=_watch, name="AsyncCheckpointParentMonitor", daemon=True).start()


def cleanup_and_reinit_process_group(
    master_addr: str,
477
478
479
480
481
482
483
484
485
    """
    # ``api`` imports this module at load time, so this import stays function local: that is
    # what keeps the two from importing each other at load time.
    from hyper_parallel.core.distributed_checkpoint.api import _save_impl  # pylint: disable=import-outside-toplevel
    _start_parent_monitor()
    try:
        # Clear the original communication group information and establish the gloo communication.
        cleanup_and_reinit_process_group(
            master_addr,
530
531
532
533
534
535
536
537
538
        use_storage_comm: TCP rendezvous address for the gloo store.
    """
    # ``api`` imports this module at load time, so this import has to stay function local.
    from hyper_parallel.core.distributed_checkpoint.api import _save_impl  # pylint: disable=import-outside-toplevel
    _start_parent_monitor()
    try:
        meta = _save_impl(
            staged,
            checkpoint_id=checkpoint_id,
593
594
595
596
597
598
599
600
601

    proc.join()
    # Abort may race a result already received above. Keep the Future check,
    # publication and cache update under the same lock as cancellation.
    response.finalize(result, async_callback, proc.exitcode)


def batch_read_worker(file_batch: tuple[int], checkpoint_id: str, file_type: FileType) -> list:
    """
751
752
753
754
755
756
757
758
759
760
        file_path (str): File to delete.
    """
    try:
        os.remove(file_path)
    except FileNotFoundError:
        pass
    except Exception as e:  # pylint: disable=broad-except
        logger.warning(
            "Could not remove the checkpoint exchange file %s, because the error: %s", file_path, e
        )
hyper_parallel/core/distributed_checkpoint/broadcast.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
    absent_somewhere = {ranks for _, reported in gathered for ranks in reported}

    groups = dict(supplied)
    owned = set()
    create_group = dist.new_group
    registry = getattr(create_group, "__self__", None)
    if isinstance(registry, GroupRegistry):
        # These groups are destroyed when loading finishes, so they must not
        # enter the persistent recovery catalog or its sealed-group checks.
        create_group = registry.call_original_new_group
    for group_ranks in wanted:
        # Both inputs to this came from the gather, so every rank takes the same branch.
        fresh = create_group(ranks=list(group_ranks)) if group_ranks in absent_somewhere else None
        if group_ranks not in needed:
            continue
        if fresh is None:
            groups[group_ranks] = _existing_group(group_ranks)
hyper_parallel/core/dtensor/dtensor.py
378
379
380
381
382
383
384
385
386
387
388
389
                raise ValueError("RaggedShard local tensor must be contiguous")
            local_tensor = local_tensor.view(-1)
        elif stride is not None and shape is None:
            raise ValueError("stride requires an explicit shape")
        if run_check and is_recovery_bootstrapping():
            logger.warning("DTensor.from_local: overriding run_check=True with False during replacement bootstrap "
                           "to avoid cross-rank checks while peers may be waiting for recovery")
            run_check = False
        if run_check:
            # pylint: disable=C0415
            from hyper_parallel.core.dtensor._from_local_utils import run_from_local_checks
            run_from_local_checks(
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
        >>> global_tensor = Tensor(np.arange(16).reshape(4, 4))
        >>> dtensor = distribute_tensor(global_tensor, mesh, [Shard(0), Replicate()])
        >>> dtensor = distribute_tensor(global_tensor, mesh, ("dp", "None"))
    """
    if is_recovery_bootstrapping():
        # A replacement constructs local storage while peers are parked.
        # Replica repair supplies device values after communication rebuild.
        if src_data_rank is not None:
            logger.warning("distribute_tensor: overriding src_data_rank=%s with None "
                           "during worker recovery to avoid source-rank communication", src_data_rank)
        src_data_rank = None
    layout = _build_layout(device_mesh, placements, len(tensor.shape))
    if _layout_has_ragged_shard(layout):
        if src_data_rank is None:
            local_tensor = _slice_ragged_tensor(tensor, layout)
hyper_parallel/core/fully_shard/hsdp_scheduler.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
        and park the training thread. Unlike ordinary finalization this
        path never waits on a failed collective, reads an unsharded buffer,
        or replaces a persistent sharded parameter.
        """
        state = self.hsdp_state
        self.reset_iter_state()
        for param in state.hsdp_params:
            param.sharded_param.grad = None
            if hasattr(param.sharded_param, "main_grad"):
                param.sharded_param.main_grad = None
            param._setattr_on_modules(param.sharded_param)
            # Avoid to_sharded(): a failure before the first all-gather may
            # leave unsharded_param_buffers empty.
            if param.unsharded_param_buffers and param.unsharded_param_buffers[0] is not param._sharded_param_data:
                param.free_unsharded_param()
            param.sharded_state = type(param.sharded_state).SHARDED
        state.is_shard = True

    def set_requires_grad_sync(self, requires_grad_sync: bool) -> None:
        """Set flag controlling whether gradients are synchronized.
hyper_parallel/core/optimizer/muon.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319

    def reset_optimizer_parameters(self) -> None:
        """Rebuild all parameter-identity caches from current param groups."""
        self._group_dtensor_by_mesh()
        if is_recovery_bootstrapping():
            # Peers are parked until communication rebuild. Shape collectives
            # must run on all workers from rebuild_recovery_state instead.
            self._param_shard_metadata = {}
        else:
            self._build_param_shard_metadata()
        if self.hsdp_replica_count is None:
            self.hsdp_replica_count = self._auto_deduce_replica_count()
        self._split_replicate_groups()
        self._build_hsdp_batch()
        self._build_param_broadcast_info()
        self._classify_parameters_for_step()
319
320
321
322
323
324
325
326
327
        self._classify_parameters_for_step()

    def rebuild_recovery_state(self) -> None:
        """Refresh shard shapes on every rank after existing groups are reinitialized."""
        self._build_param_shard_metadata()

    @staticmethod
    def _validate_ns_coefficients(
            ns_variant: str,
hyper_parallel/core/optimizer/muon_shard.py
194
195
196
197
198
199
200
201

    param_to_meta: Dict[torch.Tensor, ParamShardMeta] = {}
    for record, stage_metas in zip(hsdp_group.records, stage_metas_per_param):
        shard_meta = make_param_shard_meta(record.param, stage_metas)
        record.shard_meta = shard_meta
        param_to_meta[record.param] = shard_meta
    return param_to_meta

hyper_parallel/core/optimizer/optimizer.py
481
482
483
484
485
486
487
488
489
490
491
492
493
            parent_pg: dist.ProcessGroup,
            sub_size: int,
    ) -> dist.ProcessGroup:
        """Retrieve or collectively create a synchronized sub-ProcessGroup."""
        recovery_group = recovery_optimizer_subgroup(parent_pg, sub_size)
        if recovery_group is not None:
            parent_ranks = tuple(sorted(dist.get_process_group_ranks(parent_pg)))
            self._split_sub_pg_cache[(parent_ranks, sub_size)] = {0: recovery_group}
            return recovery_group
        local_parent_ranks = tuple(sorted(list(dist.get_process_group_ranks(parent_pg))))
        cache_key = (local_parent_ranks, sub_size)

        # Cache Hit Check
hyper_parallel/core/optimizer/swap_adam.py
293
294
295
296
297
298
299
300
301
302
303
        )

    def step_state_device(self, param: Any, group: Dict[str, Any]) -> Any:
        """Use a host step tensor for packed, non-fused Adam updates."""
        if group.get("fused", False) or not self.runtime.packed_enabled:
            return param.device
        return "cpu"

    def _init_param_state(self, param: Any, group: Dict[str, Any]) -> None:
        """Initialize missing Adam state and swap slots for one parameter."""
        state = self.optimizer.state[param]
301
302
303
304
305
306
307
308
309
    def _init_param_state(self, param: Any, group: Dict[str, Any]) -> None:
        """Initialize missing Adam state and swap slots for one parameter."""
        state = self.optimizer.state[param]
        if not self.is_new_adamw and len(state) == 0:
            step_device = self.step_state_device(param, group)
            state["step"] = torch.zeros((), dtype=torch.float32, device=step_device)
        state_keys = ["exp_avg", "exp_avg_sq"]
        if group.get("amsgrad", False):
            state_keys.append("max_exp_avg_sq")
hyper_parallel/core/optimizer/swap_optimizer_base.py
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
            self._checkpoint_broadcasted = False

    def recovery_state(self, param: Any) -> Dict[str, Any]:
        """Return committed local state values from their authoritative storage."""
        state = dict(self.optimizer.state.get(param, {}))
        for key in self._configured_state_keys():
            slot = self._slots.get((id(param), key))
            if slot is None or not slot.swappable:
                continue
            if slot.event is not None or not self.has_host_mirror(slot):
                raise RuntimeError(f"Swap slot {key!r} has not finished writing its CPU mirror.")
            state[key] = slot.cpu_tensor
        return state

    def clear_recovery_slots(self) -> None:
        """Forget receiver slots before binding the donor's state layout."""
        self._slots.clear()
        self._packed_state_bindings.clear()
        self.runtime.invalidate_packed_layout()

    def step_state_device(self, param: Any, group: Dict[str, Any]) -> Any:
        """Return the local device for a scalar optimizer step tensor."""
        del group
        return param.device

    def allocate_recovery_state(self, param: Any, key: str, dtype: torch.dtype) -> Any:
        """Allocate a moment and bind a slot using the local swap policy."""
        param_local = self.runtime._storage_tensor(param)
        tensor = _restore_dtensor_metadata(param, torch.empty_like(param_local, dtype=dtype))
        if key not in self._configured_state_keys():
            return tensor
        slot = self._make_slot(key, tensor)
        self._slots[(id(param), key)] = slot
        if not slot.swappable:
            return tensor
        slot.cpu_tensor = self.runtime.make_zero_cpu_tensor_like(tensor)
        self.runtime.release_device_storage(slot)
        slot.state = "host"
        if slot.packed:
            slot.bind_tensor(slot.cpu_tensor)
        return slot.tensor

    def all_slots(self) -> Iterable[SwapSlot]:
        """Iterate known swap slots."""
        return tuple(self._ordered_slots())
1656
1657
1658
1659
1660
1661
1662
1663
1664
                continue
            exported_state = {}
            for key in self._state_keys_for_param(param):
                slot = self._slots.get((id(param), key))
                if key in saved_state and self.has_host_mirror(slot):
                    local_copy = slot.cpu_tensor.detach().clone()
                    exported_state[key] = _restore_dtensor_metadata(param, local_copy)
            for key, value in saved_state.items():
                if key not in exported_state:
1696
1697
1698
1699
1700
1701
1702
1703

    @staticmethod
    def has_host_mirror(slot: Optional[SwapSlot]) -> bool:
        """Return whether the slot is host-resident and holds a CPU mirror."""
        return slot is not None and slot.state == "host" and slot.cpu_tensor is not None

    def strip_swappable_state(self, state_dict: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[int, Dict[str, Any]]]:
        """Split Adam state tensors out before delegating to Torch loading.
hyper_parallel/data/batching/build_dataloader.py
479
480
481
482
483
484
485
486
487
488
489
490
            state_dict: State saved by the ordinary or balanced native loader.
        """
        # The training frame may still retain the old iterator during rollback.
        # Stop its producers before torchdata drops the loader's iterator reference.
        iterator = self._iterator
        if self.num_workers > 0 and iterator is not None:
            # torchdata exposes worker shutdown only through its iterator's private API.
            iterator._shutdown_workers()  # pylint: disable=protected-access
        sampler = get_sampler_checkpoint_state(state_dict)
        snapshot = state_dict.get("_snapshot", {}).get("_main_snapshot", {})
        native_sampler = sampler if sampler is not None else snapshot.get("_index_sampler_state")
        repartition = isinstance(native_sampler, Mapping) and any(
hyper_parallel/data/indexed/indexed_data_config.py
185
186
187
188
189
190
191
192
193
        collection of discoverable indexed paths, return it unchanged so an explicit blend can be parsed.
    """
    # Both original and replacement workers use the same local ordering.
    # Replaying a distributed directory walk would require parked peers.
    return _resolve_data_paths(
        data_path,
        distributed_walk=distributed_walk and not is_recovery_enabled(),
        file_suffix=file_suffix,
    )
325
326
327
328
329
330
331
332
333
334
335
336
def _walk_data_directories(directories: Sequence[str], file_suffix: str) -> list[str]:
    """Recursively find source files below the assigned directories."""
    file_paths = []
    for directory in directories:
        for root, subdirectories, filenames in os.walk(directory):
            if is_recovery_enabled():
                subdirectories.sort()
                filenames = sorted(filenames)
            for filename in filenames:
                if filename.endswith(file_suffix):
                    path = os.path.abspath(os.path.join(root, filename))
                    file_paths.append(os.path.splitext(path)[0] if file_suffix == ".bin" else path)
hyper_parallel/data/parallel/dataloader_parallel.py
204
205
206
207
208
209
210
211
212
213
214
215
    if not dataloader_context.distributed_enabled:
        local_dataset = dataset_factory()
        return local_dataset

    if is_recovery_reboot():
        # Cache-writer ranks are parked; preserve input ownership and build locally.
        owns_dataset = dataloader_context.data_index_cache or dataloader_context.build_on_rank()
        return dataset_factory() if owns_dataset else None

    local_dataset = None
    builds_cache_first = dataloader_context.build_cache_on_rank()
    owns_dataset = (
hyper_parallel/data/tools/io.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
            )
    else:
        raise ValueError(f"Unsupported object storage path: {remote_path}")

    reboot = is_recovery_reboot()
    torch_dist_enabled = torch.distributed.is_initialized() and not reboot
    rank = torch.distributed.get_rank() if torch_dist_enabled else 0
    if not os.path.exists(local_path) and rank == 0:
        directory = os.path.dirname(local_path) or "."
        os.makedirs(directory, exist_ok=True)
        if reboot:
            with tempfile.TemporaryDirectory(prefix=".idx-recovery-", dir=directory) as temporary:
                staged = os.path.join(temporary, os.path.basename(local_path))
                _download_index_file(remote_path, staged)
                os.replace(staged, local_path)
        else:
            _download_index_file(remote_path, local_path)
    if torch_dist_enabled:
        torch.distributed.barrier()
    if not os.path.exists(local_path):
        raise RuntimeError(f"Index cache file not found after download: {local_path}")
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


def _download_index_file(remote_path: str, local_path: str) -> None:
    """Download a validated object-storage index to one local destination."""
    if remote_path.startswith(S3_PREFIX):
        bucket, key = _parse_s3_path(remote_path)
        client = boto3.client("s3")
        try:
            logger.info("Downloading %s -> %s", remote_path, local_path)
            client.download_file(bucket, key, local_path)
        finally:
            client.close()
    else:
        multi_storage_client.download_file(remote_path, local_path)


class DType(Enum):
    """The NumPy data type Enum for reading the IndexedDataset indices"""
hyper_parallel/high_availability/__init__.py
27
28
29
30
31
32
33
34
35


def __getattr__(name):  # pylint: disable=invalid-name
    """Load runtime APIs only when requested, keeping configuration imports light."""
    if name == "RecoverySession":
        return import_module("hyper_parallel.high_availability.recovery_session").RecoverySession
    if name == "TrainState":
        return import_module("hyper_parallel.high_availability.recovery_state").TrainState
    raise AttributeError(name)
hyper_parallel/high_availability/config.py
33
34
35
36
37
38
39
40
41
42
    controller_port: Optional[int] = None

    def __post_init__(self) -> None:
        """Distinguish omitted endpoints from explicitly hosted Controllers."""
        if self.controller_ip and self.controller_port is None:
            object.__setattr__(self, "controller_port", 8000)
        if self.controller_port is not None and not self.controller_ip:
            raise ValueError("controller_port requires controller_ip; omit both to use TaskD")
        if self.controller_port is not None and not 0 < self.controller_port < 65536:
            raise ValueError("controller_port must be between 1 and 65535")
hyper_parallel/high_availability/group_registry.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47


def is_recovery_enabled() -> bool:
    """Return whether the current execution context belongs to a recovery session."""
    return _ACTIVE_REGISTRY.get() is not None


def is_recovery_reboot() -> bool:
    """Return whether the current session belongs to a replacement worker."""
    registry = _ACTIVE_REGISTRY.get()
    return registry is not None and registry.reboot


def is_recovery_bootstrapping() -> bool:
    """Return whether a replacement is still constructing objects before attach."""
    registry = _ACTIVE_REGISTRY.get()
    return registry is not None and registry.reboot and not registry.sealed


@dataclass(frozen=True)
class GroupDescriptor:
 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

    Returns:
        The local optimizer subgroup, or None when recovery is inactive.
    """
    registry = _ACTIVE_REGISTRY.get()
    if registry is None:
        return None
    parent_ranks = tuple(sorted(dist.get_process_group_ranks(parent)))
    parents = {descriptor.ranks for descriptor in registry.groups
               if len(descriptor.ranks) == len(parent_ranks) and descriptor.purpose != "recovery_backup"}
    if len(parent_ranks) == dist.get_world_size():
        parents.add(tuple(range(dist.get_world_size())))
    if parent_ranks not in parents:
        raise ValueError("register the optimizer's parent mesh groups before recovery subgroup construction")
    key = (tuple(sorted(parents)), sub_size)
    if key not in registry.optimizer_subgroups:
        groups = {}
        for ranks in key[0]:
            if len(ranks) % sub_size:
                raise ValueError("optimizer subgroup size must divide each recorded parent group")
            for start in range(0, len(ranks), sub_size):
                members = ranks[start:start + sub_size]
                group = dist.new_group(
                    ranks=list(members),
                    backend="hccl",
                    group_desc="recovery_optimizer",
                )
                groups[members] = group
        registry.optimizer_subgroups[key] = groups
    rank = dist.get_rank()
    start = (parent_ranks.index(rank) // sub_size) * sub_size
    return registry.optimizer_subgroups[key][parent_ranks[start:start + sub_size]]


class GroupRegistry:
    """Preserve process group identities retained by mesh, buckets and optimizer.
105
106
107
108
109
110
111
112
113
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
    """

    def __init__(self) -> None:
        """Start a fresh deterministic construction catalog."""
        self.groups: list[GroupDescriptor] = []
        self._token = None
        self._original_new_group = None
        self._original_c10d_new_group = None
        self.reboot = False
        self.sealed = False
        self.optimizer_subgroups: dict[Any, Any] = {}

    def __enter__(self) -> "GroupRegistry":
        """Record process groups created in the current execution context."""
        if (_ACTIVE_REGISTRY.get() is not None
                or isinstance(getattr(dist.new_group, "__self__", None), GroupRegistry)):
            raise RuntimeError("nested recovery group registries are not supported")
        self._original_new_group = dist.new_group
        self._original_c10d_new_group = dist.distributed_c10d.new_group
        dist.new_group = self.new_group
        dist.distributed_c10d.new_group = self.new_group
        self._token = _ACTIVE_REGISTRY.set(self)
        return self

    def __exit__(self, *exc: Any) -> None:
        """Restore the caller's construction context."""
        dist.new_group = self._original_new_group
        dist.distributed_c10d.new_group = self._original_c10d_new_group
        self._original_new_group = None
        self._original_c10d_new_group = None
        _ACTIVE_REGISTRY.reset(self._token)

    def new_group(self, *args: Any, **kwargs: Any) -> Any:
        """Validate and record native group creation for this recovery registry.
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

        Returns:
            The native process group or nonmember sentinel.
        """
        options = _NEW_GROUP_SIGNATURE.bind(*args, **kwargs).arguments
        if options.get("use_local_synchronization", False) or options.get("device_id") is not None:
            raise ValueError("recovery groups require lazy init and no local synchronization")
        if getattr(dist.group.WORLD, "bound_device_id", None) is not None:
            raise ValueError("recovery groups require a default group without bound device_id")
        if self.sealed:
            raise RuntimeError("materialize every recovery process group during bootstrap, before attach")
        if options.get("pg_options") is not None:
            raise ValueError("custom HCCL process-group options are not supported by worker recovery")
        backend = str(options.get("backend") or dist.get_backend())
        if backend != "hccl" or os.getenv("TORCH_DIST_INIT_BARRIER", "0") != "0":
            raise ValueError("worker reboot construction requires lazy HCCL and TORCH_DIST_INIT_BARRIER=0")
        group = self.call_original_new_group(*args, **kwargs)
        ranks = tuple(sorted(options.get("ranks") or range(dist.get_world_size())))
        self.groups.append(GroupDescriptor(ranks, backend, options.get("group_desc") or "", group))
        return group

    def call_original_new_group(self, *args: Any, **kwargs: Any) -> Any:
        """Call the saved group factory without reentering the recovery hook.
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

        Returns:
            A native group requiring explicit registration or caller-owned teardown.
        """
        create = self._original_new_group if self._original_new_group is not None else dist.new_group
        return create(*args, **kwargs)

    def register(self, group: Any, purpose: str = "external") -> None:
        """Record a caller-owned group used by the protected model."""
        if self.sealed:
            raise RuntimeError("register process groups before attaching recovery state")
        if any(descriptor.group is group for descriptor in self.groups):
            return
        backend = str(dist.get_backend(group))
        if backend != "hccl":
            raise ValueError("only HCCL process groups support this worker reboot path")
        self.groups.append(GroupDescriptor(tuple(dist.get_process_group_ranks(group)), backend, purpose, group))

    def rebuild(self) -> None:
        """Reinitialize member groups locally; MindIO fences completion before repair."""
        reinit = getattr(dist, "reinit_process_group", None)
        if not callable(reinit):
            raise RuntimeError("torch-npu reinit_process_group is required for process recovery")
        reinit(group=None, rebuild_link=True)
        rank = dist.get_rank()
        seen = {id(dist.group.WORLD)}
        for descriptor in self.groups:
            if rank in descriptor.ranks and id(descriptor.group) not in seen:
                reinit(group=descriptor.group, rebuild_link=True)
                seen.add(id(descriptor.group))
hyper_parallel/high_availability/model_recovery.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    """

    def __init__(self, model: torch.nn.Module, reboot: bool = False) -> None:
        """Check materialized storage and collect optional scheduler cleanup hooks."""
        validate_recovery_model(model)
        if reboot and any(isinstance(parameter, DTensor) for parameter in model.parameters()):
            if _OP_DISPATCHER._rng_tracker is None:  # pylint: disable=protected-access
                # Survivors already have a tracker. A replacement must not
                # trigger the lazy tracker's world broadcast on first use.
                tracker = OffsetBasedRNGTracker(run_state_sync=False)
                _OP_DISPATCHER._rng_tracker = tracker  # pylint: disable=protected-access
        self._schedulers: list[Any] = []
        self._swap_modules = []
        self._has_cpu_offload = False
        self._cp_async_states = {}
        self._model_modules = tuple(model.modules())
        seen = set()
        for module in self._model_modules:
            cp_state = vars(module).get("_context_parallel_async_state")
            if cp_state is not None:
                self._cp_async_states[id(cp_state)] = cp_state
            if "_swap_group_name" in vars(module):
                self._swap_modules.append(module)
            scheduler = getattr(module, "hsdp_scheduler", None)
            if scheduler is None or id(scheduler) in seen:
                continue
            state = scheduler.hsdp_state
            self._has_cpu_offload |= isinstance(state.offload_policy, CPUOffloadPolicy)
            self._schedulers.append(scheduler)
            seen.add(id(scheduler))

    def abort_iteration(self) -> None:
        """Clear retained strategy state after device work abort and main-thread ACK."""
        for scheduler in self._schedulers:
            scheduler.abort_iter_state()

    def reset_after_device_restart(self, synchronize: Callable[[], None]) -> None:
        """Drop swap and CP state after the device becomes usable.
77
78
79
80
81
82
83
84
85
86
87
88
        """
        # Swap reset already synchronizes the device, covering concurrent CP
        # and CPU-offload transfers too. The elif avoids a duplicate fence
        # when these features are enabled together.
        if self._swap_modules:
            SwapManager().reset_after_device_restart(self._swap_modules)
        elif self._cp_async_states or self._has_cpu_offload:
            synchronize()
        for state in self._cp_async_states.values():
            state.reset_after_device_restart()
        for module in self._model_modules:
            vars(module).pop("_context_parallel_output_layout_stack", None)
hyper_parallel/high_availability/recovery_session.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
85
86
87
88
89
90
91
92
93
    """

    def __init__(self, config: RecoveryConfig) -> None:
        """Validate the Ascend runtime and allocate process-local recovery bookkeeping."""
        self.config = config
        if not config.enable_worker_reboot:
            raise ValueError("enable_worker_reboot must be true to construct a RecoverySession")
        self.rank = dist.get_rank() if dist.is_initialized() else int(os.environ["RANK"])
        self.world_size = dist.get_world_size() if dist.is_initialized() else int(os.environ["WORLD_SIZE"])
        # Reads LOCAL_RANK from the environment without requiring an initialized default process group.
        self.local_rank = dist.get_node_local_rank()
        self.sdk = importlib.import_module("mindio_ttp.framework_ttp")
        self.npu = importlib.import_module("torch_npu").npu
        required = ("stop_device", "restart_device", "set_device", "synchronize")
        if any(not callable(getattr(self.npu, name, None)) for name in required):
            raise RuntimeError("torch-npu stop/restart/synchronize APIs are required")
        if not callable(getattr(dist, "reinit_process_group", None)):
            raise RuntimeError("torch-npu reinit_process_group is required")
        if os.getenv("TORCH_DIST_INIT_BARRIER", "0") != "0":
            raise ValueError("TORCH_DIST_INIT_BARRIER must be 0 for replacement worker construction")
        self.npu.set_device(self.local_rank)
        self.groups = GroupRegistry()
        self.metadata_bank = DeviceMetadataBank(self.rank, torch.device("npu", self.local_rank))
        self.replica_transport = None
        self.topology = None
        self.model_adapter = None
        self.step = 0
        self._device_state_step = None
        self.reboot = False
        self.model_state = None
        self.train_state = None
        self._stopped = False
        self._in_update = False
        self._initial_progress_pending = False
        self._processor_initialized = False
        self._running = False
        self._controller_initialized = False
        self._cleanup_callbacks = []

    def register_cleanup(self, callback: Callable[[], None]) -> None:
        """Register local resource cleanup after the training thread has stopped.
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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

        Args:
            callback: Collective-free cleanup executed before restarting the device.
        """
        self._cleanup_callbacks.append(callback)

    def initialize(self) -> None:
        """Start an explicitly configured Controller or connect to TaskD's Controller."""
        if self._processor_initialized:
            raise RuntimeError("Processor is already initialized")
        controller_ip, controller_port = self._controller_endpoint()
        try:
            if self.rank == 0 and self.config.controller_ip:
                # MindIO builds with separate Controller/Processor native
                # loggers need distinct paths when both live in rank zero.
                log_path = os.environ.get("TTP_LOG_PATH")
                os.environ["TTP_LOG_PATH"] = os.path.join(log_path or "logs", "controller")
                try:
                    self.sdk.tft_init_controller(0, self.world_size, False, True, False)
                    self._controller_initialized = True
                    self.sdk.tft_start_controller(controller_ip, controller_port, False, "")
                finally:
                    if log_path is None:
                        os.environ.pop("TTP_LOG_PATH", None)
                    else:
                        os.environ["TTP_LOG_PATH"] = log_path
            self.sdk.tft_init_processor(self.rank, self.world_size, False, False, "", False, True, False)
            # Allow close() to release the Processor if startup or reboot detection fails.
            self._processor_initialized = True
            self.sdk.tft_start_processor(controller_ip, controller_port)
            self.reboot = self.sdk.tft_is_reboot_node()
            self.groups.reboot = self.reboot
        except BaseException:
            self.close()
            raise

    def _controller_endpoint(self) -> tuple[str, int]:
        """Resolve TaskD deployment metadata without using a worker's local Pod IP."""
        if self.config.controller_ip:
            return self.config.controller_ip, self.config.controller_port
        names = ("PROCESSOR_ADDR", "CONTROLLER_ADDR", "TTP_ADDR", "MASTER_ADDR")
        address = next((os.environ[name] for name in names
                        if os.environ.get(name)), "")
        port = os.getenv("TTP_PORT", "")
        if not address or not port:
            raise ValueError("TaskD Controller requires PROCESSOR_ADDR/CONTROLLER_ADDR/TTP_ADDR/MASTER_ADDR "
                             "and TTP_PORT pointing to its reachable deployment endpoint")
        try:
            port = int(port)
        except ValueError as error:
            raise ValueError("TaskD TTP_PORT must be an integer between 1 and 65535") from error
        if not 0 < port < 65536:
            raise ValueError("TaskD TTP_PORT must be between 1 and 65535")
        return address, port

    def attach(self, model: torch.nn.Module, optimizer: Any, train_state: TrainState, step: int = 0) -> None:
        """Bind protected objects and register recovery callbacks.
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
            optimizer: Optimizer or collection of supported optimizer leaves.
            train_state: Rank-owned and replica-equivalent training state adapter.
            step: Number of completed optimizer updates before training starts.
        """
        if not self._processor_initialized or self.model_state is not None:
            raise RuntimeError("initialize once before attaching training state")
        if not dist.is_initialized() or dist.get_rank() != self.rank or str(dist.get_backend()) != "hccl":
            raise ValueError("attach requires the matching initialized HCCL world")
        if dist.get_world_size() != self.world_size or step < 0:
            raise ValueError("world size or checkpoint step disagrees with recovery configuration")
        self.model_adapter = ModelRecoveryAdapter(model, reboot=self.reboot)
        self.model_state = ModelOptimizerState(model, optimizer)
        self.topology = ReplicaTopology.discover(self.model_state, self.rank, self.world_size, self.reboot)
        self.train_state = train_state
        self.step = step
        self._device_state_step = None if self.reboot else step
        ranks = list(self.topology.members(self.rank))
        replicas = len(ranks)
        replica_info = [{"rank_list": ranks, "replica_cnt": replicas, "replica_shift": 0}]
        self.sdk.tft_set_optimizer_replica(self.rank, replica_info)
        handlers = {
            "stop": self._stop,
            "clean": self._clean,
            "repair": self._repair,
            "rollback": self._rollback,
184
185
186
187
188
189
190
191
192
193
194
195
            "stream_sync": self._sync,
            "save_ckpt": self._unsupported_dump,
            "rename": self._unsupported_dump
        }
        for name, handler in handlers.items():
            getattr(self.sdk, f"tft_register_{name}_handler")(handler)
        group = self.topology.get_metadata_group(self.rank, self.groups)
        self.replica_transport = ReplicaTransport(
            group,
            self.metadata_bank,
            self.model_state,
            torch.device("npu", self.local_rank),
193
194
195
196
197
198
199
200
201
202
203
204
205
            self.metadata_bank,
            self.model_state,
            torch.device("npu", self.local_rank),
        )
        self.groups.sealed = True

    def _capture_metadata(self, step: int) -> None:
        """Keep rank-specific metadata and mutable buffers; never snapshot weights or moments."""
        state = self.model_state.rank_state()
        self.metadata_bank.put(step, {"state": self.train_state.capture(), "extra": state["extra"]}, state["buffers"])

    def initialize_training_progress(self, step: int) -> None:
        """Align the initial progress after native start callbacks without mirroring state.
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

        Args:
            step: Completed updates after any normal initial checkpoint load.
        """
        if not self._initial_progress_pending:
            return
        self.model_state.validate_layout()
        self.step = step
        self._device_state_step = step
        if step > 0:
            self.sdk.tft_report_load_ckpt_step(step)
        self._initial_progress_pending = False

    @contextmanager
    def update(self, step: int) -> Iterator[None]:
        """Guard one positive, consecutive optimizer/scheduler update transaction.
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

        Yields:
            Control to the native optimizer and scheduler update.
        """
        if not self._running or self._in_update or step != self.step + 1:
            raise RuntimeError("updates must be consecutive transactions inside session.run")
        # HCCL's synchronous barrier also fences the local device. Align ranks
        # outside the SDK update window without a duplicate device synchronize.
        if dist.is_initialized():
            dist.barrier()
        self.sdk.tft_start_updating_os()
        self._in_update = True
        self._device_state_step = None
        try:
            yield
            self._sync()
            self._device_state_step = step
            self._capture_metadata(step)
            self._mirror_metadata(step)
            self.sdk.tft_end_updating_os(step)
            self.step = step
            self.pause()
        finally:
            self._in_update = False

    def _mirror_metadata(self, step: int) -> None:
        """Require a complete metadata mirror before publishing a recoverable step."""
        try:
            self.replica_transport.mirror_metadata(step)
        except Exception as error:
            # MindIO retries classified RuntimeErrors; incomplete mirrors must
            # use its non-retry exception path even if retry is enabled later.
            raise MetadataMirrorError(f"metadata mirror failed at step {step}; recovery is unavailable") from error

    def pause(self) -> None:
        """Cooperate at a Python step boundary, including CPU-only waiting loops.
269
270
271
272
273
274
275
276
277
278
279
        fences optimizer entry rather than raising from arbitrary Python
        code. After device stop, a boundary must also unwind into the SDK
        exception loop so its stop callback can finish the main-thread ACK.
        """
        if self._stopped:
            raise RuntimeError("FORCE STOP")
        self.sdk.tft_pause_train(self.step)


    def run(self, body: Callable[[], Any]) -> Any:
        """Enter the exception loop and release owned resources on termination.
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
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
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423

        Raises:
            RuntimeError: The session is uninitialized, unattached, or already running.
        """
        if not self._processor_initialized or self.model_state is None or self._running:
            raise RuntimeError("initialize and attach once before running a recovery body")
        # The SDK retries training and teardown in one loop. A teardown error
        # followed by RETRY may reenter an already completed training body;
        # handling that exit-stage retry is outside the current recovery scope.
        @self.sdk.tft_exception_handler
        def _train(session):
            if session.reboot:
                session.reboot = False
                raise RuntimeError("ARF FINISH")
            return body()

        self._running = True
        self._initial_progress_pending = not self.reboot
        try:
            with self.groups:
                result = _train(self)
            self._processor_initialized = False
            self._controller_initialized = False
        finally:
            self._running = False
            self.close()
        return result

    def close(self) -> None:
        """Release initialized resources outside the active SDK training loop."""
        if self._running:
            return
        if self._processor_initialized:
            self.sdk.tft_destroy_processor()
            self._processor_initialized = False
        if self._controller_initialized:
            self.sdk.tft_destroy_controller()
            self._controller_initialized = False

    def _sync(self) -> None:
        self.npu.set_device(self.local_rank)
        self.npu.synchronize()

    def _stop(self, train_args, ctx) -> None:
        del train_args, ctx
        result = self.npu.stop_device(self.local_rank)
        if result not in (None, 0):
            raise RuntimeError(f"NPU stop_device failed: {result}")
        self._stopped = True
        logger.info("Recovery device stopped: rank=%s step=%s", self.rank, self.step)

    def _clean(self, is_uce_error, train_args, ctx) -> int:
        """Discard interrupted runtime state after stop and restart the device."""
        del train_args, ctx
        if is_uce_error or not self._stopped:
            raise RuntimeError("clean requires a completed device stop; UCE recovery is unsupported")
        for callback in self._cleanup_callbacks:
            callback()
        self.npu.set_device(self.local_rank)
        self.model_adapter.abort_iteration()
        self.npu.restart_device(self.local_rank)
        self.model_adapter.reset_after_device_restart(self.npu.synchronize)
        self._stopped = False
        logger.info("Recovery device cleaned: rank=%s", self.rank)
        return 0

    def _rebuild(self, fault_ranks, train_args, ctx) -> None:
        del train_args, ctx
        if 0 in fault_ranks and self.config.controller_ip:
            raise RuntimeError("rank-zero Controller loss requires restarting the job in this hosting mode")
        self.groups.rebuild()
        logger.info("Recovery groups rebuilt: rank=%s", self.rank)

    def _repair(self, step, need_rebuild, error_ranks, repair_info, train_args, ctx) -> None:
        """Execute the Controller's donor and receiver plan for the target step."""
        del need_rebuild, error_ranks, train_args, ctx
        repair_type = repair_info["repair_type"]
        sending = repair_type == self.sdk.RepairType.RT_SEND.value
        if not sending and repair_type != self.sdk.RepairType.RT_RECV_REPAIR.value:
            raise RuntimeError(f"replica-only recovery does not support repair strategy {repair_type}")
        if sending and self._device_state_step != step:
            raise RuntimeError("donor does not hold valid device state at the requested recovery step")
        pairs = list(zip(repair_info["src"], repair_info["dst"]))
        sources = [source for source, destination in pairs if destination == self.rank]
        if not sending and len(sources) != 1:
            raise RuntimeError("dense recovery requires exactly one source per destination")
        ranks = tuple(sorted(repair_info["rank_list"]))
        group = next((descriptor.group for descriptor in self.groups.groups
                      if tuple(sorted(descriptor.ranks)) == ranks), None)
        if group is None and ranks == tuple(range(self.world_size)):
            group = dist.group.WORLD
        temporary = group is None
        if temporary:
            # A superset could require uninvolved peers to establish HCCL links.
            group = self.groups.call_original_new_group(
                ranks=repair_info["rank_list"],
                backend="hccl",
                use_local_synchronization=True,
            )
        try:
            if sending:
                for destination in repair_info["dst"]:
                    self.replica_transport.send(destination, step, group)
            else:
                self.replica_transport.receive(sources[0], step, group)
                self._device_state_step = step
                logger.info("Recovery state received: rank=%s source=%s step=%s", self.rank, sources[0], step)
        finally:
            if temporary:
                dist.destroy_process_group(group)

    def _rollback(self, step, train_args, ctx) -> None:
        """Restore committed local state after communication and replica repair."""
        del train_args, ctx
        if self._device_state_step != step:
            raise RuntimeError("device state requires replica repair before rollback; no CPU snapshot fallback exists")
        # MindIO waits for all rebuild and repair replies before global rollback.
        # Muon's shape collectives must not run while a peer still clears HCCL keys.
        self.model_state.rebuild_runtime_state()
        snapshot = self.metadata_bank.get(self.rank, step)
        self.npu.set_device(self.local_rank)
        metadata = self.metadata_bank.metadata(self.rank, step)
        self.model_state.restore_rank_state(snapshot["buffers"], metadata["extra"])
        self.train_state.restore(metadata["state"])
        # Replacements have no saved plans. All ranks must rebuild together so
        # the next checkpoint uses the same sequence of planning collectives.
        standard_planner.StandardSavePlanner.cached_save_result.clear()
        self._sync()
        self.step = step
        logger.info("Recovery rollback completed: rank=%s step=%s", self.rank, step)


    @staticmethod
    def _unsupported_dump(*args: Any) -> None:
421
422
423
424
425
426

    @staticmethod
    def _unsupported_dump(*args: Any) -> None:
        """Reject SDK dump strategies rather than acknowledge nonexistent files."""
        del args
        raise RuntimeError("replica-only recovery does not support checkpoint dumping")
hyper_parallel/high_availability/recovery_state.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52


def local_tensor(tensor: torch.Tensor) -> torch.Tensor:
    """Access persistent local storage without redistributing a DTensor."""
    return getattr(tensor, "_local_tensor", tensor)


def clone_metadata(value: Any) -> Any:
    """Copy rank-owned training metadata; never use this for model or optimizer tensors."""
    if isinstance(value, torch.Tensor):
        if value.device.type != "cpu":
            raise ValueError("training metadata cannot contain device tensors; register them as model buffers")
        return value.detach().clone()
    if isinstance(value, dict):
        return {key: clone_metadata(item) for key, item in value.items()}
    if isinstance(value, list):
        return [clone_metadata(item) for item in value]
    if isinstance(value, tuple):
        return tuple(clone_metadata(item) for item in value)
    return copy.deepcopy(value)


class ModelOptimizerState:
    """Bind live local shards without optimizer ``state_dict`` collectives.
 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
    """

    def __init__(self, model: torch.nn.Module, optimizer: Any) -> None:
        """Bind persistent local parameters and every supported optimizer leaf."""
        self.model = model
        self.parameters = dict(model.named_parameters())
        self.buffers = dict(model.named_buffers())
        self.extra_modules = {name: module for name, module in model.named_modules()
                              if type(module).get_extra_state is not torch.nn.Module.get_extra_state}
        self.leaves = []
        roots = optimizer if isinstance(optimizer, (tuple, list)) else [optimizer]
        for root in roots:
            self.leaves.extend(getattr(root, "chained_optimizers", [root]))
        self._swap_leaves = {index: leaf for index, leaf in enumerate(self.leaves) if isinstance(leaf, SwapOptimizer)}
        self.leaves = [self._swap_leaves[index].optimizer if index in self._swap_leaves else leaf
                       for index, leaf in enumerate(self.leaves)]
        if not self.leaves or any(not isinstance(leaf, (AdamW, Muon)) for leaf in self.leaves):
            raise ValueError("process recovery supports HyperParallel AdamW and Muon leaves only")
        self.names = {}
        for name, parameter in self.parameters.items():
            self.names[id(parameter)] = name
            main = getattr(parameter, "main_param", None)
            if main is not None:
                self.names[id(main)] = name
        self._validate_optimizer_parameters()
        self.schema = self._schema()
        self.optimizer_ownership = self._optimizer_ownership()

    def _validate_optimizer_parameters(self) -> None:
        """Require supported moments and one optimizer owner per model parameter."""
        owned = []
        for leaf in self.leaves:
            for group in leaf.param_groups:
                if group.get("amsgrad", False):
                    raise ValueError("AMSGrad process recovery is not supported")
                for parameter in group["params"]:
                    if id(parameter) not in self.names:
                        raise ValueError("optimizer parameter has no stable model FQN")
                    owned.append(id(parameter))
        if len(owned) != len(set(owned)):
            raise ValueError("a recovery parameter must belong to exactly one optimizer leaf")

    def _optimizer_ownership(self, rank: int = None) -> str:
        """Fingerprint the state slots this rank owns after Muon's second partition."""
        ownership = []
        for leaf in self.leaves:
            if isinstance(leaf, Muon):
                owned = self._muon_owned_parameter_ids(leaf, rank)
            else:
                owned = {id(param) for group in leaf.param_groups for param in group["params"]}
            ownership.append(tuple(tuple(self.names[id(param)] for param in group["params"] if id(param) in owned)
                                   for group in leaf.param_groups))
        return hashlib.sha256(repr(ownership).encode()).hexdigest()

    @staticmethod
    def _muon_owned_parameter_ids(optimizer: Muon, rank: int = None) -> set[int]:
        """Resolve owners from Muon's existing local and distributed assignments."""
        owned = set()
        assignments = vars(optimizer)["_hsdp_assignment_batches"]
        for info in assignments.values():
            owned.update(id(param) for param in info["no_comm"])
            for batch in info["batch_groups"]:
                for assignment in batch["sub_batches"]:
                    if rank is None:
                        owned.update(id(param) for param in assignment.owned_params)
                        continue
                    domain = batch["hsdp_group"].comm_key
                    coordinate = np.unravel_index(domain.mesh_rank_list.index(rank), domain.mesh_shape)
                    logical = tuple(coordinate[axis] % size for axis, size in
                                    zip(domain.replicate_mesh_dims, assignment.replicate_sizes))
                    owned.update(id(record.param) for record in assignment.all_records
                                 if assignment.owner_by_index.get(record.index) == logical)
        return owned

    def replica_ownership(self, rank: int) -> str:
        """Derive a model replica's optimizer owners from the existing Muon assignment map.
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

        Returns:
            Optimizer-state ownership fingerprint without remote communication.
        """
        return self._optimizer_ownership(rank)

    def _schema(self) -> str:
        """Fingerprint local shard shape, dtype, storage device, aliases and optimizer ownership."""
        items = [(name, tuple(local_tensor(param).shape), str(param.dtype), local_tensor(param).device.type,
                  str(getattr(param, "placements", ()))) for name, param in self.parameters.items()]
        items += [("buffer:" + name, tuple(buffer.shape), str(buffer.dtype), local_tensor(buffer).device.type)
                  for name, buffer in self.buffers.items()]
        items += [("aliases", tuple((name, self.names[id(param)])
                                    for name, param in self.model.named_parameters(remove_duplicate=False)))]
        items += [("optimizer", tuple((type(leaf).__module__, type(leaf).__qualname__,
                                       getattr(leaf, "hsdp_replica_count", None),
                                       tuple(tuple(self.names[id(param)] for param in group["params"])
                                             for group in leaf.param_groups)) for leaf in self.leaves))]
        items += [("optimizer_swap", tuple((index, swap.config.packed_swap, swap.config.min_numel,
                                              swap.config.state_keys) for index, swap in self._swap_leaves.items()))]
        items += [("extra_modules", tuple(self.extra_modules))]
        return hashlib.sha256(repr(items).encode()).hexdigest()

    def _optimizer_state(self, index: int, parameter: torch.nn.Parameter) -> Mapping[str, Any]:
        swap = self._swap_leaves.get(index)
        if swap is not None:
            return swap.adapter.recovery_state(parameter)
        return self.leaves[index].state.get(parameter, {})

    def metadata(self) -> dict[str, Any]:
        """Describe live device slots without exporting parameter or moment values."""
        self.validate_identities()
        optimizers = []
        for index, leaf in enumerate(self.leaves):
            groups = []
            for group in leaf.param_groups:
                states = {}
                for parameter in group["params"]:
                    values = {}
                    for key, value in self._optimizer_state(index, parameter).items():
                        if isinstance(value, torch.Tensor):
                            values[key] = {"tensor": True, "shape": tuple(local_tensor(value).shape),
                                           "dtype": value.dtype}
                        else:
                            values[key] = {"tensor": False, "value": copy.deepcopy(value)}
                    states[self.names[id(parameter)]] = values
                options = copy.deepcopy({key: value for key, value in group.items() if key != "params"})
                groups.append({"options": options,
                               "states": states})
            optimizers.append(groups)
        return {"schema": self.schema, "optimizer_ownership": self.optimizer_ownership, "optimizers": optimizers}

    def validate_layout(self) -> None:
        """Check that training initialization preserved the validated recovery layout."""
        self.validate_identities()
        if self._schema() != self.schema or self._optimizer_ownership() != self.optimizer_ownership:
            raise RuntimeError("training initialization changed the validated recovery layout")

    def validate_identities(self) -> None:
        """Reject objects that no longer refer to the persistent local shards."""
        for expected, actual in ((self.parameters, dict(self.model.named_parameters())),
                                 (self.buffers, dict(self.model.named_buffers()))):
            if expected.keys() != actual.keys() or any(actual[name] is not value for name, value in expected.items()):
                raise RuntimeError("recovery requires stable persistent parameter and buffer identities")

    def tensor_items(self) -> list[tuple[str, torch.Tensor]]:
        """Return live local tensors, including CPU offload, never model/optimizer snapshots."""
        self.validate_identities()
        result = [("parameter:" + name, local_tensor(parameter)) for name, parameter in self.parameters.items()]
        for index, leaf in enumerate(self.leaves):
            for group in leaf.param_groups:
                for parameter in group["params"]:
                    name = self.names[id(parameter)]
                    if parameter is not self.parameters[name]:
                        result.append((f"main:{index}:{name}", local_tensor(parameter)))
                    for key, value in sorted(self._optimizer_state(index, parameter).items()):
                        if isinstance(value, torch.Tensor):
                            result.append((f"state:{index}:{name}:{key}", local_tensor(value)))
        return result

    def prepare_receive(self, metadata: Mapping[str, Any]) -> None:
        """Allocate matching moment slots on the parameter storage device and preserve layouts.
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

        Args:
            metadata: Donor schema, optimizer ownership and per-parameter state descriptions.
        """
        if metadata["schema"] != self.schema:
            raise RuntimeError("recovery state schema/layout mismatch")
        if metadata["optimizer_ownership"] != self.optimizer_ownership:
            raise RuntimeError("recovery optimizer-state ownership mismatch")
        for index, (leaf, groups) in enumerate(zip(self.leaves, metadata["optimizers"])):
            swap = self._swap_leaves.get(index)
            if swap is not None:
                swap.adapter.clear_recovery_slots()
            for group, saved in zip(leaf.param_groups, groups):
                for key in list(group):
                    if key != "params":
                        del group[key]
                group.update(copy.deepcopy(saved["options"]))
                for parameter in group["params"]:
                    values = {}
                    for key, entry in saved["states"][self.names[id(parameter)]].items():
                        values[key] = self._receive_optimizer_value(swap, parameter, key, entry, group=group)
                    leaf.state[parameter] = values
            if swap is not None:
                swap.adapter.publish_packed_state()

    @staticmethod
    def _receive_optimizer_value(
            swap: Any,
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
            *,
            group: Mapping[str, Any],
    ) -> Any:
        """Allocate the actual receive destination for one local optimizer value."""
        if not entry["tensor"]:
            return copy.deepcopy(entry["value"])
        shape = tuple(entry["shape"])
        parameter_shape = tuple(local_tensor(parameter).shape)
        if swap is not None and key == "step" and not shape:
            device = swap.adapter.step_state_device(parameter, group)
            return torch.empty((), dtype=entry["dtype"], device=device)
        if shape != parameter_shape:
            raise RuntimeError("optimizer moment does not match its local parameter shard")
        if swap is not None:
            return swap.adapter.allocate_recovery_state(parameter, key, entry["dtype"])
        return torch.zeros_like(parameter, dtype=entry["dtype"])

    def rank_state(self) -> dict[str, Any]:
        """Retain rank-local buffers on their original device and small extra metadata."""
        extra = {name: clone_metadata(module.get_extra_state()) for name, module in self.extra_modules.items()}
        return {"buffers": {name: local_tensor(buffer).detach().clone() for name, buffer in self.buffers.items()},
                "extra": extra}

    @torch.no_grad()
    def restore_rank_state(self, buffers: Mapping[str, torch.Tensor], extra: Mapping[str, Any]) -> None:
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

    @torch.no_grad()
    def restore_rank_state(self, buffers: Mapping[str, torch.Tensor], extra: Mapping[str, Any]) -> None:
        """Restore rank-owned device buffers, then align computation and main parameters."""
        for name, buffer in self.buffers.items():
            local_tensor(buffer).copy_(buffers[name])
        for name, module in self.extra_modules.items():
            module.set_extra_state(copy.deepcopy(extra[name]))
        for name, parameter in self.parameters.items():
            main = getattr(parameter, "main_param", None)
            if main is not None and main is not parameter:
                local_tensor(parameter).copy_(local_tensor(main))
            parameter.grad = None
            if hasattr(parameter, "main_grad"):
                parameter.main_grad = None
        for leaf in self.leaves:
            for group in leaf.param_groups:
                for parameter in group["params"]:
                    parameter.grad = None

    def rebuild_runtime_state(self) -> None:
        """Collect Muon shard metadata only after every worker's groups are usable."""
        for leaf in self.leaves:
            if isinstance(leaf, Muon):
                leaf.rebuild_recovery_state()
        if self._optimizer_ownership() != self.optimizer_ownership:
            raise RuntimeError("optimizer-state ownership changed after communication rebuild")


class TrainState:
    """Capture rank-owned RNG/cursor and replica-equivalent training providers.
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
            replica_providers: Named stateful objects interchangeable between full replicas.
            device: Optional device API exposing RNG get/set operations.
            generators: Explicit rank-specific Torch generators keyed by name.
        """
        validate_recovery_state_providers(loader, replica_providers)
        self.loader = loader
        self.replica_providers = dict(replica_providers)
        self.device = device
        self.generators = dict(generators or {})
        self._pending_rng_state = None

    def capture(self) -> dict[str, Any]:
        """Snapshot separate rank-owned and replica-equivalent state groups."""
        rank_state = self._capture_rng()
        rank_state["loader"] = self.loader.state_dict()
        return clone_metadata({
            "rank_state": rank_state,
            "replica_state": {name: provider.state_dict() for name, provider in self.replica_providers.items()},
        })
334
335
336
337
338
339
340
341
342
        })

    def _capture_rng(self) -> dict[str, Any]:
        """Read random state without exporting loader or replica-provider state."""
        return {
            "rng": {"python": random.getstate(), "numpy": np.random.get_state(),
                    "torch": torch.get_rng_state(),
                    "device": self.device.get_rng_state() if self.device is not None else None},
            "generators": {name: generator.get_state() for name, generator in self.generators.items()},
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
        Note:
            The training main thread must call restore_pending_rng after startup/epoch callbacks
            and iterator construction, before consuming training data.
        """
        if set(state["replica_state"]) != set(self.replica_providers):
            raise RuntimeError("replica training state provider schema mismatch")
        rank_state = state["rank_state"]
        if set(rank_state["generators"]) != set(self.generators):
            raise RuntimeError("custom RNG generator schema mismatch")
        if self.loader.load_state_dict(copy.deepcopy(rank_state["loader"])) is False:
            raise RuntimeError("data loader refused the consumed-data cursor rollback")
        for name, provider in self.replica_providers.items():
            provider.load_state_dict(copy.deepcopy(state["replica_state"][name]))
        self._pending_rng_state = clone_metadata({"rng": rank_state["rng"], "generators": rank_state["generators"]})

    def restore_pending_rng(self) -> None:
        """Apply pending RNG once after callbacks and iterator reconstruction.
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385

        Failed application retains the pending state so that the caller can retry.
        Ordinary epoch initialization without a recovery does not change RNG.
        """
        if self._pending_rng_state is not None:
            self._restore_rng(self._pending_rng_state)
            self._pending_rng_state = None

    def _restore_rng(self, rng_state: Mapping[str, Any]) -> None:
        """Apply the committed random streams before training consumes restored data."""
        rng = rng_state["rng"]
        random.setstate(rng["python"])
        np.random.set_state(rng["numpy"])
        torch.set_rng_state(rng["torch"])
        if self.device is not None:
            self.device.set_rng_state(rng["device"])
        for name, generator in self.generators.items():
            generator.set_state(rng_state["generators"][name])
hyper_parallel/high_availability/replica_topology.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54


def device_replica_ranks(parameter: Any, rank: int) -> set[int]:
    """Vary replicated mesh axes only; TP/EP shard coordinates must stay fixed."""
    mesh = getattr(parameter, "device_mesh", None)
    placements = getattr(parameter, "placements", None)
    if mesh is None or placements is None:
        return {rank}
    shape = tuple(mesh.mesh_shape)
    ranks = tuple(int(value) for value in mesh.rank_list)
    own = tuple(np.unravel_index(ranks.index(rank), shape))
    result = set()
    for index, coordinate in enumerate(np.ndindex(shape)):
        if all(placement.is_replicate() or coordinate[axis] == own[axis]
               for axis, placement in enumerate(placements)):
            result.add(ranks[index])
    return result


def model_replica_candidates(state: Any, rank: int, world: int) -> tuple[int, ...]:
    """Intersect declared device-shard equivalence across every model parameter."""
    candidates = set(range(world))
    for parameter in state.parameters.values():
        peers = device_replica_ranks(parameter, rank)
        candidates.intersection_update(peers)
    return tuple(sorted(candidates))


@dataclass(frozen=True)
class ReplicaTopology:
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

    @classmethod
    def from_profiles(cls, profiles: list[dict[str, Any]]) -> "ReplicaTopology":
        """Intersect model equivalence with actual optimizer-state ownership."""
        groups = set()
        for rank, profile in enumerate(profiles):
            peers = tuple(profile["candidates"])
            if len(peers) < 2 or rank not in peers:
                raise ValueError(f"rank {rank} has no equivalent device replica; unique TP/EP shards cannot recover "
                                 "and worker recovery cannot be enabled")
            for peer in peers:
                if not 0 <= peer < len(profiles):
                    raise ValueError("replica rank is outside the training world")
                other = profiles[peer]
                if tuple(other["candidates"]) != peers or other["schema"] != profile["schema"]:
                    raise ValueError("device replica layout or optimizer ownership is inconsistent")
            complete = tuple(peer for peer in peers
                             if profiles[peer]["optimizer_ownership"] == profile["optimizer_ownership"])
            if len(complete) < 2:
                raise ValueError(f"rank {rank} has no complete device replica for model and optimizer state; "
                                 f"worker recovery cannot be enabled (model replicas={peers}). "
                                 "Check Muon hsdp_replica_count and its actual state-owner assignments.")
            groups.add(complete)
        if len({len(group) for group in groups}) != 1:
            raise ValueError("MindIO recovery requires uniform replica counts across these device domains")
        return cls(tuple(sorted(groups)))

    @classmethod
    def discover(cls, state: Any, rank: int, world: int, reboot: bool) -> "ReplicaTopology":
        """Derive equivalent owners locally; validate original workers once without caching.
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

        Returns:
            Complete local-state replicas containing this worker.
        """
        candidates = model_replica_candidates(state, rank, world)
        if len(candidates) < 2:
            raise ValueError(f"rank {rank} has no equivalent device replica; worker recovery cannot be enabled")
        ownership = {peer: state.replica_ownership(peer) for peer in candidates}
        if ownership.get(rank) != state.optimizer_ownership:
            raise ValueError("local Muon owner inference differs from its actual optimizer assignment")
        members = tuple(peer for peer in candidates if ownership[peer] == state.optimizer_ownership)
        if len(members) < 2:
            raise ValueError(f"rank {rank} has no complete device replica for model and optimizer state; "
                             "check Muon hsdp_replica_count and its actual state-owner assignments")
        if not reboot:
            own = {"candidates": candidates, "schema": state.schema,
                   "optimizer_ownership": state.optimizer_ownership}
            profiles = [None] * world
            dist.all_gather_object(profiles, own)
            if cls.from_profiles(profiles).members(rank) != members:
                raise ValueError("derived optimizer replicas disagree with original workers")
        return cls((members,))

    def members(self, rank: int) -> tuple[int, ...]:
        """Return the complete equivalent device-replica domain for this rank."""
        for group in self.replica_groups:
            if rank in group:
                return group
        raise ValueError(f"rank {rank} is outside the device replica topology")

    def get_metadata_group(self, rank: int, registry: GroupRegistry) -> Any:
        """Reuse the first exact registered HCCL group or construct a lazy local handle.
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151

        Returns:
            An existing or newly registered HCCL group with exactly the replica members.
        """
        ranks = tuple(sorted(self.members(rank)))
        group = next((descriptor.group for descriptor in registry.groups
                      if tuple(sorted(descriptor.ranks)) == ranks), None)
        if group is None:
            if ranks == tuple(range(dist.get_world_size())):
                group = dist.group.WORLD
            else:
                if os.getenv("TORCH_DIST_INIT_BARRIER", "0") != "0":
                    raise ValueError("metadata group bootstrap requires TORCH_DIST_INIT_BARRIER=0")
                if getattr(dist.group.WORLD, "bound_device_id", None) is not None:
                    raise ValueError("metadata group bootstrap requires a default group without bound device_id")
                # Hashed names depend on members, not the creation count of other
                # replica domains. No device_id keeps replacement HCCL setup lazy.
                group = registry.call_original_new_group(
                    ranks=list(ranks),
                    backend="hccl",
                    use_local_synchronization=True,
                    group_desc="recovery_metadata",
149
150
151
152
153
154
155
                    backend="hccl",
                    use_local_synchronization=True,
                    group_desc="recovery_metadata",
                )
        if group is not dist.group.WORLD:
            registry.register(group, purpose="recovery_metadata")
        return group
hyper_parallel/high_availability/replica_transport.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


def serialize_metadata(value: Any) -> bytes:
    """Serialize Python training metadata, never model weights or optimizer moments."""
    stream = io.BytesIO()
    torch.save(value, stream)
    return stream.getvalue()


def deserialize_metadata(payload: bytes) -> Any:
    """Decode small metadata received from a trusted training peer."""
    return torch.load(io.BytesIO(payload), map_location="cpu", weights_only=False)


def metadata_to_device(value: Any, device: torch.device) -> torch.Tensor:
    """Place serialized metadata in a device byte buffer."""
    return torch.frombuffer(bytearray(serialize_metadata(value)), dtype=torch.uint8).to(device)


class DeviceMetadataBank:
    """Mirror rank-specific device metadata and keep donor providers local until repair."""
51
52
53
54
55
56
57
58
59
60
61
    """Mirror rank-specific device metadata and keep donor providers local until repair."""

    def __init__(self, rank: int, device: torch.device) -> None:
        """Bind this rank's device and allocate a bounded metadata version ring."""
        self.rank, self.device = rank, device
        self._rank_versions = {}
        self._replica_versions = OrderedDict()
        self._lock = threading.RLock()

    def put(self, step: int, metadata: Any, buffers: dict[str, torch.Tensor]) -> None:
        """Separate local replica providers from mirrored rank state and device buffers.
 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
            step: Committed training step represented by this snapshot.
            metadata: Training snapshot including replica_state and module extra state.
            buffers: Rank-owned buffer snapshots on the worker device.
        """
        for value in buffers.values():
            if value.device != self.device:
                raise ValueError("recovery buffers must reside on the worker device")
        state = metadata["state"]
        with self._lock:
            self._replica_versions[step] = clone_metadata(state["replica_state"])
            self._replica_versions.move_to_end(step)
            while len(self._replica_versions) > _RETAINED_VERSIONS:
                self._replica_versions.popitem(last=False)
        metadata = {**metadata, "state": {"rank_state": state["rank_state"]}}
        self.install(self.rank, step, metadata_to_device(metadata, self.device), buffers)

    def install(self, owner: int, step: int, payload: torch.Tensor, buffers: dict[str, torch.Tensor]) -> None:
        """Install device buffers without retaining a CPU checkpoint."""
        with self._lock:
            slots = self._rank_versions.setdefault(owner, OrderedDict())
            slots[step] = {"owner": owner, "step": step, "payload": payload, "buffers": buffers}
            slots.move_to_end(step)
            while len(slots) > _RETAINED_VERSIONS:
                slots.popitem(last=False)

    def get(self, owner: int, step: int) -> dict[str, Any]:
        """Require exact target-rank metadata; a donor's own RNG is not interchangeable."""
        with self._lock:
            if step not in self._rank_versions.get(owner, {}):
                raise RuntimeError(f"exact training metadata unavailable: owner={owner}, step={step}")
            return self._rank_versions[owner][step]

    def tensors(self) -> list[torch.Tensor]:
        """List retained device allocations for torch-npu safety recovery."""
        with self._lock:
            return [value for slots in self._rank_versions.values() for entry in slots.values()
                    for value in [entry["payload"], *entry["buffers"].values()]]

    def metadata(self, owner: int, step: int) -> dict[str, Any]:
        """Combine target-rank state with the donor's exact-step replica providers.
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

        Returns:
            Decoded rank state combined with the local replica-provider snapshot.
        """
        entry = self.get(owner, step)
        metadata = deserialize_metadata(entry["payload"].cpu().numpy().tobytes())
        with self._lock:
            if step not in self._replica_versions:
                raise RuntimeError(f"exact replica provider metadata unavailable: step={step}")
            metadata["state"]["replica_state"] = clone_metadata(self._replica_versions[step])
        return metadata


class ReplicaTransport:
    """Send the donor's live device model/main/moment tensors directly over HCCL."""
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    """Send the donor's live device model/main/moment tensors directly over HCCL."""

    def __init__(self, group: Any, bank: DeviceMetadataBank, state: Any, device: torch.device) -> None:
        """Bind the exact replica collective group and persistent live device state."""
        self.group = group
        self.metadata_bank = bank
        self.state = state
        self.device = device
        self.ranks = tuple(dist.get_process_group_ranks(group))

    @staticmethod
    def _wait(work: Any) -> None:
        try:
            work.wait(timeout=timedelta(seconds=_METADATA_TIMEOUT_SECONDS))
        except RuntimeError as error:
            raise RuntimeError("SUSPECT REMOTE ERROR: training metadata communication failed") from error

    def mirror_metadata(self, step: int) -> None:
        """Mirror RNG/cursor and rank-local buffers; never mirror parameter or moment values.
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

        Args:
            step: Exact committed step whose rank metadata must be mirrored.
        """
        entry = self.metadata_bank.get(self.metadata_bank.rank, step)
        size = torch.tensor([entry["payload"].numel()], dtype=torch.int64, device=self.device)
        sizes = [torch.empty_like(size) for _ in self.ranks]
        self._wait(dist.all_gather(sizes, size, group=self.group, async_op=True))
        lengths = [int(value.item()) for value in sizes]
        payload = entry["payload"]
        if payload.numel() < max(lengths):
            padded = torch.empty(max(lengths), dtype=torch.uint8, device=self.device)
            padded[:payload.numel()].copy_(payload)
            padded[payload.numel():].zero_()
            payload = padded
        payloads = [torch.empty_like(payload) for _ in self.ranks]
        self._wait(dist.all_gather(payloads, payload, group=self.group, async_op=True))
        buffers = [{} for _ in self.ranks]
        for name, tensor in sorted(entry["buffers"].items()):
            values = [torch.empty_like(tensor) for _ in self.ranks]
            self._wait(dist.all_gather(values, tensor.contiguous(), group=self.group, async_op=True))
            for saved, value in zip(buffers, values):
                saved[name] = value
        for owner, length, value, saved in zip(self.ranks, lengths, payloads, buffers):
            if owner != self.metadata_bank.rank:
                self.metadata_bank.install(owner, step, value[:length], saved)
        self._wait(dist.barrier(group=self.group, async_op=True))

    def _send_tensor(self, tensor: torch.Tensor, destination: int, group: Any = None) -> None:
        flat = tensor.detach().to(device=self.device).contiguous().view(-1)
        chunk = max(1, _TRANSFER_CHUNK_BYTES // tensor.element_size())
        for start in range(0, flat.numel(), chunk):
            dist.send(flat[start:start + chunk], dst=destination, group=group)

    @torch.no_grad()
    def _receive_tensor(self, tensor: torch.Tensor, source: int, group: Any = None) -> None:
        flat = torch.empty(tensor.numel(), dtype=tensor.dtype, device=self.device)
        chunk = max(1, _TRANSFER_CHUNK_BYTES // tensor.element_size())
        for start in range(0, flat.numel(), chunk):
            dist.recv(flat[start:start + chunk], src=source, group=group)
        tensor.copy_(flat.view(tensor.shape))

    def send(self, destination: int, step: int, group: Any = None) -> None:
        """Send metadata, then the donor's current device tensors, never a stored weight copy.
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
            destination: Global rank of the replacement full replica.
            step: Exact committed step selected by MindIO.
            group: MindIO-selected temporary repair group, or the default group.
        """
        if destination not in self.ranks or destination == self.metadata_bank.rank:
            raise ValueError("destination is not an equivalent device replica")
        entry = self.metadata_bank.get(destination, step)
        header = {"optimizer": self.state.metadata(), "training": self.metadata_bank.metadata(destination, step),
                  "owner": destination, "step": step}
        payload = metadata_to_device(header, self.device)
        dist.send(torch.tensor([payload.numel()], dtype=torch.int64, device=self.device),
                  dst=destination, group=group)
        self._send_tensor(payload, destination, group)
        for _, tensor in self.state.tensor_items():
            self._send_tensor(tensor, destination, group)
        for _, tensor in sorted(entry["buffers"].items()):
            self._send_tensor(tensor, destination, group)

    def receive(self, source: int, step: int, group: Any = None) -> None:
        """Receive weights directly into device storage, rebuilding optimizer slots in place.
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
            source: Global rank of the full device-state donor selected by MindIO.
            step: Exact committed step selected by MindIO.
            group: MindIO-selected temporary repair group, or the default group.
        """
        if source not in self.ranks or source == self.metadata_bank.rank:
            raise ValueError("source is not an equivalent device replica")
        length = torch.empty(1, dtype=torch.int64, device=self.device)
        dist.recv(length, src=source, group=group)
        if length.item() <= 0:
            raise RuntimeError("empty device repair header")
        payload = torch.empty(int(length.item()), dtype=torch.uint8, device=self.device)
        self._receive_tensor(payload, source, group)
        header = deserialize_metadata(payload.cpu().numpy().tobytes())
        if header["owner"] != self.metadata_bank.rank or header["step"] != step:
            raise RuntimeError("repair metadata belongs to another logical rank or step")
        self.state.prepare_receive(header["optimizer"])
        for _, tensor in self.state.tensor_items():
            self._receive_tensor(tensor, source, group)
        buffers = {name: torch.empty_like(tensor) for name, tensor in self.state.buffers.items()}
        for _, tensor in sorted(buffers.items()):
            self._receive_tensor(tensor, source, group)
        self.metadata_bank.put(step, header["training"], buffers)
hyper_parallel/high_availability/validation.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

    Args:
        config: Trainer configuration for a recovery-enabled job.
    """
    if config.accelerator.pp_size != 1:
        raise ValueError("PP schedule state requires a dedicated recovery adapter")
    if config.training.backend not in ("hccl", "nccl"):
        raise ValueError("worker recovery requires an HCCL or NCCL backend")
    if config.compile.enabled:
        raise ValueError("worker recovery requires eager training")
    if config.dataloader is None or config.dataloader.use_background_prefetcher:
        raise ValueError("worker recovery requires a stateful loader without background prefetch")
    if config.model_integration.mode != "off" or config.peft is not None or config.magi is not None:
        raise ValueError("worker recovery does not yet cover integration probes, PEFT or external model state")
    if config.training.eval_iters or config.training.eval_steps or config.training.eval_epochs:
        raise ValueError("worker recovery does not yet cover evaluation data state")


def validate_recovery_model(model: torch.nn.Module) -> None:
    """Check live model state and strategy cleanup support before binding.
 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

    Args:
        model: Materialized model with its parallel strategies applied.
    """
    if getattr(model, "_hp_external_state", None) is not None:
        raise ValueError("model-owned external state requires its own recovery provider")
    parameters = list(model.parameters())
    if not parameters or any(parameter.device.type == "meta" for parameter in parameters):
        raise ValueError("recovery requires materialized persistent local parameters")
    validate_low_precision_state(model)
    for module in model.modules():
        attributes = vars(module)
        cp_state = attributes.get("_context_parallel_async_state")
        if cp_state is not None and not callable(getattr(cp_state, "reset_after_device_restart", None)):
            raise ValueError("asynchronous CP state requires a device-restart cleanup method")
        if "_swap_group_name" in attributes:
            pool = attributes.get("cpu_pool")
            if pool is not None and not isinstance(pool, PinnedMemoryPool):
                raise ValueError("activation swap recovery requires the native PinnedMemoryPool")
        scheduler = getattr(module, "hsdp_scheduler", None)
        if scheduler is not None:
            policy = scheduler.hsdp_state.offload_policy
            if policy is not None and type(policy) not in (OffloadPolicy, CPUOffloadPolicy):
                raise ValueError("custom HSDP offload policies require a dedicated recovery adapter")


def validate_low_precision_state(model: torch.nn.Module) -> None:
    """Allow built-in current-scaling computation with ordinary persistent weights.
107
108
109
110
111
112
113
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
        ValueError: A strategy, quantizer or persistent quantized tensor needs a
            dedicated recovery contract. Subclasses are checked explicitly because
            they may introduce unregistered observer or scaling-history state.
    """
    for name, module in model.named_modules():
        has_quantization = False
        for attribute, value in vars(module).items():
            location = f"{name or '<root>'}.{attribute}"
            if isinstance(value, (LinearStrategy, GroupedLinear)):
                specification = _STRATEGIES.get(type(value))
                if specification is None:
                    raise ValueError(f"{location}: custom low-precision strategy requires a recovery adapter")
                quantizer_type, fields = specification
                for field in fields:
                    actual_type = type(getattr(value, field, None))
                    if actual_type is not quantizer_type:
                        raise ValueError(f"{location}.{field}: custom quantizer requires a recovery adapter")
                has_quantization = True
            elif isinstance(value, Quantizer):
                if type(value) not in _QUANTIZERS:
                    raise ValueError(f"{location}: custom quantizer requires a recovery adapter")
                has_quantization = True
        for parameter_name, parameter in module.named_parameters(recurse=False):
            local = getattr(parameter, "_local_tensor", parameter)
            if isinstance(local, QuantizedTensor) or (has_quantization and local.dtype not in _PARAMETER_DTYPES):
                raise ValueError(f"{name or '<root>'}.{parameter_name}: recovery requires high-precision parameters")
        for buffer_name, buffer in module.named_buffers(recurse=False):
            if isinstance(getattr(buffer, "_local_tensor", buffer), QuantizedTensor):
                raise ValueError(f"{name or '<root>'}.{buffer_name}: persistent quantized buffers require an adapter")


def validate_recovery_state_providers(loader: Any, replica_providers: Mapping[str, Any]) -> None:
    """Check that the loader and replica providers expose state save and restore.
141
142
143
144
145
146
147
148
    Args:
        loader: Training loader bound to the recovery session.
        replica_providers: Named objects with equivalent state across replicas.
    """
    for provider in (loader, *replica_providers.values()):
        if (not callable(getattr(provider, "state_dict", None))
                or not callable(getattr(provider, "load_state_dict", None))):
            raise ValueError("recovery requires state_dict/load_state_dict for every training state provider")
hyper_parallel/trainer/base.py
680
681
682
683
684
685
686
687
688
689
            self.config.checkpoint.save_ckpt
            or self.config.checkpoint.save_hf_weights
            or self.config.checkpoint.restore_from is not None
        ):
            self.checkpoint_callback = CheckpointerCallback(self)
            self._callbacks.append(self.checkpoint_callback)
        else:
            logger.info(
                "Checkpointing is inactive (save_ckpt=false, save_hf_weights=false, "
                "restore_from=None); "
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220

    @recovery_epoch_initialized
    def _initialize_train_epoch(self, epoch: int, start_epoch: int) -> None:
        """Prepare the native epoch iterator and dispatch epoch callbacks."""
        if epoch != start_epoch:
            self.train_dataloader.set_epoch(epoch)
            self.data_iterator = HyperIter(
                self.train_dataloader,
                use_background_prefetcher=self.config.dataloader.use_background_prefetcher,
            )
        self.state.epoch = epoch
        self.on_epoch_begin()

    @recovery_train_loop
    def train(self) -> None:
        """Run the configured training loop."""
1232
1233
1234
1235
1236
1237
1238
1239
1240

            try:
                start_epoch = self.state.epoch
                for epoch in range(start_epoch, self.train_epochs):
                    self._initialize_train_epoch(epoch, start_epoch)

                    start_step = self.state.global_step - epoch * self.train_steps
                    train_steps = min(self.train_steps, self.train_iters - epoch * self.train_steps)
                    for _ in range(start_step, train_steps):
hyper_parallel/trainer/callbacks/checkpoint_callback.py
171
172
173
174
175
176
177
178
179
                raise ValueError("Host PP checkpoint requires per-rank extra state")

        self._last_saved_step: int = -1
        self._last_hf_saved_step: int = -1
        self._initial_checkpoint_processed = False
        self.checkpointer = build_checkpointer(
            extra_state_per_rank=self._save_extra_state_per_rank,
        )
        self._hf_checkpoint_manager = (
210
211
212
213
214
215
216
217
218
219
220
221
222
            self._restore_from,
        )
        if self._save_time_interval_seconds > 0:
            self._next_time_save = time.monotonic() + self._save_time_interval_seconds
        if self._initial_checkpoint_processed:
            return
        if not is_recovery_reboot():
            self._load_checkpoint()
        self._initial_checkpoint_processed = True

    def on_step_end(  # pylint: disable=arguments-differ
        self, state: TrainerState, **kwargs: Any
    ) -> None:
279
280
281
282
283
284
285
286
287
288
            self._rotate_checkpoints()

    def cleanup_state(self) -> None:
        """Reset save bookkeeping and abort local persistence before device restart."""
        self._last_saved_step = -1
        self.checkpointer.abort_async_save()

    def wait_for_pending_save(self) -> None:
        """Block until the checkpointer's in-flight async save is persisted."""
        self.checkpointer.maybe_wait_for_async_save()
hyper_parallel/trainer/callbacks/profiler_callback.py
59
60
61
62
63
64
65
66
        self._device_type: Optional[str] = None
        self._is_profiler_started = False
        self._metadata_recorded = False
        self._training_step = 0
        self._resume_step: Optional[int] = None

        if not self.config.enable:
            return
70
71
72
73
74
75
76
77
78
        self.level = self._normalize_level()

    def _create_profiler(self) -> None:
        """Create a fresh backend session for the remaining configured window."""
        rank = self.trainer.global_rank
        if not self._is_profile_required(rank) or self._training_step >= self.stop_step:
            return

        self._device_type, self._profiler_module = self._resolve_profiler_module()
102
103
104
105
106
107
108
109
110
111
112
113
        self.profiler = self._profiler_module.profile(**profile_kwargs)

    def state_dict(self) -> dict[str, int]:
        """Protect session-relative progress without serializing backend resources."""
        return {"training_step": self._training_step}

    def load_state_dict(self, state: dict[str, int]) -> None:
        """Stage committed progress; backend recreation belongs to the main thread."""
        self._resume_step = state["training_step"]

    def on_train_begin(self, state: TrainerState, **kwargs: Any) -> None:
        """Create the initial or restored profiler before the next training step.
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        Args:
            state: Restored Trainer counters; profiling uses its own session-relative count.
            **kwargs: Additional callback context.
        """
        del state, kwargs
        if not self.config.enable:
            return
        if self._resume_step is not None:
            self._stop()
            self._training_step = self._resume_step
            self._resume_step = None
            self._metadata_recorded = False
        if self.profiler is None:
            self._create_profiler()

    def on_step_begin(
        self,
        state: TrainerState,
140
141
142
143
144
145
146
147
148
149
150
            micro_batches: Optional micro-batches prepared for the current step.
            **kwargs: Additional callback context supplied by the trainer.
        """
        del state, micro_batches, kwargs
        if not self.config.enable:
            return
        self._training_step += 1
        if self.profiler is None:
            return

        if not self._is_profiler_started:
148
149
150
151
152
153
154
155
156
            return

        if not self._is_profiler_started:
            self._start()
        if self._training_step >= self.start_step:
            self._record_metadata()

    def on_step_end(
        self,
252
253
254
255
256
257
258
259
260
            return 0
        return level

    def _get_schedule(self) -> Any:
        warmup = min(self.config.warmup_steps, max(0, self.start_step - self._training_step - 1))
        return self._profiler_module.schedule(
            wait=0,
            warmup=warmup,
            active=self.stop_step - max(self.start_step, self._training_step + 1) + 1,
304
305
306
307
308
309
310
311
312

    def _start(self) -> None:
        self.profiler.start()
        self._is_profiler_started = True
        self.profiler.step()

    def _record_metadata(self) -> None:
        """Record distributed topology metadata once per profiling session."""
        if self._metadata_recorded:
328
329
330
331
332
333
334
335
336
337
338
339
340
            logger.warning("Profiler failed to record distributed args: %s", error)

    def _stop(self) -> None:
        """Stop the profiler session and release its resources."""
        if self.profiler is not None and self._is_profiler_started:
            # A stopped device can make finalization fail. Retain the handle so
            # recovery retries cleanup before opening another backend session.
            self.profiler.stop()
        self.profiler = None
        self._is_profiler_started = False


__all__ = ["ProfilerCallback"]
hyper_parallel/trainer/callbacks/tqdm_callback.py
207
208
209
210
211
212
213
214
215
216
        del kwargs
        self._last_updated_step = state.global_step
        if getattr(self.trainer, "global_rank", 0) != 0:
            return
        if self._progress_bar is not None:
            self._progress_bar.close()
        self._progress_bar = self._create_progress_bar(
            total=self.trainer.train_iters,
            initial=state.global_step,
        )
hyper_parallel/trainer/runtime/memory_profiler.py
73
74
75
76
77
78
79
80
81
82
            dp_rank: Rank in the data-parallel group.
        """
        self._discard_previous_session()
        if config is None:
            self.enable = False
            self.mem_info = False
            return

        self._validate(config)
        self.enable = config.enable
 99
100
101
102
103
104
105
106
            self.step()

    def state_dict(self) -> dict[str, int]:
        """Protect recording progress; configuration and history remain local."""
        return {"current_step": self.current_step}

    def load_state_dict(self, state: dict[str, int]) -> None:
        """Restore recording progress; the next step reopens any remaining window.
110
111
112
113
114
115
116
117
118
119
120

        Args:
            state: Committed session-relative recording progress.
        """
        self._discard_previous_session()
        self.current_step = state["current_step"]
        self._session_active = self.mem_info or (self.enable and self.current_step <= self.end_step)

    def step(self) -> None:
        """Advance the state machine before a Trainer training step starts."""
        if not self._session_active:
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
            return

        try:
            if self.enable:
                if self.start_step <= self.current_step <= self.end_step and not self._history_started:
                    self._record()
                # The control point precedes training, so dump after the inclusive end step.
                if self.current_step == self.end_step + 1:
                    try:
                        if self._history_started:
                            self._dump_and_stop_history()
                    finally:
                        if not self.mem_info and not self._history_started:
                            self._session_active = False

            if self.mem_info:
                self._log_memory_info()
        except BaseException:
150
151
152
153
154
155
156
157
            try:
                if self._history_started:
                    self._dump_and_stop_history()
            finally:
                self._session_active = False
        except BaseException:
            self.abort()
            raise
157
158
159
160
161
162
163
164
165
            raise

    def abort(self) -> None:
        """Stop allocator history without dumping or masking a Trainer error."""
        self._session_active = False
        try:
            self._stop_history()
        except Exception:  # pylint: disable=broad-exception-caught
            logger.exception("Failed to stop allocator memory history while aborting training.")
238
239
240
241
242
243
244
245
246
        """Dump the allocator snapshot for a configured rank."""
        if self.global_rank not in self.dump_ranks:
            return
        os.makedirs(self.save_path, exist_ok=True)
        timestamp = time.strftime("%Y-%m-%d-%H-%M-%S")
        file_path = os.path.join(
            self.save_path,
            f"snapshot_{timestamp}_{self.global_rank}.pickle",
        )
hyper_parallel/trainer/runtime/process_recovery.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
        Constructor wrapper that registers groups during native initialization.
    """
    @wraps(initialize)
    def _construct(trainer: Any, config: Any) -> None:
        recovery_config = vars(config).get("worker_recovery")
        if recovery_config is None or not recovery_config.enable_worker_reboot:
            initialize(trainer, config)
            vars(trainer).get("base", trainer).recovery = None
            return
        validate_recovery_config(config)
        session = RecoverySession(recovery_config)
        try:
            session.initialize()
            with session.groups:
                initialize(trainer, config)
            base = vars(trainer).get("base", trainer)
            base.recovery = session
        except BaseException:
            session.close()
            raise
    return _construct


def recovery_train_loop(train: Callable) -> Callable:
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        Entry wrapper that preserves the original method's result.
    """
    @wraps(train)
    def _run(trainer: Any) -> Any:
        base = vars(trainer).get("base", trainer)
        session = vars(base).get("recovery")
        if session is None:
            return train(trainer)
        try:
            return _train_recoverable(trainer, base, session, train)
        finally:
            session.close()
    return _run


def recovery_train_step(train_step: Callable) -> Callable:
87
88
89
90
91
92
93
94
95
96
97
98
99
        Step wrapper preserving the original return value and counter updates.
    """
    @wraps(train_step)
    def _run_step(trainer: Any, *args: Any, **kwargs: Any) -> Any:
        base = vars(trainer).get("base", trainer)
        session = vars(base).get("recovery")
        if session is not None:
            session.pause()
        return train_step(trainer, *args, **kwargs)
    return _run_step


def recovery_epoch_initialized(initialize: Callable) -> Callable:
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        Wrapper preserving the stage result and applying pending RNG once.
    """
    @wraps(initialize)
    def _initialize(trainer: Any, *args: Any, **kwargs: Any) -> Any:
        result = initialize(trainer, *args, **kwargs)
        base = vars(trainer).get("base", trainer)
        session = vars(base).get("recovery")
        if session is not None:
            session.train_state.restore_pending_rng()
        return result
    return _initialize


def recovery_train_initialized(initialize: Callable) -> Callable:
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        Wrapper preserving the callback result and synchronizing initial progress.
    """
    @wraps(initialize)
    def _initialize(trainer: Any, *args: Any, **kwargs: Any) -> Any:
        result = initialize(trainer, *args, **kwargs)
        base = vars(trainer).get("base", trainer)
        session = vars(base).get("recovery")
        if session is not None:
            session.initialize_training_progress(base.state.global_step)
        return result
    return _initialize


def recovery_optimizer_update(step: Callable) -> Callable:
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
        Update wrapper that captures the committed step without changing native counters.
    """
    @wraps(step)
    def _step(base: Any) -> Any:
        session = vars(base).get("recovery")
        if session is not None:
            committing_step = session.step + 1
            transaction = session.update(committing_step)
            vars(base)["_recovery_committing_step"] = committing_step
        else:
            transaction = nullcontext()
        try:
            with transaction:
                return step(base)
        finally:
            if session is not None:
                vars(base).pop("_recovery_committing_step", None)
    return _step


class _TrainerProgress:
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
204
205
206
207
208
209
210
211
212
213
214
215
216
    """Expose the authoritative committed counters without invoking DCP state_dict."""

    def __init__(self, base: Any) -> None:
        """Bind the Trainer whose progress participates in the transaction."""
        self.base = base

    def state_dict(self) -> dict[str, int]:
        """Capture committed counters without collective checkpoint export."""
        state = asdict(self.base.state)
        committing_step = vars(self.base).get("_recovery_committing_step")
        if committing_step is not None:
            state["global_step"] = committing_step
        return state

    def load_state_dict(self, state: dict[str, int]) -> None:
        """Restore progress before recreating the training iterator."""
        self.base.state.global_step = state["global_step"]
        self.base.state.epoch = state["epoch"]


def _build_train_state(base: Any, device: Any) -> TrainState:
    """Build the recovery state from the Trainer's loader and state providers."""
    replica_providers = {"progress": _TrainerProgress(base)}
    schedulers = base.lr_scheduler if isinstance(base.lr_scheduler, list) else [base.lr_scheduler]
    replica_providers.update({f"scheduler_{index}": scheduler for index, scheduler in enumerate(schedulers)
                              if scheduler is not None})
    profiler_callback = getattr(base, "profiler_callback", None)
    if profiler_callback is not None and profiler_callback.config.enable:
        replica_providers["profiler"] = profiler_callback
    memory_config = getattr(getattr(base, "config", None), "memory", None)
    if memory_config is not None and (memory_config.enable or memory_config.mem_info):
        replica_providers["memory_profiler"] = memory_profiler
    source_loader = getattr(base.train_dataloader, "source_dataloader", base.train_dataloader)
    data_generator = getattr(source_loader, "generator", None)
    generators = {"data_loader": data_generator} if data_generator is not None else {}
    return TrainState(base.train_dataloader, replica_providers, device, generators)


def _train_recoverable(trainer: Any, base: Any, session: RecoverySession, train: Callable) -> Any:
    """Bind state once and reenter the original Trainer implementation."""
    state = _build_train_state(base, session.npu)
    checkpoint_callback = getattr(base, "checkpoint_callback", None)
    if checkpoint_callback is not None:
        session.register_cleanup(checkpoint_callback.cleanup_state)
    session.attach(base.model, base.optimizer, state, base.state.global_step)

    def _body() -> Any:
        return train(trainer)

    return session.run(_body)
hyper_parallel/trainer/text_trainer.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337

    @recovery_epoch_initialized
    def _create_data_iterator(self) -> Optional[Iterator[Any]]:
        """Construct the native iterator before consuming this epoch's data."""
        loader = self.base.train_dataloader
        return iter(loader) if loader is not None else None

    def _train_epoch(self, epoch: int, balanced_loader: bool) -> bool:
        """Consume complete optimizer steps and report whether the source epoch ended."""
        data_iterator = self._create_data_iterator()
        start_step = self.base.state.global_step - epoch * self.base.train_steps
        train_steps = min(self.base.train_steps, self.base.train_iters - epoch * self.base.train_steps)
        if balanced_loader:
            start_step = 0
hyper_parallel/trainer/vlm_trainer.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344

    @recovery_epoch_initialized
    def _create_data_iterator(self) -> Optional[Iterator[Any]]:
        """Construct the native iterator before consuming this epoch's data."""
        loader = self.base.train_dataloader
        return iter(loader) if loader is not None else None

    def _train_epoch(self, epoch: int, balanced_loader: bool) -> bool:
        """Run complete optimizer steps and report actual Dataset exhaustion."""
        data_iterator = self._create_data_iterator()
        start_step = self.base.state.global_step - epoch * self.base.train_steps
        train_steps = min(self.base.train_steps, self.base.train_iters - epoch * self.base.train_steps)
        if balanced_loader:
            start_step = 0