Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / runtime / worker_recovery.py: 97%

119 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"""Adapt Base, Text and VLM Trainer lifecycles to the recovery session.""" 

16 

17from contextlib import nullcontext 

18from dataclasses import asdict 

19from functools import wraps 

20from typing import Any, Callable 

21 

22from hyper_parallel.high_availability.recovery_session import RecoverySession 

23from hyper_parallel.high_availability.recovery_state import TrainState 

24from hyper_parallel.high_availability.validation import validate_recovery_config 

25from hyper_parallel.trainer.runtime.memory_profiler import memory_profiler 

26 

27 

28def recovery_constructor(initialize: Callable) -> Callable: 

29 """Bootstrap the Processor before the Trainer constructs meshes or models. 

30 

31 Args: 

32 initialize: Original Trainer constructor accepting its training configuration. 

33 

34 Returns: 

35 Constructor wrapper that registers groups during native initialization. 

36 """ 

37 @wraps(initialize) 

38 def _construct(trainer: Any, config: Any) -> None: 

39 availability = vars(config).get("high_availability") 

40 recovery_config = availability.worker_recovery if availability is not None else None 

41 if recovery_config is None or not recovery_config.enable: 

42 initialize(trainer, config) 

43 vars(trainer).get("base", trainer).recovery = None 

44 return 

45 validate_recovery_config(config) 

46 session = RecoverySession(recovery_config) 

47 try: 

48 session.initialize() 

49 with session.groups: 

50 initialize(trainer, config) 

51 base = vars(trainer).get("base", trainer) 

52 base.recovery = session 

53 except BaseException: 

54 session.close() 

55 raise 

56 return _construct 

57 

58 

59def recovery_train_loop(train: Callable) -> Callable: 

60 """Run the original Trainer entry point inside the recovery exception loop. 

61 

62 Args: 

63 train: Original Trainer train method, including its native epoch/step loop. 

64 

65 Returns: 

66 Entry wrapper that preserves the original method's result. 

67 """ 

68 @wraps(train) 

69 def _run(trainer: Any) -> Any: 

70 base = vars(trainer).get("base", trainer) 

71 session = vars(base).get("recovery") 

72 if session is None: 

73 return train(trainer) 

74 try: 

75 return _train_recoverable(trainer, base, session, train) 

76 finally: 

77 session.close() 

78 return _run 

79 

80 

81def recovery_train_step(train_step: Callable) -> Callable: 

82 """Honor recovery commands before invoking the native Trainer step. 

83 

84 Args: 

85 train_step: Original Trainer step implementation. 

86 

87 Returns: 

88 Step wrapper preserving the original return value and counter updates. 

89 """ 

90 @wraps(train_step) 

91 def _run_step(trainer: Any, *args: Any, **kwargs: Any) -> Any: 

92 base = vars(trainer).get("base", trainer) 

93 session = vars(base).get("recovery") 

94 if session is not None: 

95 session.pause() 

96 return train_step(trainer, *args, **kwargs) 

97 return _run_step 

98 

99 

100def recovery_epoch_initialized(initialize: Callable) -> Callable: 

101 """Finalize pending RNG after a native epoch initialization stage returns. 

102 

103 Args: 

104 initialize: Native stage completing callbacks and iterator construction. 

105 

106 Returns: 

107 Wrapper preserving the stage result and applying pending RNG once. 

108 """ 

109 @wraps(initialize) 

110 def _initialize(trainer: Any, *args: Any, **kwargs: Any) -> Any: 

111 result = initialize(trainer, *args, **kwargs) 

112 base = vars(trainer).get("base", trainer) 

113 session = vars(base).get("recovery") 

114 if session is not None: 

115 session.train_state.restore_pending_rng() 

116 return result 

117 return _initialize 

118 

119 

120def recovery_train_initialized(initialize: Callable) -> Callable: 

121 """Align initial progress after the native train-begin callbacks return. 

122 

123 Args: 

124 initialize: Native train-begin dispatcher, including initial checkpoint loading. 

125 

126 Returns: 

127 Wrapper preserving the callback result and synchronizing initial progress. 

128 """ 

129 @wraps(initialize) 

130 def _initialize(trainer: Any, *args: Any, **kwargs: Any) -> Any: 

131 result = initialize(trainer, *args, **kwargs) 

132 base = vars(trainer).get("base", trainer) 

133 session = vars(base).get("recovery") 

134 if session is not None: 

135 session.initialize_training_progress(base.state.global_step) 

136 return result 

137 return _initialize 

138 

139 

140def recovery_optimizer_update(step: Callable) -> Callable: 

141 """Keep both Trainer step conventions inside one committed transaction. 

142 

143 Args: 

144 step: Original optimizer and scheduler update method. 

145 

146 Returns: 

147 Update wrapper that captures the committed step without changing native counters. 

148 """ 

149 @wraps(step) 

150 def _step(base: Any) -> Any: 

151 session = vars(base).get("recovery") 

152 if session is not None: 

153 committing_step = session.step + 1 

154 transaction = session.update(committing_step) 

155 vars(base)["_recovery_committing_step"] = committing_step 

156 else: 

157 transaction = nullcontext() 

158 try: 

159 with transaction: 

160 return step(base) 

161 finally: 

162 if session is not None: 

163 vars(base).pop("_recovery_committing_step", None) 

164 return _step 

165 

166 

167class _TrainerProgress: 

168 """Expose the authoritative committed counters without invoking DCP state_dict.""" 

169 

170 def __init__(self, base: Any) -> None: 

171 """Bind the Trainer whose progress participates in the transaction.""" 

172 self.base = base 

173 

174 def state_dict(self) -> dict[str, int]: 

175 """Capture committed counters without collective checkpoint export.""" 

176 state = asdict(self.base.state) 

177 committing_step = vars(self.base).get("_recovery_committing_step") 

178 if committing_step is not None: 

179 state["global_step"] = committing_step 

180 return state 

181 

182 def load_state_dict(self, state: dict[str, int]) -> None: 

183 """Restore progress before recreating the training iterator.""" 

184 self.base.state.global_step = state["global_step"] 

185 self.base.state.epoch = state["epoch"] 

186 

187 

188def _build_train_state(base: Any, device: Any) -> TrainState: 

189 """Build the recovery state from the Trainer's loader and state providers.""" 

190 replica_providers = {"progress": _TrainerProgress(base)} 

191 schedulers = base.lr_scheduler if isinstance(base.lr_scheduler, list) else [base.lr_scheduler] 

192 replica_providers.update({f"scheduler_{index}": scheduler for index, scheduler in enumerate(schedulers) 

193 if scheduler is not None}) 

194 profiler_callback = getattr(base, "profiler_callback", None) 

195 if profiler_callback is not None and profiler_callback.config.enable: 

196 replica_providers["profiler"] = profiler_callback 

197 memory_config = getattr(getattr(base, "config", None), "memory", None) 

198 if memory_config is not None and (memory_config.enable or memory_config.mem_info): 

199 replica_providers["memory_profiler"] = memory_profiler 

200 source_loader = getattr(base.train_dataloader, "source_dataloader", base.train_dataloader) 

201 data_generator = getattr(source_loader, "generator", None) 

202 generators = {"data_loader": data_generator} if data_generator is not None else {} 

203 return TrainState(base.train_dataloader, replica_providers, device, generators) 

204 

205 

206def _train_recoverable(trainer: Any, base: Any, session: RecoverySession, train: Callable) -> Any: 

207 """Bind state once and reenter the original Trainer implementation.""" 

208 state = _build_train_state(base, session.npu) 

209 checkpoint_callback = getattr(base, "checkpoint_callback", None) 

210 if checkpoint_callback is not None: 

211 session.register_cleanup(checkpoint_callback.cleanup_state) 

212 session.attach(base.model, base.optimizer, state, base.state.global_step) 

213 

214 def _body() -> Any: 

215 return train(trainer) 

216 

217 return session.run(_body)