Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / high_availability / model_recovery.py: 94%

50 statements  

« 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"""Model-runtime cleanup adapters separate from recovery scheduling and transport.""" 

16 

17from typing import Any, Callable 

18 

19import torch 

20 

21from hyper_parallel.core.activation_memory.swap import SwapManager 

22from hyper_parallel.core.dtensor.dtensor import DTensor 

23from hyper_parallel.core.dtensor.random import OffsetBasedRNGTracker 

24from hyper_parallel.core.fully_shard.utils import CPUOffloadPolicy 

25from hyper_parallel.core.shard._op_dispatch import _OP_DISPATCHER 

26from hyper_parallel.high_availability.validation import validate_recovery_model 

27from hyper_parallel.models.external_state import get_model_external_state 

28 

29 

30class ModelRecoveryAdapter: 

31 """Bind persistent local state for TP/EP, CP and optional HSDP modules. 

32 

33 TP/EP collective work is owned by the interrupted autograd execution and 

34 released when the SDK unwinds that body. HSDP additionally retains work, 

35 views and bucket references in schedulers, handled by its optional adapter. 

36 """ 

37 

38 def __init__(self, model: torch.nn.Module, reboot: bool = False) -> None: 

39 """Check materialized storage and collect optional scheduler cleanup hooks.""" 

40 validate_recovery_model(model) 

41 self._external_state = get_model_external_state(model) 

42 if reboot and any(isinstance(parameter, DTensor) for parameter in model.parameters()): 

43 if _OP_DISPATCHER._rng_tracker is None: # pylint: disable=protected-access 

44 # Survivors already have a tracker. A replacement must not 

45 # trigger the lazy tracker's world broadcast on first use. 

46 tracker = OffsetBasedRNGTracker(run_state_sync=False) 

47 _OP_DISPATCHER._rng_tracker = tracker # pylint: disable=protected-access 

48 self._schedulers: list[Any] = [] 

49 self._swap_modules = [] 

50 self._has_cpu_offload = False 

51 self._cp_async_states = {} 

52 self._model_modules = tuple(model.modules()) 

53 seen = set() 

54 for module in self._model_modules: 

55 cp_state = vars(module).get("_context_parallel_async_state") 

56 if cp_state is not None: 

57 self._cp_async_states[id(cp_state)] = cp_state 

58 if "_swap_group_name" in vars(module): 

59 self._swap_modules.append(module) 

60 scheduler = getattr(module, "hsdp_scheduler", None) 

61 if scheduler is None or id(scheduler) in seen: 

62 continue 

63 state = scheduler.hsdp_state 

64 self._has_cpu_offload |= isinstance(state.offload_policy, CPUOffloadPolicy) 

65 self._schedulers.append(scheduler) 

66 seen.add(id(scheduler)) 

67 

68 def abort_iteration(self) -> None: 

69 """Clear retained strategy state after device work abort and main-thread ACK.""" 

70 for scheduler in self._schedulers: 

71 scheduler.abort_iter_state() 

72 if self._external_state is not None: 

73 self._external_state.reset_after_recovery() 

74 

75 def reset_after_device_restart(self, synchronize: Callable[[], None]) -> None: 

76 """Drop swap and CP state after the device becomes usable. 

77 

78 Args: 

79 synchronize: Device fence for CPU-offload transfers and asynchronous 

80 CP buffers when activation swap has not already fenced the device. 

81 """ 

82 # Swap reset already synchronizes the device, covering concurrent CP 

83 # and CPU-offload transfers too. The elif avoids a duplicate fence 

84 # when these features are enabled together. 

85 if self._swap_modules: 

86 SwapManager().reset_after_device_restart(self._swap_modules) 

87 elif self._cp_async_states or self._has_cpu_offload: 

88 synchronize() 

89 for state in self._cp_async_states.values(): 

90 state.reset_after_device_restart() 

91 for module in self._model_modules: 

92 vars(module).pop("_context_parallel_output_layout_stack", None)