Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / high_availability / recovery_session.py: 86%
262 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""MindIO-coordinated process recovery independent of parameter partitioning."""
17import importlib
18import logging
19import os
20from contextlib import contextmanager
21from typing import Any, Callable, Iterator
23import torch
24import torch.distributed as dist
26from hyper_parallel.core.distributed_checkpoint import standard_planner
27from hyper_parallel.high_availability.config import WorkerRecoveryConfig
28from hyper_parallel.high_availability.model_recovery import ModelRecoveryAdapter
29from hyper_parallel.high_availability.group_registry import GroupRegistry
30from hyper_parallel.high_availability.recovery_state import ModelOptimizerState, TrainState
31from hyper_parallel.high_availability.replica_topology import ReplicaTopology
32from hyper_parallel.high_availability.replica_transport import DeviceMetadataBank, ReplicaTransport
34logger = logging.getLogger(__name__)
37class MetadataMirrorError(Exception):
38 """Terminate training when required recovery metadata cannot be mirrored."""
41class RecoverySession:
42 """Protect an explicit training body with MindIO Processor callbacks.
44 Construct before the model, use ``groups`` around deterministic local
45 mesh/model construction, then ``attach`` the persistent local state.
46 Call ``run(body)`` once: the SDK reenters only this body after rollback.
47 The body must recreate its iterator from the restored loader and use
48 ``update`` around optimizer, main-param copyback and scheduler updates.
49 Setup, checkpoint loads and teardown belong outside the reentrant body.
51 Rank zero hosts the explicitly configured Controller; otherwise TaskD does.
52 Worker restart remains owned by the existing launcher/TaskD Agent.
53 """
55 def __init__(self, config: WorkerRecoveryConfig) -> None:
56 """Validate the Ascend runtime and allocate process-local recovery bookkeeping."""
57 self.config = config
58 if not config.enable:
59 raise ValueError("enable must be true to construct a RecoverySession")
60 self.rank = dist.get_rank() if dist.is_initialized() else int(os.environ["RANK"])
61 self.world_size = dist.get_world_size() if dist.is_initialized() else int(os.environ["WORLD_SIZE"])
62 # Reads LOCAL_RANK from the environment without requiring an initialized default process group.
63 self.local_rank = dist.get_node_local_rank()
64 self.sdk = importlib.import_module("mindio_ttp.framework_ttp")
65 self.npu = importlib.import_module("torch_npu").npu
66 required = ("stop_device", "restart_device", "set_device", "synchronize")
67 if any(not callable(getattr(self.npu, name, None)) for name in required):
68 raise RuntimeError("torch-npu stop/restart/synchronize APIs are required")
69 if not callable(getattr(dist, "reinit_process_group", None)):
70 raise RuntimeError("torch-npu reinit_process_group is required")
71 if os.getenv("TORCH_DIST_INIT_BARRIER", "0") != "0":
72 raise ValueError("TORCH_DIST_INIT_BARRIER must be 0 for replacement worker construction")
73 self.npu.set_device(self.local_rank)
74 self.groups = GroupRegistry()
75 self.metadata_bank = None
76 self.replica_transport = None
77 self.topology = None
78 self.model_adapter = None
79 self.step = 0
80 self._device_state_step = None
81 self.reboot = False
82 self.model_state = None
83 self.train_state = None
84 self._stopped = False
85 self._in_update = False
86 self._initial_progress_pending = False
87 self._processor_initialized = False
88 self._running = False
89 self._controller_initialized = False
90 self._cleanup_callbacks = []
92 def register_cleanup(self, callback: Callable[[], None]) -> None:
93 """Register local resource cleanup after the training thread has stopped.
95 Args:
96 callback: Collective-free cleanup executed before restarting the device.
97 """
98 self._cleanup_callbacks.append(callback)
100 def initialize(self) -> None:
101 """Start an explicitly configured Controller or connect to TaskD's Controller."""
102 if self._processor_initialized:
103 raise RuntimeError("Processor is already initialized")
104 controller_ip, controller_port = self._controller_endpoint()
105 try:
106 if self.rank == 0 and self.config.controller_ip:
107 # MindIO builds with separate Controller/Processor native
108 # loggers need distinct paths when both live in rank zero.
109 log_path = os.environ.get("TTP_LOG_PATH")
110 os.environ["TTP_LOG_PATH"] = os.path.join(log_path or "logs", "controller")
111 try:
112 self.sdk.tft_init_controller(0, self.world_size, False, True, False)
113 self._controller_initialized = True
114 self.sdk.tft_start_controller(controller_ip, controller_port, False, "")
115 finally:
116 if log_path is None:
117 os.environ.pop("TTP_LOG_PATH", None)
118 else:
119 os.environ["TTP_LOG_PATH"] = log_path
120 self.sdk.tft_init_processor(self.rank, self.world_size, False, False, "", False, True, False)
121 # Allow close() to release the Processor if startup or reboot detection fails.
122 self._processor_initialized = True
123 self.sdk.tft_start_processor(controller_ip, controller_port)
124 self.reboot = self.sdk.tft_is_reboot_node()
125 self.groups.reboot = self.reboot
126 except BaseException:
127 self.close()
128 raise
130 def _controller_endpoint(self) -> tuple[str, int]:
131 """Resolve TaskD deployment metadata without using a worker's local Pod IP."""
132 if self.config.controller_ip:
133 if os.getenv("MINDX_TASK_ID"):
134 raise ValueError(
135 "TaskD-managed Controller (MINDX_TASK_ID is set) conflicts with rank-zero Controller hosting; "
136 "remove controller_ip/controller_port or disable TaskD Controller hosting in the deployment"
137 )
138 return self.config.controller_ip, self.config.controller_port
139 names = ("PROCESSOR_ADDR", "CONTROLLER_ADDR", "TTP_ADDR", "MASTER_ADDR")
140 address = next((os.environ[name] for name in names
141 if os.environ.get(name)), "")
142 port = os.getenv("TTP_PORT", "")
143 if not address or not port:
144 raise ValueError("TaskD Controller requires PROCESSOR_ADDR/CONTROLLER_ADDR/TTP_ADDR/MASTER_ADDR "
145 "and TTP_PORT pointing to its reachable deployment endpoint")
146 try:
147 port = int(port)
148 except ValueError as error:
149 raise ValueError("TaskD TTP_PORT must be an integer between 1 and 65535") from error
150 if not 0 < port < 65536:
151 raise ValueError("TaskD TTP_PORT must be between 1 and 65535")
152 return address, port
154 def attach(self, model: torch.nn.Module, optimizer: Any, train_state: TrainState, step: int = 0) -> None:
155 """Bind protected objects and register recovery callbacks.
157 The caller must have built an eager model with supported offload
158 policies and adapted external state (currently Host Engram). Initial
159 checkpoint loading is permitted only on original workers.
161 Args:
162 model: Materialized model whose persistent local state is protected.
163 optimizer: Optimizer or collection of supported optimizer leaves.
164 train_state: Rank-owned and replica-equivalent training state adapter.
165 step: Number of completed optimizer updates before training starts.
166 """
167 if not self._processor_initialized or self.model_state is not None:
168 raise RuntimeError("initialize once before attaching training state")
169 if not dist.is_initialized() or dist.get_rank() != self.rank or str(dist.get_backend()) != "hccl":
170 raise ValueError("attach requires the matching initialized HCCL world")
171 if dist.get_world_size() != self.world_size or step < 0:
172 raise ValueError("world size or checkpoint step disagrees with recovery configuration")
173 self.model_adapter = ModelRecoveryAdapter(model, reboot=self.reboot)
174 self.model_state = ModelOptimizerState(model, optimizer)
175 self.topology = ReplicaTopology.discover(self.model_state, self.rank, self.world_size, self.reboot)
176 self.train_state = train_state
177 self.step = step
178 self._device_state_step = None if self.reboot else step
179 ranks = list(self.topology.members(self.rank))
180 replicas = len(ranks)
181 replica_info = [{"rank_list": ranks, "replica_cnt": replicas, "replica_shift": 0}]
182 self.sdk.tft_set_optimizer_replica(self.rank, replica_info)
183 handlers = {
184 "stop": self._stop,
185 "clean": self._clean,
186 "repair": self._repair,
187 "rollback": self._rollback,
188 "rebuild_group": self._rebuild,
189 "stream_sync": self._sync,
190 "save_ckpt": self._unsupported_dump,
191 "rename": self._unsupported_dump
192 }
193 for name, handler in handlers.items():
194 getattr(self.sdk, f"tft_register_{name}_handler")(handler)
195 group = self.topology.get_metadata_group(self.rank, self.groups)
196 self.metadata_bank = DeviceMetadataBank(
197 self.rank,
198 torch.device("npu", self.local_rank),
199 )
200 self.replica_transport = ReplicaTransport(
201 group,
202 self.metadata_bank,
203 self.model_state,
204 torch.device("npu", self.local_rank),
205 mirror_metadata=self.config.mirror_metadata,
206 )
207 self.groups.sealed = True
209 def _capture_metadata(self, step: int) -> None:
210 """Keep rank-specific metadata and mutable buffers; never snapshot weights or moments."""
211 model_state = self.model_state.rank_state()
212 training_state = self.train_state.capture()
213 rank_metadata = {
214 "rank_state": training_state["rank_state"],
215 "extra": model_state["extra"],
216 "buffers": model_state["buffers"],
217 }
218 self.metadata_bank.put_snapshot(step, rank_metadata, training_state["replica_state"])
220 def initialize_training_progress(self, step: int) -> None:
221 """Align the initial progress after native start callbacks without mirroring state.
223 Args:
224 step: Completed updates after any normal initial checkpoint load.
225 """
226 if not self._initial_progress_pending:
227 return
228 self.model_state.validate_layout()
229 self.step = step
230 self._device_state_step = step
231 if step > 0:
232 self.sdk.tft_report_load_ckpt_step(step)
233 self._initial_progress_pending = False
235 @contextmanager
236 def update(self, step: int) -> Iterator[None]:
237 """Guard one positive, consecutive optimizer/scheduler update transaction.
239 Data consumption and forward/backward precede this context. All
240 writes to optimizer-owned values, main-to-model copyback and scheduler
241 must complete inside the context. Progress providers must capture the
242 committed step even if the native Trainer advances its counter later.
243 No ``end_updating_os`` is reported after a partial update or failed metadata mirror.
245 Args:
246 step: Next positive, consecutive committed optimizer step.
248 Yields:
249 Control to the native optimizer and scheduler update.
250 """
251 if not self._running or self._in_update or step != self.step + 1:
252 raise RuntimeError("updates must be consecutive transactions inside session.run")
253 # HCCL's synchronous barrier also fences the local device. Align ranks
254 # outside the SDK update window without a duplicate device synchronize.
255 if dist.is_initialized():
256 dist.barrier()
257 self.sdk.tft_start_updating_os()
258 self._in_update = True
259 self._device_state_step = None
260 try:
261 yield
262 self._sync()
263 self._device_state_step = step
264 self._capture_metadata(step)
265 self._mirror_metadata(step)
266 self.sdk.tft_end_updating_os(step)
267 self.step = step
268 self.pause()
269 finally:
270 self._in_update = False
272 def _mirror_metadata(self, step: int) -> None:
273 """Require a complete metadata mirror before publishing a recoverable step."""
274 try:
275 self.replica_transport.mirror_metadata(step)
276 except Exception as error:
277 # MindIO retries classified RuntimeErrors; incomplete mirrors must
278 # use its non-retry exception path even if retry is enabled later.
279 raise MetadataMirrorError(f"metadata mirror failed at step {step}; recovery is unavailable") from error
281 def pause(self) -> None:
282 """Cooperate at a Python step boundary, including CPU-only waiting loops.
284 ``tft_pause_train`` implements SDK pause commands; PRELOCK itself
285 fences optimizer entry rather than raising from arbitrary Python
286 code. After device stop, a boundary must also unwind into the SDK
287 exception loop so its stop callback can finish the main-thread ACK.
288 """
289 if self._stopped:
290 raise RuntimeError("FORCE STOP")
291 self.sdk.tft_pause_train(self.step)
294 def run(self, body: Callable[[], Any]) -> Any:
295 """Enter the exception loop and release owned resources on termination.
297 The body must initialize training progress after its startup callbacks finish
298 and before consuming training data. Initialization is disabled on replacement
299 workers and becomes a no-op after the original startup initialization.
301 Args:
302 body: Reentrant training function with no arguments.
304 Returns:
305 The result returned by the completed training function.
307 Raises:
308 RuntimeError: The session is uninitialized, unattached, or already running.
309 """
310 if not self._processor_initialized or self.model_state is None or self._running:
311 raise RuntimeError("initialize and attach once before running a recovery body")
312 # The SDK retries training and teardown in one loop. A teardown error
313 # followed by RETRY may reenter an already completed training body;
314 # handling that exit-stage retry is outside the current recovery scope.
315 @self.sdk.tft_exception_handler
316 def _train(session):
317 if session.reboot:
318 session.reboot = False
319 raise RuntimeError("ARF FINISH")
320 return body()
322 self._running = True
323 self._initial_progress_pending = not self.reboot
324 try:
325 with self.groups:
326 result = _train(self)
327 self._processor_initialized = False
328 self._controller_initialized = False
329 finally:
330 self._running = False
331 self.close()
332 return result
334 def close(self) -> None:
335 """Release initialized resources outside the active SDK training loop."""
336 if self._running:
337 return
338 if self._processor_initialized:
339 self.sdk.tft_destroy_processor()
340 self._processor_initialized = False
341 if self._controller_initialized:
342 self.sdk.tft_destroy_controller()
343 self._controller_initialized = False
345 def _sync(self) -> None:
346 self.npu.set_device(self.local_rank)
347 self.npu.synchronize()
349 def _stop(self, train_args, ctx) -> None:
350 del train_args, ctx
351 result = self.npu.stop_device(self.local_rank)
352 if result not in (None, 0):
353 raise RuntimeError(f"NPU stop_device failed: {result}")
354 self._stopped = True
355 logger.info("Recovery device stopped: rank=%s step=%s", self.rank, self.step)
357 def _clean(self, is_uce_error, train_args, ctx) -> int:
358 """Discard interrupted runtime state after stop and restart the device."""
359 del train_args, ctx
360 if is_uce_error or not self._stopped:
361 raise RuntimeError("clean requires a completed device stop; UCE recovery is unsupported")
362 for callback in self._cleanup_callbacks:
363 callback()
364 self.npu.set_device(self.local_rank)
365 self.model_adapter.abort_iteration()
366 self.npu.restart_device(self.local_rank)
367 self.model_adapter.reset_after_device_restart(self.npu.synchronize)
368 self._stopped = False
369 logger.info("Recovery device cleaned: rank=%s", self.rank)
370 return 0
372 def _rebuild(self, fault_ranks, train_args, ctx) -> None:
373 del train_args, ctx
374 if 0 in fault_ranks and self.config.controller_ip:
375 raise RuntimeError("rank-zero Controller loss requires restarting the job in this hosting mode")
376 self.groups.rebuild()
377 logger.info("Recovery groups rebuilt: rank=%s", self.rank)
379 def _repair(self, step, need_rebuild, error_ranks, repair_info, train_args, ctx) -> None:
380 """Execute the Controller's donor and receiver plan for the target step."""
381 del need_rebuild, error_ranks, train_args, ctx
382 repair_type = repair_info["repair_type"]
383 sending = repair_type == self.sdk.RepairType.RT_SEND.value
384 if not sending and repair_type != self.sdk.RepairType.RT_RECV_REPAIR.value:
385 raise RuntimeError(f"replica-only recovery does not support repair strategy {repair_type}")
386 if sending and self._device_state_step != step:
387 raise RuntimeError("donor does not hold valid device state at the requested recovery step")
388 pairs = list(zip(repair_info["src"], repair_info["dst"]))
389 sources = [source for source, destination in pairs if destination == self.rank]
390 if not sending and len(sources) != 1:
391 raise RuntimeError("dense recovery requires exactly one source per destination")
392 ranks = tuple(sorted(repair_info["rank_list"]))
393 group = next((descriptor.group for descriptor in self.groups.groups
394 if tuple(sorted(descriptor.ranks)) == ranks), None)
395 if group is None and ranks == tuple(range(self.world_size)):
396 group = dist.group.WORLD
397 temporary = group is None
398 if temporary:
399 # A superset could require uninvolved peers to establish HCCL links.
400 group = self.groups.call_original_new_group(
401 ranks=repair_info["rank_list"],
402 backend="hccl",
403 use_local_synchronization=True,
404 )
405 try:
406 if sending:
407 for destination in repair_info["dst"]:
408 self.replica_transport.send(destination, step, group)
409 else:
410 self.replica_transport.receive(sources[0], step, group)
411 self._device_state_step = step
412 logger.info("Recovery state received: rank=%s source=%s step=%s", self.rank, sources[0], step)
413 finally:
414 if temporary:
415 dist.destroy_process_group(group)
417 def _rollback(self, step, train_args, ctx) -> None:
418 """Restore committed local state after communication and replica repair."""
419 del train_args, ctx
420 if self._device_state_step != step:
421 raise RuntimeError("device state requires replica repair before rollback; no CPU snapshot fallback exists")
422 # MindIO waits for all rebuild and repair replies before global rollback.
423 # Muon's shape collectives must not run while a peer still clears HCCL keys.
424 self.model_state.rebuild_runtime_state()
425 self.npu.set_device(self.local_rank)
426 rank_metadata = self.metadata_bank.get_rank_metadata(self.rank, step)
427 replica_state = self.metadata_bank.get_replica_state(step)
428 self.model_state.restore_model_state(rank_metadata["buffers"], rank_metadata["extra"])
429 self.train_state.restore(rank_metadata["rank_state"], replica_state)
430 # Replacements have no saved plans. All ranks must rebuild together so
431 # the next checkpoint uses the same sequence of planning collectives.
432 standard_planner.StandardSavePlanner.cached_save_result.clear()
433 self._sync()
434 self.step = step
435 logger.info("Recovery rollback completed: rank=%s step=%s", self.rank, step)
438 @staticmethod
439 def _unsupported_dump(*args: Any) -> None:
440 """Reject SDK dump strategies rather than acknowledge nonexistent files."""
441 del args
442 raise RuntimeError("replica-only recovery does not support checkpoint dumping")