Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / swiglu.py: 83%

46 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"""Packed and DeepSeek FP32 clamped SwiGLU implementations.""" 

16 

17from typing import Protocol 

18 

19import torch 

20from torch.nn import functional as F 

21 

22from ..registry import OpRegistry 

23from ..spec import OpSpec 

24from .._dependency import require_package, require_symbol 

25 

26 

27class SwiGLUFn(Protocol): 

28 """Apply SiLU(gate) * up to packed Gate/Up projections.""" 

29 

30 def __call__(self, x: torch.Tensor, dim: int = -1) -> torch.Tensor: 

31 """Split the packed projection evenly along the given dimension.""" 

32 

33 

34class ClampedSwiGLUFn(Protocol): 

35 """Compute a FP32 activation from separate, optionally clamped projections.""" 

36 

37 def __call__(self, x: torch.Tensor, up: torch.Tensor, limit: float) -> torch.Tensor: 

38 """Clamp the projections for positive limits and return the FP32 result.""" 

39 

40 

41SWIGLU = OpSpec[SwiGLUFn](config_key="swiglu") 

42SWIGLU_CLAMPED = OpSpec[ClampedSwiGLUFn](config_key="swiglu", variant="clamped_fp32") 

43 

44 

45def _native(x: torch.Tensor, dim: int = -1) -> torch.Tensor: 

46 if x.shape[dim] % 2: 

47 raise ValueError("SwiGLU requires an evenly packed Gate/Up dimension") 

48 gate, up = x.chunk(2, dim=dim) 

49 return F.silu(gate) * up 

50 

51 

52def _clamp(x: torch.Tensor, up: torch.Tensor, limit: float) -> tuple[torch.Tensor, torch.Tensor]: 

53 gate, up = x.float(), up.float() 

54 if limit > 0: 

55 gate = gate.clamp(max=limit) 

56 up = up.clamp(min=-limit, max=limit) 

57 return gate, up 

58 

59 

60def _native_clamped(x: torch.Tensor, up: torch.Tensor, limit: float) -> torch.Tensor: 

61 gate, up = _clamp(x, up, limit) 

62 return F.silu(gate) * up 

63 

64 

65def _load_native() -> SwiGLUFn: 

66 return _native 

67 

68 

69def _load_native_clamped() -> ClampedSwiGLUFn: 

70 return _native_clamped 

71 

72 

73def _load_npu() -> SwiGLUFn: 

74 require_symbol(require_package("torch_npu"), "npu_swiglu") 

75 # The existing implementation imports the optional NPU package. 

76 from hyper_parallel.components.functional.swiglu import swiglu # pylint: disable=import-outside-toplevel 

77 return swiglu 

78 

79 

80def _load_npu_clamped() -> ClampedSwiGLUFn: 

81 kernel = _load_npu() 

82 

83 def swiglu_clamped(x: torch.Tensor, up: torch.Tensor, limit: float) -> torch.Tensor: 

84 """Clamp separate projections in FP32 and apply the packed activation kernel.""" 

85 gate, up = _clamp(x, up, limit) 

86 return kernel(torch.cat((gate, up), dim=-1), dim=-1) 

87 

88 return swiglu_clamped 

89 

90 

91def register_swiglu(registry: OpRegistry) -> None: 

92 """Register packed and clamped SwiGLU under the same selection key.""" 

93 registry.register_family("swiglu", specs=(SWIGLU, SWIGLU_CLAMPED)) 

94 registry.register_impl(SWIGLU, name="native", devices=("cuda", "cpu", "npu"), load=_load_native) 

95 registry.register_impl(SWIGLU, name="torch_npu", devices=("npu",), load=_load_npu) 

96 registry.register_impl( 

97 SWIGLU_CLAMPED, name="native", devices=("cuda", "cpu", "npu"), load=_load_native_clamped, 

98 ) 

99 registry.register_impl(SWIGLU_CLAMPED, name="torch_npu", devices=("npu",), load=_load_npu_clamped)