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

185 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"""Bridge Trainer microbatches and loss semantics to the HP pipeline scheduler.""" 

16 

17from collections import defaultdict 

18from collections.abc import Iterator 

19from contextlib import nullcontext 

20from contextvars import copy_context 

21from typing import Any, Optional 

22 

23import torch 

24from torch import distributed as dist, nn 

25 

26from hyper_parallel.components.losses.aux_loss import aux_loss_scale_context 

27from hyper_parallel.trainer.callbacks.moe_monitor_callback import MoEMonitorCallback 

28from hyper_parallel.core.pipeline_parallel import ( 

29 MetaStepType, PipelineStage, Schedule1F1B, ScheduleGPipe, ScheduleInterleaved1F1B, ScheduleMPipeTranspose, 

30) 

31from hyper_parallel.trainer.runtime.memory import empty_cache 

32from hyper_parallel.trainer.runtime.loss_aggregation import count_loss_token 

33 

34 

35class _TrainerStage(PipelineStage): 

36 """Preserve one auxiliary-loss context through each microbatch's backward.""" 

37 

38 def __init__(self, runtime: "TrainerPipeline", model: nn.Module) -> None: 

39 mesh = runtime.trainer.mesh 

40 partition = model._hp_pipeline_partition # pylint: disable=protected-access 

41 super().__init__( 

42 model, partition.stage_index, partition.stage_count, 

43 device=runtime.trainer.device, group=mesh.pp_mesh.get_group(), mesh=mesh.pp_mesh, dyn_shape=True, 

44 ) 

45 self.contexts = {} 

46 self.partition = partition 

47 self.runtime = runtime 

48 self.monitor = MoEMonitorCallback(model) 

49 

50 def _forward_submodule(self, *args: torch.Tensor, **kwargs: dict) -> Any: 

51 """Run the local forward and capture stage-local metrics before the next microbatch.""" 

52 runtime = self.runtime 

53 trainer = runtime.trainer 

54 inputs = {**kwargs["inputs"], "pipeline_inputs": args, "use_cache": False} 

55 loss_inputs = kwargs["loss_inputs"] 

56 counts = kwargs["counts"] 

57 micro_index = kwargs["micro_index"] 

58 prepare = getattr(trainer.loss_fn, "prepare_model_inputs", None) 

59 if callable(prepare) and self.partition.is_last: 

60 inputs = prepare(inputs, loss_inputs) 

61 context = trainer.model_fwd_context 

62 with context() if callable(context) else context: 

63 outputs = self.submodule(**inputs) 

64 router_losses = self.monitor.last_aux_losses() 

65 if router_losses: 

66 runtime.router_stats[micro_index, 0] += torch.stack(router_losses).detach().sum() 

67 runtime.router_stats[micro_index, 1] += len(router_losses) 

68 if not self.partition.is_last: 

69 return outputs 

70 loss, metrics = trainer.postforward(outputs, loss_inputs.get("labels"), current_token_counts=counts) 

71 runtime.metrics[micro_index] = { 

72 name: value.detach() for name, value in metrics.items() if name != "router_aux_loss" 

73 } 

74 return loss 

75 

76 def forward_one_chunk(self, micro_index: int, args: Optional[tuple] = None, 

77 kwargs: Optional[dict] = None) -> Any: 

78 """Fetch this DP replica's next batch and run the local stage forward. 

79 

80 Args: 

81 micro_index: Forward microbatch index within the optimizer step. 

82 args: Local positional inputs supplied by the schedule. 

83 kwargs: Unused schedule inputs. The Trainer supplies the batch fields. 

84 """ 

85 runtime = self.runtime 

86 trainer = runtime.trainer 

87 inputs, loss_inputs, counts, scale = runtime.batch_for_chunk(self, micro_index) 

88 trainer.current_token_counts = counts 

89 callback = getattr(trainer, "channel_loss_callback", None) 

90 tracking = callback.micro_step_context(trainer.state, inputs) if callback is not None else nullcontext() 

91 with tracking: 

92 context = copy_context() 

93 scope = aux_loss_scale_context(scale) 

94 context.run(scope.__enter__) 

95 self.contexts[micro_index] = (context, scope) 

96 if callback is not None: 

97 inputs = inputs.copy() 

98 callback.strip_model_inputs(inputs) 

99 if self is runtime.stages[0]: 

100 trainer.model_integration.record_batch(inputs, loss_inputs) 

101 stage_kwargs = {"inputs": inputs, "loss_inputs": loss_inputs, "counts": counts, "micro_index": micro_index} 

102 result = context.run(super().forward_one_chunk, micro_index, args, stage_kwargs) 

103 prefetch_plan = getattr(trainer.train_dataloader, "prefetch_plan", None) 

104 if self is runtime.stages[-1] and callable(prefetch_plan): 

105 prefetch_plan() 

106 return result 

107 

108 def backward_one_chunk(self, micro_index: int) -> None: 

109 """Run backward with the auxiliary-loss scale captured during forward. 

110 

111 Args: 

112 micro_index: Index of the corresponding saved forward context. 

113 """ 

114 context, scope = self.contexts.pop(micro_index) 

115 trainer = self.runtime.trainer 

116 try: 

117 if trainer.config.training.empty_cache_before_backward: 

118 empty_cache() 

119 with trainer.model_bwd_context: 

120 context.run(super().backward_one_chunk, micro_index) 

121 prefetch = getattr(trainer.train_dataloader, "prefetch", None) 

122 if self is self.runtime.stages[0] and callable(prefetch): 

123 prefetch() 

124 finally: 

125 context.run(scope.__exit__, None, None, None) 

126 

127 def clear_cache(self) -> None: 

128 """Release microbatch contexts and saved activations after the schedule finishes.""" 

129 for context, scope in self.contexts.values(): 

130 context.run(scope.__exit__, None, None, None) 

131 self.contexts.clear() 

132 super().clear_cache() 

133 self.fwd_cache.clear() 

134 self.clear_states() 

135 self.last_stage_outputs = None 

136 

137 

138class TrainerPipeline: 

139 """Run a complete optimizer step's microbatches on one local stage. 

140 

141 The data runtime supplies the same DP-coordinate batches to every PP rank. 

142 Labels and model-owned metadata remain local; the schedule sends only the 

143 model adapter's explicit activation/state tensors. 

144 """ 

145 

146 def __init__(self, trainer: Any) -> None: 

147 """Bind the local partition and its PP group to the Trainer.""" 

148 self.trainer = trainer 

149 self.partition = trainer.model._hp_pipeline_partition # pylint: disable=protected-access 

150 self.stages = [_TrainerStage(self, part) for part in getattr(trainer.model, "parts", (trainer.model,))] 

151 self.preprocess = None 

152 self.visual_inputs = {} 

153 if self.partition.mpipe: 

154 self.preprocess = trainer.model.build_mpipe_preprocess() 

155 # Frozen weights can differ after scratch init or checkpoint restore. 

156 group = trainer.mesh.pp_mesh.get_group() 

157 for tensor in (*self.preprocess.parameters(), *self.preprocess.buffers()): 

158 if not tensor.requires_grad: 

159 local = tensor.to_local() if hasattr(tensor, "to_local") else tensor 

160 dist.broadcast(local.detach(), group=group, group_src=0) 

161 self.batch_cache = {} 

162 self.schedule = None 

163 self.batches = None 

164 self.router_stats = None 

165 self.metrics = {} 

166 

167 def batch_for_chunk(self, stage: PipelineStage, micro_index: int) -> tuple: 

168 """Share a microbatch and its token weight across this rank's virtual stages. 

169 

170 Args: 

171 stage: Local chunk about to execute forward. 

172 micro_index: Microbatch index within the current optimizer step. 

173 """ 

174 trainer = self.trainer 

175 if stage is self.stages[0]: 

176 inputs, loss_inputs = next(self.batches) 

177 inputs, loss_inputs = trainer.preforward(inputs), trainer.preforward(loss_inputs) 

178 counts = count_loss_token(loss_inputs) 

179 for name, value in counts.items(): 

180 trainer.step_token_counts[name] = trainer.step_token_counts.get(name, 0) + value.detach() 

181 count = counts["foundation_tokens"] 

182 trainer.on_micro_step_begin({**inputs, **loss_inputs, "token_count": count}) 

183 trainer.begin_fsdp_runtime_diagnostics(micro_index) 

184 mesh = trainer.mesh 

185 if mesh.sequence_parallel: 

186 group = mesh.device_mesh["tp"].get_group() 

187 count = count.clone() 

188 dist.all_reduce(count, group=group) 

189 count = count / dist.get_world_size(group) 

190 self.batch_cache[micro_index] = (inputs, loss_inputs, counts, count * mesh.dp_size * mesh.cp_size) 

191 if stage is self.stages[-1]: 

192 return self.batch_cache.pop(micro_index) 

193 return self.batch_cache[micro_index] 

194 

195 def _load_visual_input(self, step, context): 

196 context.arg_mbs[step.micro_index] = self.visual_inputs.pop(step.micro_index) 

197 

198 def _finish_step(self, losses: list, count: int) -> tuple[float, dict[str, float]]: 

199 """Publish per-microbatch callbacks and the same step numerators on every stage.""" 

200 trainer = self.trainer 

201 group = trainer.mesh.pp_mesh.get_group() 

202 source = trainer.mesh.pp_mesh.rank_list[-1] 

203 keys = [tuple(self.metrics[i]) for i in range(count)] if self.partition.is_last else None 

204 metadata = [(keys, trainer.loss_names) if self.partition.is_last else None] 

205 dist.broadcast_object_list(metadata, src=source, group=group) 

206 keys, trainer.loss_names = metadata[0] 

207 columns = {name: i for i, name in enumerate(dict.fromkeys(name for row in keys for name in row), start=1)} 

208 values = torch.zeros((count, len(columns) + 1), device=trainer.device, dtype=torch.float32) 

209 if self.partition.is_last: 

210 values[:, 0] = torch.stack(losses).detach() 

211 for i, metrics in self.metrics.items(): 

212 for name, value in metrics.items(): 

213 values[i, columns[name]] = value 

214 dist.broadcast(values, src=source, group=group) 

215 dist.all_reduce(self.router_stats, group=group) 

216 router_counts = self.router_stats[:, 1].tolist() 

217 totals = defaultdict(float) 

218 for i, names in enumerate(keys): 

219 metrics = {name: values[i, columns[name]] for name in names} 

220 if router_counts[i]: 

221 metrics["router_aux_loss"] = self.router_stats[i, 0] / router_counts[i] 

222 trainer.on_micro_step_end(metrics) 

223 for name, value in metrics.items(): 

224 totals[name] += value.item() 

225 return sum(values[:, 0].tolist()), totals 

226 

227 def run(self, batches: Iterator[tuple[dict, dict]], count: int) -> tuple[float, dict[str, float]]: 

228 """Consume batches in forward order and schedule their forward/backward work. 

229 

230 Args: 

231 batches: Stage-local iterator over Trainer model and loss inputs. 

232 count: Number of microbatches in this optimizer step. 

233 """ 

234 if not count: 

235 raise ValueError("a pipeline optimizer step needs at least one microbatch") 

236 if self.schedule is None or self.schedule.micro_batch_num != count: 

237 if self.preprocess is not None: 

238 self.schedule = ScheduleMPipeTranspose(self.stages, count, self.preprocess, num_transpose_layers=1) 

239 self.schedule.register_custom_function(MetaStepType.DATA_LOAD, self._load_visual_input) 

240 else: 

241 schedule_type = { 

242 "1f1b": Schedule1F1B, "gpipe": ScheduleGPipe, "interleaved_1f1b": ScheduleInterleaved1F1B, 

243 }[self.trainer.config.pipeline.schedule] 

244 self.schedule = schedule_type(self.stages, count) 

245 self.batches = iter(batches) 

246 self.router_stats = torch.zeros((count, 2), device=self.trainer.device, dtype=torch.float32) 

247 try: 

248 if self.preprocess is not None: 

249 prepared = [] 

250 for index in range(count): 

251 inputs, loss_inputs = next(self.batches) 

252 inputs = inputs.copy() 

253 if self.schedule.owner_of(index) == self.trainer.mesh.pp_rank: 

254 self.visual_inputs[index] = self.preprocess.take_inputs(inputs) 

255 prepared.append((inputs, loss_inputs)) 

256 self.batches = iter(prepared) 

257 return self._finish_step(self.schedule.run(), count) 

258 finally: 

259 for stage in self.stages: 

260 stage.clear_cache() 

261 self.visual_inputs.clear() 

262 self.batch_cache.clear() 

263 self.batches = None 

264 self.router_stats = None 

265 self.metrics.clear() 

266 

267 

268__all__ = ["TrainerPipeline"]