Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / callbacks / moe_monitor_callback.py: 100%
34 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"""Step-level MoE monitoring, also callable from an independent training loop."""
17from typing import Any, Optional
19import torch
20from torch import nn
22from hyper_parallel.core.activation_memory.wrapper import ActivationWrapper
23from hyper_parallel.components.modules.moe.moe_utils import sync_and_update_expert_bias
26class MoEMonitorCallback:
27 """Callback that automates expert bias updates across all MoE layers.
29 Provides a three-layer invocation architecture:
31 - **Layer 0**: :func:`sync_and_update_expert_bias` — per-module sync + update
32 - **Layer 1**: :meth:`on_step_end` — iterates all MoE layers, calling Layer 0
33 - **Layer 2**: :meth:`register` — registers optimizer post-hook for auto-trigger
35 Each layer can be used independently; Layer 0 is sufficient for basic usage,
36 while Layers 1–2 add convenience for production training loops.
38 Args:
39 model: The model containing MoE layers to monitor.
40 lr: Step size for expert bias updates. Defaults to ``1e-3``.
41 tp_group: Tensor parallel process group. Only needed for TP+SP
42 (sequence-sharded activations across TP ranks). Standard TP
43 does not need this — pass ``None``.
44 cp_group: Context parallel process group. Sync across sequence shards.
45 dp_group: Data parallel process group. Sync across different samples.
46 num_recomputations: Number of forward executions per optimizer step.
47 Default ``1``. Set to ``2`` when activation checkpoint is enabled.
49 Example:
50 >>> # Layer 1: manual trigger in training loop
51 >>> callback = MoEMonitorCallback(
52 ... model, lr=1e-3, dp_group=dp_group_info,
53 ... )
54 >>> for batch in dataloader:
55 ... loss = model(batch)
56 ... loss.backward()
57 ... optimizer.step()
58 ... callback.on_step_end() # auto-updates all MoE layers
59 ... optimizer.zero_grad()
60 >>>
61 >>> # Layer 2: auto-trigger via optimizer post-hook
62 >>> callback = MoEMonitorCallback(model, lr=1e-3, dp_group=dp_group_info)
63 >>> callback.register(optimizer)
64 >>> # optimizer.step() now auto-triggers callback.on_step_end()
66 Note:
67 Sync dimensions use ``dp_group``/``tp_group``/``cp_group`` (not ``ep_group``).
68 The adapter reduces unique data and token partition axes. A TP-extended
69 dispatch group overlaps those axes and must not be reduced again.
70 """
72 def __init__(
73 self,
74 model: "nn.Module",
75 lr: float = 1e-3,
76 tp_group: Optional[Any] = None,
77 cp_group: Optional[Any] = None,
78 dp_group: Optional[Any] = None,
79 num_recomputations: int = 1,
80 ) -> None:
81 """Initialize MoEMonitorCallback."""
82 self.model = model
83 self.lr = lr
84 self.tp_group = tp_group
85 self.cp_group = cp_group
86 self.dp_group = dp_group
87 self.num_recomputations = num_recomputations
88 self._hook_handle = None
90 @property
91 def last_mean_aux_loss(self) -> Optional[torch.Tensor]:
92 """Return the mean router metric as an on-device scalar Tensor.
94 Keep the mean on-device so graph capture never reads a Python scalar.
95 Logging callbacks convert the result only when formatting output.
96 Writers detach ``last_aux_loss`` at the source, so the result carries
97 no autograd graph in production. Auxiliary loss remains observable
98 when expert-bias updates are disabled.
99 """
100 aux_losses = self.last_aux_losses()
101 return torch.stack(aux_losses).mean() if aux_losses else None
103 def last_aux_losses(self) -> list[torch.Tensor]:
104 """Return each local router metric once for aggregation across pipeline stages."""
105 return [
106 module.last_aux_loss
107 for module in self.model.modules()
108 if not isinstance(module, ActivationWrapper) and getattr(module, "last_aux_loss", None) is not None
109 ]
111 def on_step_end(self) -> None:
112 """Update expert bias for all MoE layers in the model.
114 Iterates over router modules with
115 ``enable_expert_bias=True`` and calls
116 :func:`sync_and_update_expert_bias` for each one.
118 Auxiliary loss is read separately through ``last_mean_aux_loss`` so
119 bias updates do not synchronize device scalars for logging each step.
120 """
121 for moe in self.model.modules():
122 if isinstance(moe, ActivationWrapper) or not getattr(moe, "enable_expert_bias", False):
123 continue
124 sync_and_update_expert_bias(
125 moe,
126 lr=self.lr,
127 tp_group=self.tp_group,
128 cp_group=self.cp_group,
129 dp_group=self.dp_group,
130 num_recomputations=self.num_recomputations,
131 )
133 def register(self, optimizer: Any) -> None:
134 """Register an optimizer post-hook to auto-trigger :meth:`on_step_end`.
136 Uses ``optimizer.register_step_post_hook``.
137 The hook fires after each ``optimizer.step()`` call, so that
138 expert bias is updated once parameters have been updated. Repeated
139 calls replace the existing hook registration.
141 Args:
142 optimizer: The optimizer instance to register the hook on.
144 Raises:
145 RuntimeError: If the optimizer does not support step post-hooks.
146 """
147 if not hasattr(optimizer, "register_step_post_hook"):
148 raise RuntimeError(
149 "Optimizer does not support register_step_post_hook. "
150 "Requires PyTorch 2.0+. Call on_step_end() manually instead."
151 )
152 self.remove()
153 self._hook_handle = optimizer.register_step_post_hook(
154 lambda *_: self.on_step_end(),
155 )
157 def remove(self) -> None:
158 """Remove the optimizer post-hook if registered."""
159 if self._hook_handle is not None:
160 self._hook_handle.remove()
161 self._hook_handle = None