Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / moe / shared_expert.py: 88%
231 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"""MoE shared expert module."""
17from __future__ import annotations
19from collections.abc import Mapping
20from functools import partial
21from math import isfinite, sqrt
22from typing import Any, Literal, Optional
24import torch
25from torch import nn
26from transformers.activations import ACT2FN
27from hyper_parallel.components.checkpoint.weight_conversion import (
28 WeightConverter,
29 WeightRenaming,
30)
32from hyper_parallel.components.checkpoint import ConcatenateWithSections
33from hyper_parallel.models.replacement import module_replacement
34from hyper_parallel.components.modules.mlp.swiglu_mlp import (
35 SwiGLUMLPModule, _validate_mlp_config, local_swiglu, _activation_settings,
36)
37from hyper_parallel.components.modules.module_family import ModuleFamily, build_family, register_module_family
40class LinearWithMatmul(nn.Linear):
41 """Aligned with ColumnParallelLinear (single device, no parallelism).
43 name: ColumnParallelLinear
44 forward path: LinearWithGradAccumulationAndAsyncCommunication.forward
45 → output = torch.matmul(input, weight.t())
46 → output = output + bias (bias explicitly added separately, not addmm fused)
48 Used for: linear_fc1, linear_fc2
50 skip_bias_add=True: don't add bias, return (output, bias) for external addition.
51 skip_bias_add=False: bias explicitly added in forward, return (output, None).
53 NPU bf16 note: matmul runs in @custom_fwd autograd Function context,
54 NPU automatically selects the same kernel for non-contiguous weight.t() as weight.t().contiguous().
55 calling directly in forward does not trigger this behavior, so explicit .contiguous() is needed.
56 """
58 def __init__(
59 self,
60 in_features: int,
61 out_features: int,
62 bias: bool = True,
63 skip_bias_add: bool = True,
64 device: torch.device | str | None = None,
65 dtype: torch.dtype | None = None,
66 ) -> None:
67 """Initialize the linear parameters and bias-return behavior."""
68 super().__init__(in_features, out_features, bias=bias, device=device, dtype=dtype)
69 self.skip_bias_add = skip_bias_add
71 def forward( # pylint: disable=redefined-builtin
72 self, input: torch.Tensor
73 ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
74 """Apply matmul and optionally return bias for external addition.
76 Args:
77 input: Activations ending in in_features.
78 """
79 output = torch.matmul(input, self.weight.t().contiguous())
80 if self.skip_bias_add:
81 return output, self.bias
82 if self.bias is not None:
83 output = output + self.bias
84 return output, None
87class SharedExpertModule(nn.Module):
88 """Transformers-compatible parameter-owning MoE shared expert.
90 Args:
91 module: Source Transformers shared-expert module.
92 module_fqn: Fully qualified name supplied by the replacement framework.
93 context: Additional replacement context.
94 """
96 @staticmethod
97 def _separate_projections(module: nn.Module) -> tuple[nn.Linear, nn.Linear, nn.Linear]:
98 """Validate and return separate source projections."""
99 source_linears = (module.gate_proj, module.up_proj, module.down_proj)
100 if any(not isinstance(layer, nn.Linear) for layer in source_linears):
101 raise TypeError("SharedExpertModule source projections must be nn.Linear instances")
102 gate_proj, up_proj, down_proj = source_linears
103 SwiGLUMLPModule._validate_projection_contract(gate_proj, up_proj, down_proj) # pylint: disable=protected-access
104 if gate_proj.in_features != up_proj.in_features:
105 raise ValueError("SharedExpertModule gate and up projections must have the same input size")
106 if gate_proj.out_features != up_proj.out_features:
107 raise ValueError("SharedExpertModule gate and up projections must have the same output size")
108 if down_proj.in_features != gate_proj.out_features:
109 raise ValueError("SharedExpertModule down projection input size is incompatible with gate/up")
110 if down_proj.out_features != gate_proj.in_features:
111 raise ValueError("SharedExpertModule down projection output size is incompatible with gate/up")
112 if gate_proj.weight.requires_grad != up_proj.weight.requires_grad:
113 raise ValueError("SharedExpertModule gate and up weights must use the same training policy")
114 if (gate_proj.bias is None) != (up_proj.bias is None):
115 raise ValueError("SharedExpertModule gate and up projections must use the same bias policy")
116 if gate_proj.bias is not None and gate_proj.bias.requires_grad != up_proj.bias.requires_grad:
117 raise ValueError("SharedExpertModule gate and up biases must use the same training policy")
118 return gate_proj, up_proj, down_proj
120 def _initialize_fused_source(self, module: nn.Module) -> None:
121 """Reuse an already fused source module without converting parameters."""
122 self.linear_fc1 = module.linear_fc1
123 self.linear_fc2 = module.linear_fc2
124 if not all(hasattr(layer, "skip_bias_add") for layer in (self.linear_fc1, self.linear_fc2)):
125 raise TypeError("fused SharedExpertModule projections must return output and bias separately")
126 if not hasattr(module, "activation_func"):
127 raise TypeError("fused SharedExpertModule source module is missing activation_func")
128 self.activation_func = module.activation_func
129 self._return_bias_tuple = getattr(module, "_return_bias_tuple", True)
130 self._gate_size = 0
131 self._up_size = 0
132 self.train(module.training)
134 def _initialize_separate_linears(
135 self,
136 gate_proj: nn.Linear,
137 up_proj: nn.Linear,
138 down_proj: nn.Linear,
139 ) -> None:
140 """Construct fused linear layers from separate source projections."""
141 self._gate_size = gate_proj.out_features
142 self._up_size = up_proj.out_features
143 self.linear_fc1 = LinearWithMatmul(
144 gate_proj.in_features,
145 self._gate_size + self._up_size,
146 bias=gate_proj.bias is not None,
147 device=gate_proj.weight.device,
148 dtype=gate_proj.weight.dtype,
149 )
150 self.linear_fc1.weight.requires_grad_(gate_proj.weight.requires_grad)
151 if gate_proj.bias is not None:
152 self.linear_fc1.bias.requires_grad_(gate_proj.bias.requires_grad)
153 self.linear_fc2 = LinearWithMatmul(
154 down_proj.in_features,
155 down_proj.out_features,
156 bias=down_proj.bias is not None,
157 device=down_proj.weight.device,
158 dtype=down_proj.weight.dtype,
159 )
160 self.linear_fc2.weight.requires_grad_(down_proj.weight.requires_grad)
161 if down_proj.bias is not None:
162 self.linear_fc2.bias.requires_grad_(down_proj.bias.requires_grad)
163 self.linear_fc1.weight = nn.Parameter(
164 torch.cat((gate_proj.weight.detach(), up_proj.weight.detach())),
165 requires_grad=gate_proj.weight.requires_grad,
166 )
167 if gate_proj.bias is not None:
168 self.linear_fc1.bias = nn.Parameter(
169 torch.cat((gate_proj.bias.detach(), up_proj.bias.detach())),
170 requires_grad=gate_proj.bias.requires_grad,
171 )
172 self.linear_fc2.weight = down_proj.weight
173 self.linear_fc2.bias = down_proj.bias
175 def _initialize_activation(self, module: nn.Module, config: Any) -> None:
176 """Select the source-compatible gated activation implementation."""
177 hidden_act = getattr(config, "hidden_act", None)
178 if hidden_act is None:
179 hidden_act = getattr(config, "hidden_activation", None)
180 if hidden_act is None:
181 hidden_act = getattr(config, "mlp_hidden_act", None)
182 activation_func = getattr(module, "act_fn", None)
183 if activation_func is None:
184 if hidden_act is None:
185 hidden_act = "silu"
186 activation_func = ACT2FN[hidden_act]
187 if hidden_act == "silu" and bool(getattr(config, "use_fused_swiglu", True)):
188 self.activation_func = local_swiglu
189 return
191 def glu(x: torch.Tensor) -> torch.Tensor:
192 """Apply the configured gated linear unit.
194 Args:
195 x: Concatenated gate/up activations.
196 """
197 gate, value = torch.chunk(x, 2, dim=-1)
198 return activation_func(gate) * value
200 self.activation_func = glu
202 def __init__(
203 self,
204 *,
205 module: nn.Module | None = None,
206 module_fqn: str = "",
207 context: Mapping[str, Any] | None = None,
208 config: Any = None,
209 activation_dtype: str | None = None,
210 swiglu_limit: float | None = None,
211 preserve_source_layout: bool = False,
212 ) -> None:
213 """Build the high-performance module from a Transformers shared expert."""
214 super().__init__()
215 if (config is None) == (module is None):
216 raise ValueError("provide exactly one of config or module")
217 self._ep_context = None
218 del module_fqn
219 source_config = config if config is not None else getattr(module, "config", None)
220 self.num_layers = (context or {}).get("num_layers", getattr(
221 source_config, "num_layers", getattr(source_config, "num_hidden_layers", None)))
222 self.init_method_std = getattr(source_config, "init_method_std", 0.02)
223 if not isinstance(preserve_source_layout, bool):
224 raise TypeError("preserve_source_layout must be bool")
225 self._preserve_source_layout = preserve_source_layout
226 self.swiglu_limit, self.activation_dtype = _activation_settings(
227 config if config is not None else module, limit=swiglu_limit, activation_dtype=activation_dtype)
228 self.limit = self.swiglu_limit
229 if config is not None:
230 self._initialize_from_config(config)
231 self.reset_parameters()
232 return
233 config = getattr(module, "config", None)
234 self.config = config
235 self._source_is_fused = all(
236 hasattr(module, name) for name in ("linear_fc1", "linear_fc2")
237 )
238 self._source_is_separate = all(
239 hasattr(module, name) for name in ("gate_proj", "up_proj", "down_proj")
240 )
241 if not self._source_is_fused and not self._source_is_separate:
242 raise TypeError(
243 "SharedExpertModule requires linear_fc1/linear_fc2 or gate_proj/up_proj/down_proj"
244 )
246 if self._source_is_fused:
247 if self._preserve_source_layout:
248 raise ValueError("preserve_source_layout requires separate gate/up/down source projections")
249 self._initialize_fused_source(module)
250 return
252 gate_proj, up_proj, down_proj = self._separate_projections(module)
253 if self._preserve_source_layout:
254 self.gate_proj, self.up_proj, self.down_proj = gate_proj, up_proj, down_proj
255 if isinstance(getattr(module, "act_fn", None), nn.Module):
256 self.act_fn = module.act_fn
257 self._initialize_activation(module, config)
258 self._set_clamped_activation(config)
259 self._return_bias_tuple = False
260 self.train(module.training)
261 return
262 self._initialize_separate_linears(gate_proj, up_proj, down_proj)
263 self._initialize_activation(module, config)
264 self._set_clamped_activation(config)
265 self._return_bias_tuple = False
266 self.train(module.training)
268 def _initialize_from_config(self, config: Any) -> None:
269 """Create the separate gate, up and down projections for a new shared expert."""
270 _validate_mlp_config(config)
271 if not isinstance(config.return_bias_tuple, bool):
272 raise TypeError("return_bias_tuple must be bool")
273 self.config = config
274 self._gate_size = self._up_size = config.intermediate_size
275 self._source_is_fused = False
276 self._source_is_separate = True
277 self._return_bias_tuple = config.return_bias_tuple
278 self.activation_func = partial(local_swiglu, limit=self.swiglu_limit,
279 activation_dtype=self.activation_dtype)
280 if self._preserve_source_layout:
281 if config.return_bias_tuple:
282 raise ValueError("separate SharedExpert returns a tensor, not a bias tuple")
283 self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.bias)
284 self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.bias)
285 self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.bias)
286 return
287 self.linear_fc1 = LinearWithMatmul(config.hidden_size, 2 * config.intermediate_size, bias=config.bias)
288 self.linear_fc2 = LinearWithMatmul(config.intermediate_size, config.hidden_size, bias=config.bias)
289 return
291 def _set_clamped_activation(self, config: Any) -> None:
292 if self.swiglu_limit > 0 or self.activation_dtype == "float32":
293 hidden_act = getattr(config, "hidden_act", getattr(config, "hidden_activation", None))
294 if hidden_act not in (None, "silu", "swiglu"):
295 raise ValueError("clamped/FP32 SharedExpert requires SwiGLU activation")
296 self.activation_func = partial(local_swiglu, limit=self.swiglu_limit,
297 activation_dtype=self.activation_dtype)
299 def make_transforms(self) -> list[WeightRenaming | WeightConverter]:
300 """Describe reversible source-checkpoint to high-performance conversion."""
301 if self._source_is_fused or self._preserve_source_layout:
302 return []
303 transforms: list[WeightRenaming | WeightConverter] = [
304 WeightConverter(
305 source_patterns=["gate_proj.weight", "up_proj.weight"],
306 target_patterns="linear_fc1.weight",
307 operations=[
308 ConcatenateWithSections(
309 (self._gate_size, self._up_size),
310 dim=0,
311 )
312 ],
313 ),
314 WeightRenaming(
315 source_patterns="down_proj.weight",
316 target_patterns="linear_fc2.weight",
317 ),
318 ]
319 if self.linear_fc1.bias is not None:
320 transforms.insert(
321 1,
322 WeightConverter(
323 source_patterns=["gate_proj.bias", "up_proj.bias"],
324 target_patterns="linear_fc1.bias",
325 operations=[
326 ConcatenateWithSections(
327 (self._gate_size, self._up_size),
328 dim=0,
329 )
330 ],
331 ),
332 )
333 if self.linear_fc2.bias is not None:
334 transforms.append(
335 WeightRenaming(
336 source_patterns="down_proj.bias",
337 target_patterns="linear_fc2.bias",
338 )
339 )
340 return transforms
342 split_forward_supported = True
344 def bind_ep_context(self, context: Any) -> None:
345 """Borrow the transport owner without registering another module or parameter tree.
347 Args:
348 context: EP context scheduling this shared expert's FC1 and FC2.
349 """
350 if self._ep_context is not None and self._ep_context is not context:
351 raise ValueError("shared expert already has an EP communication owner")
352 self._ep_context = context
354 def __call__(self, *args: Any, **kwargs: Any) -> Any:
355 """Consume an overlapped result before repeating module/FSDP hooks.
357 The two scheduled stages use normal module calls. The later model call
358 only consumes their result, so it must not gather the same weights again.
359 """
360 if self._ep_context is not None and kwargs.get("stage", "full") == "full":
361 hidden = args[0] if args else kwargs.get("hidden_states", kwargs.get("x"))
362 output = self._ep_context.take_shared_output(hidden)
363 if output is not None:
364 return output
365 return super().__call__(*args, **kwargs)
367 def forward_fc1(self, hidden_states: torch.Tensor) -> torch.Tensor:
368 """Apply the first projection and activation during dispatch.
370 Args:
371 hidden_states: Original shared-branch tokens [..., hidden_size].
373 Returns:
374 Activated intermediate [..., intermediate_size], retaining source dtype policy.
375 """
376 if self._preserve_source_layout:
377 if self.swiglu_limit <= 0 and self.activation_dtype == "input" and hasattr(self, "act_fn"):
378 return self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)
379 intermediate = torch.cat((self.gate_proj(hidden_states), self.up_proj(hidden_states)), dim=-1)
380 return self.activation_func(intermediate).to(hidden_states.dtype)
381 intermediate, bias = self.linear_fc1(hidden_states)
382 if bias is not None:
383 intermediate = intermediate + bias
384 return self.activation_func(intermediate)
386 def forward_fc2(self, intermediate: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, Optional[torch.Tensor]]:
387 """Apply the second projection during combine, preserving the output-bias protocol.
389 Args:
390 intermediate: This invocation's activated FC1 output [..., intermediate_size].
392 Returns:
393 Shared output [..., hidden_size], or the source's (output, output_bias) pair.
394 """
395 if self._preserve_source_layout:
396 return self.down_proj(intermediate)
397 output, output_bias = self.linear_fc2(intermediate)
398 if not self._return_bias_tuple:
399 if output_bias is not None:
400 output = output + output_bias
401 return output
402 return output, output_bias
404 def forward(
405 self,
406 hidden_states: torch.Tensor | None = None,
407 *,
408 x: torch.Tensor | None = None,
409 stage: Literal["full", "fc1", "fc2"] = "full",
410 ) -> torch.Tensor | tuple[torch.Tensor, Optional[torch.Tensor]]:
411 """Apply the shared-expert MLP while preserving the source return contract.
413 Args:
414 hidden_states: Source token activations; mutually exclusive with x.
415 x: Compatibility alias for hidden_states.
416 stage: Full MLP, FC1 plus activation, or FC2 using an already activated intermediate.
417 Staged callers use module(..., stage=...) so module/FSDP hooks still run.
418 """
419 if (hidden_states is None) == (x is None):
420 raise ValueError("provide exactly one of hidden_states or x")
421 hidden_states = x if hidden_states is None else hidden_states
422 if stage == "fc1":
423 return self.forward_fc1(hidden_states)
424 if stage == "fc2":
425 return self.forward_fc2(hidden_states)
426 if stage != "full":
427 raise ValueError("shared expert stage must be full, fc1 or fc2")
428 return self.forward_fc2(self.forward_fc1(hidden_states))
430 def reset_parameters(self) -> None:
431 """Use Megatron's normal FC1 and depth-scaled output-layer initialization."""
432 if isinstance(self.num_layers, bool) or not isinstance(self.num_layers, int) or self.num_layers < 1:
433 raise ValueError("shared expert initialization requires num_layers in config or replacement context")
434 if (isinstance(self.init_method_std, bool) or not isinstance(self.init_method_std, (int, float))
435 or not isfinite(self.init_method_std) or self.init_method_std < 0):
436 raise ValueError("init_method_std must be finite and nonnegative")
437 output_std = self.init_method_std / sqrt(2.0 * self.num_layers)
438 if self._preserve_source_layout:
439 projections = ((self.gate_proj, self.init_method_std), (self.up_proj, self.init_method_std),
440 (self.down_proj, output_std))
441 else:
442 projections = ((self.linear_fc1, self.init_method_std), (self.linear_fc2, output_std))
443 for projection, std in projections:
444 nn.init.normal_(projection.weight, mean=0.0, std=std)
445 if projection.bias is not None:
446 nn.init.zeros_(projection.bias)
449@module_replacement
450def SharedExpert( # pylint: disable=invalid-name
451 *, config: Any = None, module: nn.Module | None = None,
452 module_fqn: str = "", context: Mapping[str, Any] | None = None, mesh: Any = None,
453 activation_dtype: str | None = None, swiglu_limit: float | None = None,
454 preserve_source_layout: bool = False,
455) -> nn.Module:
456 """Construct a tracked shared expert preserving its source return protocol."""
457 return build_family(SharedExpert, config=config, module=module, module_fqn=module_fqn,
458 context=context, mesh=mesh, activation_dtype=activation_dtype,
459 swiglu_limit=swiglu_limit, preserve_source_layout=preserve_source_layout)
462register_module_family(ModuleFamily(
463 name="shared_expert", baseline=SharedExpert,
464 variants={"local": "hyper_parallel.components.modules.moe.shared_expert.SharedExpertModule"},
465 default_variant="local",
466))