Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / callbacks / profiler_callback.py: 92%

179 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"""MindFormers-derived training profiler backed by PyTorch.""" 

16 

17from __future__ import annotations 

18 

19import json 

20import logging 

21from pathlib import Path 

22from typing import TYPE_CHECKING, Any, Optional 

23 

24# Trainer is Torch-owned; match the other callbacks under the legacy backend-import checker. 

25import torch 

26 

27from hyper_parallel.trainer.callbacks.base import Callback 

28from hyper_parallel.trainer.config.training import ProfilingAnalysisConfig, ProfilingConfig 

29from hyper_parallel.trainer.runtime.device import get_device_type 

30from hyper_parallel.trainer.state import TrainerState 

31 

32 

33if TYPE_CHECKING: 

34 from hyper_parallel.trainer.base import BaseTrainer 

35 

36 

37logger = logging.getLogger(__name__) 

38 

39 

40class ProfilerCallback(Callback): 

41 """Collect a bounded CPU, CUDA, or Ascend NPU profile. 

42 

43 The profiler schedule, rank selection, output layout, metadata, and NPU 

44 options follow MindFormers ``ProfileMonitor`` semantics. PyTorch profiler 

45 activities replace the corresponding MindSpore profiler backend. 

46 """ 

47 

48 def __init__(self, trainer: "BaseTrainer") -> None: 

49 """Prepare and validate the configuration without creating backend resources. 

50 

51 Args: 

52 trainer: Trainer that owns the callback lifecycle. 

53 """ 

54 super().__init__(trainer) 

55 self.config: ProfilingConfig = trainer.config.profiler 

56 self.profiler: Any = None 

57 self.output_path: Optional[Path] = None 

58 self._profiler_module: Any = None 

59 self._device_type: Optional[str] = None 

60 self._is_profiler_started = False 

61 self._metadata_recorded = False 

62 self._training_step = 0 

63 self._resume_step: Optional[int] = None 

64 

65 if not self.config.enable: 

66 return 

67 

68 self._validate_types() 

69 self.start_step, self.stop_step = self._normalize_steps() 

70 self.level = self._normalize_level() 

71 

72 def _create_profiler(self) -> None: 

73 """Create a fresh backend session for the remaining configured window.""" 

74 rank = self.trainer.global_rank 

75 if not self._is_profile_required(rank) or self._training_step >= self.stop_step: 

76 return 

77 

78 self._device_type, self._profiler_module = self._resolve_profiler_module() 

79 

80 output_root = Path(self.config.output_path or "./output").expanduser() 

81 self.output_path = output_root / "profile" / f"rank_{rank}" 

82 logger.info("Profile save path: %s", self.output_path) 

83 

84 schedule_config = self._get_schedule() 

85 trace_handler_options = {} 

86 if self._device_type == "npu": 

87 trace_handler_options = { 

88 "analyse_flag": self.config.analysis.enable, 

89 "async_mode": self.config.analysis.async_mode, 

90 } 

91 profile_kwargs = { 

92 "activities": self._get_activities(), 

93 "profile_memory": self.config.memory, 

94 "with_stack": self.config.with_stack, 

95 "schedule": schedule_config, 

96 "on_trace_ready": self._profiler_module.tensorboard_trace_handler( 

97 str(self.output_path), **trace_handler_options 

98 ), 

99 } 

100 if self._device_type == "npu": 

101 profile_kwargs["experimental_config"] = self._get_npu_experimental_config() 

102 self.profiler = self._profiler_module.profile(**profile_kwargs) 

103 

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

105 """Protect session-relative progress without serializing backend resources.""" 

106 return {"training_step": self._training_step} 

107 

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

109 """Stage committed progress; backend recreation belongs to the main thread.""" 

110 self._resume_step = state["training_step"] 

111 

112 def on_train_begin(self, state: TrainerState, **kwargs: Any) -> None: 

113 """Create the initial or restored profiler before the next training step. 

114 

115 Args: 

116 state: Restored Trainer counters; profiling uses its own session-relative count. 

117 **kwargs: Additional callback context. 

118 """ 

119 del state, kwargs 

120 if not self.config.enable: 

121 return 

122 if self._resume_step is not None: 

123 self._stop() 

124 self._training_step = self._resume_step 

125 self._resume_step = None 

126 self._metadata_recorded = False 

127 if self.profiler is None: 

128 self._create_profiler() 

129 

130 def on_step_begin( 

131 self, 

132 state: TrainerState, 

133 micro_batches: Optional[list[dict[str, Any]]] = None, 

134 **kwargs: Any, 

135 ) -> None: 

136 """Start the profiler and align its schedule with the first training step. 

137 

138 Args: 

139 state: Current trainer state. 

140 micro_batches: Optional micro-batches prepared for the current step. 

141 **kwargs: Additional callback context supplied by the trainer. 

142 """ 

143 del state, micro_batches, kwargs 

144 if not self.config.enable: 

145 return 

146 self._training_step += 1 

147 if self.profiler is None: 

148 return 

149 

150 if not self._is_profiler_started: 

151 self._start() 

152 if self._training_step >= self.start_step: 

153 self._record_metadata() 

154 

155 def on_step_end( 

156 self, 

157 state: TrainerState, 

158 loss: Optional[float] = None, 

159 loss_dict: Optional[dict[str, float]] = None, 

160 grad_norm: Optional[float] = None, 

161 **kwargs: Any, 

162 ) -> None: 

163 """Advance the profiler schedule after one complete optimizer step. 

164 

165 Args: 

166 state: Current trainer state. 

167 loss: Optional scalar loss for the completed step. 

168 loss_dict: Optional named losses for the completed step. 

169 grad_norm: Optional gradient norm for the completed step. 

170 **kwargs: Additional callback context supplied by the trainer. 

171 """ 

172 del state, loss, loss_dict, grad_norm, kwargs 

173 if self.profiler is None or not self._is_profiler_started: 

174 return 

175 

176 self.profiler.step() 

177 if self._training_step == self.stop_step: 

178 logger.info("End of profiling. Analyze the trace under %s", self.output_path) 

179 self._stop() 

180 

181 def on_train_end(self, state: TrainerState, **kwargs: Any) -> None: 

182 """Flush a partial profile when training ends before the stop step. 

183 

184 Args: 

185 state: Final trainer state. 

186 **kwargs: Additional callback context supplied by the trainer. 

187 """ 

188 del state, kwargs 

189 self.close() 

190 

191 def close(self) -> None: 

192 """Stop collection and release a profiler after completion or failure.""" 

193 self._stop() 

194 

195 def _validate_types(self) -> None: 

196 """Validate profiler fields that dataclass construction cannot constrain.""" 

197 boolean_fields = ( 

198 "enable", 

199 "memory", 

200 "with_stack", 

201 "data_simplification", 

202 ) 

203 for name in boolean_fields: 

204 if not isinstance(getattr(self.config, name), bool): 

205 raise TypeError(f"profiler.{name} must be a bool") 

206 if not isinstance(self.config.analysis, ProfilingAnalysisConfig): 

207 raise TypeError("profiler.analysis must be a ProfilingAnalysisConfig") 

208 for name in ("enable", "async_mode"): 

209 if not isinstance(getattr(self.config.analysis, name), bool): 

210 raise TypeError(f"profiler.analysis.{name} must be a bool") 

211 for name in ("start_step", "stop_step", "warmup_steps"): 

212 value = getattr(self.config, name) 

213 if isinstance(value, bool) or not isinstance(value, int): 

214 raise TypeError(f"profiler.{name} must be an int") 

215 if self.config.output_path is not None and not isinstance(self.config.output_path, str): 

216 raise TypeError("profiler.output_path must be a string or null") 

217 ranks = self.config.rank_ids 

218 if ranks is not None: 

219 if not isinstance(ranks, list): 

220 raise TypeError("profiler.rank_ids must be a list or null") 

221 if any(isinstance(rank, bool) or not isinstance(rank, int) or not 0 <= rank < self.trainer.world_size 

222 for rank in ranks): 

223 raise ValueError(f"profiler.rank_ids must contain only integers in [0, {self.trainer.world_size})") 

224 

225 def _normalize_steps(self) -> tuple[int, int]: 

226 """Normalize the inclusive profiling window to valid positive steps.""" 

227 start_step = self.config.start_step 

228 stop_step = self.config.stop_step 

229 if start_step < 1: 

230 logger.warning("profiler.start_step must be greater than 0; reset it to 1") 

231 start_step = 1 

232 if stop_step < 1: 

233 logger.warning("profiler.stop_step must be greater than 0; reset it to 10") 

234 stop_step = 10 

235 if start_step > stop_step: 

236 logger.warning( 

237 "profiler.stop_step must be greater than or equal to profiler.start_step; reset both to 1 and 10" 

238 ) 

239 start_step, stop_step = 1, 10 

240 if not 0 <= self.config.warmup_steps < start_step: 

241 raise ValueError("profiler.warmup_steps must be non-negative and less than profiler.start_step") 

242 return start_step, stop_step 

243 

244 def _normalize_level(self) -> int: 

245 level = self.config.level 

246 if level is None: 

247 return 0 

248 if isinstance(level, bool) or not isinstance(level, int): 

249 raise TypeError("profiler.level must be an int or null") 

250 if level not in (0, 1, 2): 

251 logger.warning("Invalid profiler.level %s; reset it to 0", level) 

252 return 0 

253 return level 

254 

255 def _get_schedule(self) -> Any: 

256 warmup = min(self.config.warmup_steps, max(0, self.start_step - self._training_step - 1)) 

257 return self._profiler_module.schedule( 

258 wait=0, 

259 warmup=warmup, 

260 active=self.stop_step - max(self.start_step, self._training_step + 1) + 1, 

261 repeat=1, 

262 skip_first=max(1, self.start_step - warmup - self._training_step), 

263 ) 

264 

265 def _is_profile_required(self, rank: int) -> bool: 

266 """Return whether the current rank is selected for profiling.""" 

267 ranks = self.config.rank_ids or [] 

268 return not ranks or rank in ranks 

269 

270 def _resolve_profiler_module(self) -> tuple[str, Any]: 

271 """Resolve the profiler backend for the active device type.""" 

272 device_type = get_device_type() 

273 if device_type == "npu": 

274 # torch-npu is optional and must not become a trainer import-time dependency. 

275 import torch_npu # pylint: disable=import-outside-toplevel 

276 

277 return device_type, torch_npu.profiler 

278 if device_type in ("cpu", "cuda"): 

279 return device_type, torch.profiler 

280 raise RuntimeError(f"profiler does not support device type {device_type!r}") 

281 

282 def _get_activities(self) -> list[Any]: 

283 activities = [self._profiler_module.ProfilerActivity.CPU] 

284 if self._device_type == "cuda": 

285 activities.append(self._profiler_module.ProfilerActivity.CUDA) 

286 elif self._device_type == "npu": 

287 activities.append(self._profiler_module.ProfilerActivity.NPU) 

288 return activities 

289 

290 def _get_npu_experimental_config(self) -> Any: 

291 """Build the torch-npu experimental profiler configuration.""" 

292 profiler_level = getattr(self._profiler_module.ProfilerLevel, f"Level{self.level}") 

293 options = { 

294 "profiler_level": profiler_level, 

295 "data_simplification": self.config.data_simplification, 

296 "mstx": False, 

297 } 

298 export_type = getattr(getattr(self._profiler_module, "ExportType", None), "Text", None) 

299 if export_type is not None: 

300 options["export_type"] = [export_type] 

301 # torch-npu exposes this version-dependent profiler entry point only under its private name. 

302 experimental_config = getattr(self._profiler_module, "_ExperimentalConfig") 

303 return experimental_config(**options) 

304 

305 def _start(self) -> None: 

306 self.profiler.start() 

307 self._is_profiler_started = True 

308 self.profiler.step() 

309 

310 def _record_metadata(self) -> None: 

311 """Record distributed topology metadata once per profiling session.""" 

312 if self._metadata_recorded: 

313 return 

314 parallel = self.trainer.config.accelerator 

315 metadata = { 

316 "tensor_model_parallel_size": parallel.tp_size, 

317 "pipeline_model_parallel_size": parallel.pp_size, 

318 "data_parallel_size": getattr(self.trainer.mesh, "dp_size", 1), 

319 "expert_model_parallel_size": parallel.ep_size, 

320 "sequence_parallel": parallel.sequence_parallel, 

321 "parallel_mode": "distributed" if self.trainer.world_size > 1 else "stand_alone", 

322 "world_size": self.trainer.world_size, 

323 } 

324 try: 

325 self.profiler.add_metadata_json("distributed_args", json.dumps(metadata)) 

326 self._metadata_recorded = True 

327 except AttributeError as error: 

328 logger.warning("Profiler failed to record distributed args: %s", error) 

329 

330 def _stop(self) -> None: 

331 """Stop the profiler session and release its resources.""" 

332 if self.profiler is not None and self._is_profiler_started: 

333 # A stopped device can make finalization fail. Retain the handle so 

334 # recovery retries cleanup before opening another backend session. 

335 self.profiler.stop() 

336 self.profiler = None 

337 self._is_profiler_started = False 

338 

339 

340__all__ = ["ProfilerCallback"]