Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / mlp / swiglu_mlp.py: 78%

246 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"""SwiGLU MLP family with packed or separate logical projection layouts.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Mapping 

20from math import isfinite 

21from typing import Any 

22 

23# This package provides PyTorch-specific high-performance modules. 

24import torch 

25import torch.nn.functional as F 

26from torch import nn 

27 

28from hyper_parallel.components.checkpoint import ConcatenateWithSections 

29from hyper_parallel.components.checkpoint.weight_conversion import ( 

30 WeightConverter, 

31 WeightRenaming, 

32) 

33 

34 

35def _validate_mlp_config(config: Any) -> None: 

36 """Validate projection settings supplied by an arbitrary model config.""" 

37 for name in ("hidden_size", "intermediate_size"): 

38 value = getattr(config, name) 

39 if isinstance(value, bool) or not isinstance(value, int) or value <= 0: 

40 raise ValueError(f"{name} must be a positive integer") 

41 if not isinstance(config.bias, bool): 

42 raise TypeError("bias must be bool") 

43 limit = getattr(config, "swiglu_limit", 0.0) 

44 if isinstance(limit, bool) or not isinstance(limit, (int, float)) or not isfinite(limit): 

45 raise ValueError("swiglu_limit must be finite; nonpositive values disable clamping") 

46 

47 

48def swiglu_activation(gate: torch.Tensor, up: torch.Tensor, *, limit: float = 0.0, 

49 activation_dtype: str = "input") -> torch.Tensor: 

50 """Apply declared separate-projection activation math without changing its return dtype. 

51 

52 FP32 activation remains FP32 even when clamp is disabled. The projection 

53 owner decides when to cast back before its down projection. 

54 

55 Args: 

56 gate: Gate projection activations. 

57 up: Matching up-projection activations. 

58 limit: Positive clamp bound; nonpositive values disable clamping. 

59 activation_dtype: Compute in the input dtype or float32. 

60 """ 

61 if activation_dtype not in ("input", "float32"): 

62 raise ValueError("activation_dtype must be input or float32") 

63 if isinstance(limit, bool) or not isinstance(limit, (int, float)) or not isfinite(limit): 

64 raise ValueError("SwiGLU limit must be finite") 

65 if activation_dtype == "float32": 

66 gate, up = gate.float(), up.float() 

67 if limit > 0: 

68 gate, up = gate.clamp(max=limit), up.clamp(-limit, limit) 

69 return F.silu(gate) * up 

70 

71 

72def _resolve_activation_dtype(activation_dtype: str | None, limit: float) -> str: 

73 """Resolve the shared input/FP32 activation policy without changing projection dtype.""" 

74 if activation_dtype is None: 

75 activation_dtype = "float32" if limit > 0 else "input" 

76 if activation_dtype not in ("input", "float32"): 

77 raise ValueError("activation_dtype must be input or float32") 

78 return activation_dtype 

79 

80 

81def local_swiglu(x: torch.Tensor, *, limit: float = 0.0, activation_dtype: str | None = None) -> torch.Tensor: 

82 """Apply packed SwiGLU, retaining the historical FP32 clamp default. 

83 

84 Args: 

85 x: Packed gate/up activations ending in twice the intermediate width. 

86 limit: Positive clamp bound; nonpositive values disable clamping. 

87 activation_dtype: Explicit compute dtype policy or the clamp-dependent default. 

88 """ 

89 activation_dtype = _resolve_activation_dtype(activation_dtype, limit) 

90 if x.device.type == "npu" and limit <= 0 and activation_dtype == "input": 

91 # Optional NPU operators are required only by NPU execution. 

92 from hyper_parallel.components.functional import swiglu # pylint: disable=C0415 

93 return swiglu(x) 

94 gate, up = x.chunk(2, dim=-1) 

95 return swiglu_activation(gate, up, limit=limit, activation_dtype=activation_dtype).to(x.dtype) 

96 

97 

98def _activation_settings(source: Any, *, limit: float | None = None, 

99 activation_dtype: str | None = None) -> tuple[float, str]: 

100 """Resolve explicit source metadata without guessing custom forward behavior.""" 

101 config = getattr(source, "config", None) 

102 source_type = type(source) 

103 hf_source = source_type.__module__.startswith("transformers.models.") 

104 hf_clamped_source = (source_type.__module__.startswith("transformers.models.deepseek_v4.") 

105 and source_type.__name__ == "DeepseekV4MLP") 

106 literal_source_limit = limit is None and hf_clamped_source 

107 if limit is None: 

108 limit = source.limit if hf_clamped_source else getattr( 

109 source, "swiglu_limit", 0.0 if hf_source else getattr(config, "swiglu_limit", 0.0)) 

110 if isinstance(limit, bool) or not isinstance(limit, (int, float)) or not isfinite(limit): 

111 raise ValueError("swiglu_limit must be finite") 

112 if literal_source_limit and limit <= 0: 

113 raise ValueError("HF DeepseekV4 literal nonpositive clamp is not a disabled-clamp source contract") 

114 if activation_dtype is None: 

115 activation_dtype = getattr(source, "activation_dtype", 

116 None if hf_source else getattr(config, "activation_dtype", None)) 

117 if activation_dtype is None and hf_clamped_source: 

118 activation_dtype = "input" 

119 return limit, _resolve_activation_dtype(activation_dtype, limit) 

120 

121 

122class SwiGLUMLPModule(nn.Module): 

123 """Transformers-compatible SwiGLU MLP using one fused Gate/Up matmul.""" 

124 

125 @staticmethod 

126 

127 def _source_projections(module: nn.Module) -> tuple[nn.Linear, nn.Linear, nn.Linear]: 

128 """Validate and return the source Gate, Up, and Down projections.""" 

129 required = ("gate_proj", "up_proj", "down_proj") 

130 missing = [name for name in required if not hasattr(module, name)] 

131 if missing: 

132 raise TypeError(f"SwiGLUMLPModule source module is missing: {missing}") 

133 projections = (module.gate_proj, module.up_proj, module.down_proj) 

134 if not all(isinstance(projection, nn.Linear) for projection in projections): 

135 raise TypeError("SwiGLUMLPModule requires Gate, Up, and Down projections to be nn.Linear") 

136 return projections 

137 

138 @staticmethod 

139 

140 def _validate_projection_contract( 

141 gate_proj: nn.Linear, 

142 up_proj: nn.Linear, 

143 down_proj: nn.Linear, 

144 ) -> None: 

145 """Validate source projection shapes, placement, and training policy.""" 

146 if gate_proj.in_features != up_proj.in_features: 

147 raise ValueError("Gate and Up projections must have the same input size") 

148 if gate_proj.out_features != up_proj.out_features: 

149 raise ValueError("Gate and Up projections must have the same output size") 

150 if down_proj.in_features != gate_proj.out_features: 

151 raise ValueError("Down projection input size must equal the SwiGLU intermediate size") 

152 if down_proj.out_features != gate_proj.in_features: 

153 raise ValueError("Down projection output size must equal the MLP hidden size") 

154 if gate_proj.weight.device != up_proj.weight.device or gate_proj.weight.dtype != up_proj.weight.dtype: 

155 raise ValueError("Gate and Up projection weights must share device and dtype") 

156 if gate_proj.weight.device != down_proj.weight.device or gate_proj.weight.dtype != down_proj.weight.dtype: 

157 raise ValueError("Gate, Up, and Down projection weights must share device and dtype") 

158 if gate_proj.weight.requires_grad != up_proj.weight.requires_grad: 

159 raise ValueError("Gate and Up projection weights must share a training policy") 

160 if (gate_proj.bias is None) != (up_proj.bias is None): 

161 raise ValueError("Gate and Up projections must use the same bias policy") 

162 if gate_proj.bias is not None and gate_proj.bias.requires_grad != up_proj.bias.requires_grad: 

163 raise ValueError("Gate and Up projection biases must share a training policy") 

164 

165 def _initialize_fc1(self, gate_proj: nn.Linear, up_proj: nn.Linear) -> None: 

166 """Create the packed Gate/Up projection with source parameter values.""" 

167 pack = ConcatenateWithSections((self.intermediate_size, self.intermediate_size)) 

168 packed_weight = pack.convert( 

169 {"gate": gate_proj.weight.detach(), "up": up_proj.weight.detach()}, 

170 ["gate", "up"], 

171 ["linear_fc1.weight"], 

172 )["linear_fc1.weight"] 

173 self.linear_fc1 = nn.Linear( 

174 self.hidden_size, 

175 2 * self.intermediate_size, 

176 bias=gate_proj.bias is not None, 

177 device=gate_proj.weight.device, 

178 dtype=gate_proj.weight.dtype, 

179 ) 

180 self.linear_fc1.weight = nn.Parameter(packed_weight, requires_grad=gate_proj.weight.requires_grad) 

181 if gate_proj.bias is not None: 

182 packed_bias = pack.convert( 

183 {"gate": gate_proj.bias.detach(), "up": up_proj.bias.detach()}, 

184 ["gate", "up"], 

185 ["linear_fc1.bias"], 

186 )["linear_fc1.bias"] 

187 self.linear_fc1.bias = nn.Parameter(packed_bias, requires_grad=gate_proj.bias.requires_grad) 

188 

189 def _initialize_fc2(self, down_proj: nn.Linear) -> None: 

190 """Create the Down projection and reuse its source parameters.""" 

191 self.linear_fc2 = nn.Linear( 

192 down_proj.in_features, 

193 down_proj.out_features, 

194 bias=down_proj.bias is not None, 

195 device=down_proj.weight.device, 

196 dtype=down_proj.weight.dtype, 

197 ) 

198 self.linear_fc2.weight = down_proj.weight 

199 self.linear_fc2.bias = down_proj.bias 

200 

201 def __init__( 

202 self, 

203 *, 

204 module: nn.Module | None = None, 

205 module_fqn: str = "", 

206 context: Mapping[str, Any] | None = None, 

207 config: Any = None, 

208 activation_dtype: str | None = None, 

209 swiglu_limit: float | None = None, 

210 ) -> None: 

211 """Build the high-performance MLP from separate source projections. 

212 

213 Args: 

214 module: Source MLP exposing ``gate_proj``, ``up_proj``, and ``down_proj``. 

215 module_fqn: Fully qualified source-module name supplied by replacement. 

216 context: Replacement context supplied by Trainer. 

217 

218 Raises: 

219 TypeError: If the source projection modules are missing or unsupported. 

220 ValueError: If projection layouts, training policies, or activation differ. 

221 """ 

222 super().__init__() 

223 del module_fqn, context 

224 if (config is None) == (module is None): 

225 raise ValueError("provide exactly one of config or module") 

226 source = config if config is not None else module 

227 self.swiglu_limit, self.activation_dtype = _activation_settings( 

228 source, limit=swiglu_limit, activation_dtype=activation_dtype) 

229 if config is not None: 

230 _validate_mlp_config(config) 

231 self.config = config 

232 self.hidden_size = config.hidden_size 

233 self.intermediate_size = config.intermediate_size 

234 self.linear_fc1 = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=config.bias) 

235 self.linear_fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.bias) 

236 return 

237 if isinstance(module, SwiGLUMLPModule): 

238 self.config = module.config 

239 self.hidden_size, self.intermediate_size = module.hidden_size, module.intermediate_size 

240 self.linear_fc1, self.linear_fc2 = module.linear_fc1, module.linear_fc2 

241 self._identity_source = True 

242 self.train(module.training) 

243 return 

244 if all(isinstance(getattr(module, name, None), nn.Linear) for name in ("w1", "w2")): 

245 source_config = getattr(module, "config", None) 

246 if (not hasattr(module, "swiglu_limit") 

247 and getattr(source_config, "hidden_act", None) not in ("silu", "swiglu")): 

248 raise TypeError("packed w1/w2 source must explicitly declare SwiGLU activation semantics") 

249 if module.w1.out_features != 2 * module.w2.in_features or module.w2.out_features != module.w1.in_features: 

250 raise ValueError("packed SwiGLU source must contain [gate, up] rows followed by a down projection") 

251 if module.w1.weight.device != module.w2.weight.device or module.w1.weight.dtype != module.w2.weight.dtype: 

252 raise ValueError("packed SwiGLU projections must share device and dtype") 

253 self.config = getattr(module, "config", None) 

254 self.hidden_size, self.intermediate_size = module.w1.in_features, module.w2.in_features 

255 self.linear_fc1, self.linear_fc2 = module.w1, module.w2 

256 self._packed_source = True 

257 self.train(module.training) 

258 return 

259 gate_proj, up_proj, down_proj = self._source_projections(module) 

260 self._validate_projection_contract(gate_proj, up_proj, down_proj) 

261 

262 config = getattr(module, "config", None) 

263 hidden_act = getattr(config, "hidden_act", getattr(config, "hidden_activation", None)) 

264 if hidden_act is not None and hidden_act not in ("silu", "swiglu"): 

265 raise ValueError(f"SwiGLUMLPModule requires a SiLU activation, but got {hidden_act}") 

266 self.config = config 

267 self.hidden_size = gate_proj.in_features 

268 self.intermediate_size = gate_proj.out_features 

269 

270 self._initialize_fc1(gate_proj, up_proj) 

271 self._initialize_fc2(down_proj) 

272 self.train(module.training) 

273 

274 def make_transforms(self) -> list[WeightRenaming | WeightConverter]: 

275 """Describe reversible source-checkpoint to high-performance conversion.""" 

276 if getattr(self, "_identity_source", False): 

277 return [] 

278 if getattr(self, "_packed_source", False): 

279 return [WeightRenaming(f"{source}.{name}", f"{target}.{name}") 

280 for source, target in (("w1", "linear_fc1"), ("w2", "linear_fc2")) 

281 for name, _ in getattr(self, target).named_parameters()] 

282 transforms: list[WeightRenaming | WeightConverter] = [ 

283 WeightConverter( 

284 source_patterns=["gate_proj.weight", "up_proj.weight"], 

285 target_patterns="linear_fc1.weight", 

286 operations=[ 

287 ConcatenateWithSections((self.intermediate_size, self.intermediate_size)) 

288 ], 

289 ) 

290 ] 

291 if self.linear_fc1.bias is not None: 

292 transforms.append( 

293 WeightConverter( 

294 source_patterns=["gate_proj.bias", "up_proj.bias"], 

295 target_patterns="linear_fc1.bias", 

296 operations=[ 

297 ConcatenateWithSections((self.intermediate_size, self.intermediate_size)) 

298 ], 

299 ) 

300 ) 

301 transforms.append(WeightRenaming("down_proj.weight", "linear_fc2.weight")) 

302 if self.linear_fc2.bias is not None: 

303 transforms.append(WeightRenaming("down_proj.bias", "linear_fc2.bias")) 

304 return transforms 

305 

306 def forward(self, x: torch.Tensor | None = None, *, hidden_states: torch.Tensor | None = None) -> torch.Tensor: 

307 """Apply the fused Gate/Up projection, SwiGLU, and Down projection. 

308 

309 Args: 

310 x: Token activations, exclusive with hidden_states. 

311 hidden_states: Equivalent keyword spelling for token activations. 

312 """ 

313 if (x is None) == (hidden_states is None): 

314 raise ValueError("provide exactly one of x or hidden_states") 

315 x = hidden_states if x is None else x 

316 intermediate_parallel = self.linear_fc1(x) 

317 intermediate_parallel = local_swiglu(intermediate_parallel, limit=self.swiglu_limit, 

318 activation_dtype=self.activation_dtype) 

319 return self.linear_fc2(intermediate_parallel) 

320 

321 def reset_parameters(self) -> None: 

322 """Initialize owned projections after meta materialization.""" 

323 self.linear_fc1.reset_parameters() 

324 self.linear_fc2.reset_parameters() 

325 

326 

327class W1W2SwiGLUMLPModule(nn.Module): 

328 """Packed gate/up member preserving the vision source's w1/w2 state layout.""" 

329 

330 def __init__(self, *, config: Any = None, module: nn.Module | None = None, 

331 activation_dtype: str | None = None, swiglu_limit: float | None = None) -> None: 

332 """Construct vision projections or retain a declared packed source unchanged.""" 

333 super().__init__() 

334 if (config is None) == (module is None): 

335 raise ValueError("provide exactly one of config or module") 

336 self.swiglu_limit, self.activation_dtype = _activation_settings( 

337 config if config is not None else module, limit=swiglu_limit, activation_dtype=activation_dtype) 

338 if config is not None: 

339 _validate_mlp_config(config) 

340 self.w1 = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=config.bias) 

341 self.w2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.bias) 

342 else: 

343 if not all(isinstance(getattr(module, name, None), nn.Linear) for name in ("w1", "w2")): 

344 raise TypeError("w1_w2 source requires two Linear projections") 

345 if (module.w1.out_features != 2 * module.w2.in_features 

346 or module.w1.in_features != module.w2.out_features): 

347 raise ValueError("w1_w2 source must contain gate/up rows and a compatible down projection") 

348 if module.w1.weight.dtype != module.w2.weight.dtype or module.w1.weight.device != module.w2.weight.device: 

349 raise ValueError("w1/w2 must share dtype and device") 

350 self.w1, self.w2 = module.w1, module.w2 

351 self.train(module.training) 

352 

353 def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: 

354 """Apply the shared SwiGLU math without changing source checkpoint names. 

355 

356 Args: 

357 hidden_states: Token activations ending in the input hidden width. 

358 """ 

359 return self.w2(local_swiglu(self.w1(hidden_states), limit=self.swiglu_limit, 

360 activation_dtype=self.activation_dtype)) 

361 

362 def reset_parameters(self) -> None: 

363 """Initialize both projections after meta materialization.""" 

364 self.w1.reset_parameters() 

365 self.w2.reset_parameters() 

366 

367 def make_transforms(self) -> list[WeightRenaming | WeightConverter]: 

368 """Packed source and target share the same logical state names.""" 

369 return [] 

370 

371 

372class SeparateSwiGLUMLPModule(nn.Module): 

373 """SwiGLU retaining separate logical matrices and source parameter identities. 

374 

375 Separate projections preserve optimizer matrix boundaries, tied parameters, 

376 checkpoint keys and independently frozen projection parameters. 

377 """ 

378 

379 def __init__( 

380 self, *, module: nn.Module | None = None, config: Any = None, 

381 module_fqn: str = "", context: Mapping[str, Any] | None = None, 

382 activation_dtype: str | None = None, swiglu_limit: float | None = None, 

383 ) -> None: 

384 """Build from complete config or validated separate source projections.""" 

385 super().__init__() 

386 del module_fqn, context 

387 if (module is None) == (config is None): 

388 raise ValueError("provide exactly one of config or module") 

389 source = module if module is not None else config 

390 self.swiglu_limit, self.activation_dtype = _activation_settings( 

391 source, limit=swiglu_limit, activation_dtype=activation_dtype) 

392 self.config = config if module is None else getattr(module, "config", None) 

393 activation = getattr(self.config, "hidden_act", getattr(self.config, "hidden_activation", None)) 

394 if activation is not None and activation not in ("silu", "swiglu"): 

395 raise ValueError(f"SwiGLU requires a SiLU activation, but got {activation}") 

396 if module is None: 

397 _validate_mlp_config(config) 

398 self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.bias) 

399 self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.bias) 

400 self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.bias) 

401 else: 

402 gate, up, down = SwiGLUMLPModule._source_projections(module) 

403 # Independent projection freezing is valid without a packed Parameter. 

404 if ((gate.in_features, gate.out_features, down.in_features, down.out_features) 

405 != (up.in_features, up.out_features, gate.out_features, gate.in_features)): 

406 raise ValueError("SwiGLU projection shapes must describe one hidden/intermediate pair") 

407 if len({(item.weight.device, item.weight.dtype) for item in (gate, up, down)}) != 1: 

408 raise ValueError("SwiGLU projections must share device and dtype") 

409 self.gate_proj, self.up_proj, self.down_proj = gate, up, down 

410 if isinstance(getattr(module, "act_fn", None), nn.Module): 

411 activation_type = type(module.act_fn) 

412 hf_silu = (activation_type.__module__ == "transformers.activations" 

413 and activation_type.__name__ == "SiLUActivation") 

414 if not isinstance(module.act_fn, nn.SiLU) and not hf_silu: 

415 raise ValueError("Registered SwiGLU activation must be a supported SiLU module") 

416 self.act_fn = nn.SiLU() 

417 self.act_fn.training = module.act_fn.training 

418 self.training = module.training 

419 

420 def forward(self, hidden_states: torch.Tensor | None = None, *, x: torch.Tensor | None = None) -> torch.Tensor: 

421 """Evaluate SwiGLU; ``x`` preserves HF MLP keyword calls.""" 

422 if (hidden_states is None) == (x is None): 

423 raise ValueError("provide exactly one of hidden_states or x") 

424 hidden_states = x if hidden_states is None else hidden_states 

425 gate, up = self.gate_proj(hidden_states), self.up_proj(hidden_states) 

426 if hasattr(self, "act_fn") and self.swiglu_limit <= 0 and self.activation_dtype == "input": 

427 hidden = self.act_fn(gate) * up 

428 else: 

429 hidden = swiglu_activation(gate, up, limit=self.swiglu_limit, activation_dtype=self.activation_dtype) 

430 return self.down_proj(hidden.to(hidden_states.dtype)) 

431 

432 def reset_parameters(self) -> None: 

433 """Initialize the three projections after meta materialization.""" 

434 for projection in (self.gate_proj, self.up_proj, self.down_proj): 

435 projection.reset_parameters() 

436 

437 def make_transforms(self) -> list[WeightRenaming | WeightConverter]: 

438 """Source checkpoint names and shapes already match this member.""" 

439 return [] 

440 

441 

442def parameter_sharding_rules() -> list[tuple[str, Any]]: 

443 """Declare packed projection roles next to the family owning those names.""" 

444 # The planner imports family discovery; resolve its role type after discovery completes. 

445 from hyper_parallel.distributed.tensor_parallel.param_role import ParamRole # pylint: disable=C0415 

446 return [("linear_fc1.weight", ParamRole.FUSED_GATE_UP), ("linear_fc2.weight", ParamRole.ROWWISE)] 

447__all__ = [ 

448 "SwiGLUMLPModule", 

449 "W1W2SwiGLUMLPModule", 

450 "SeparateSwiGLUMLPModule", 

451 "local_swiglu", 

452 "swiglu_activation", 

453]