clipped_swiglu
Applicable Products
Ascend 950PR&950DT products : Not supported
Atlas A3 products : Supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description:
The clipped Swish gated linear unit (ClippedSwiGLU) activation function. Compared with standard SwiGLU, this API adds parameters such as
group_index,alpha,limit,bias,interleaved, andclamp_mode. These parameters support the SwiGLU variant used by the GPT-OSS model, the grouped use case of MoE models, and the use case where some new models require moving the clamp operation to after the silu activation.Formula:
For a given input tensor
xwith dimensions[a, b, c, d, e, f, g, ...],clipped_swigluperforms the following computation:Merge the axes of
xbased on the input parameterdim. After merging, the dimensions are[pre, cut, after]. Thecutaxis is the axis to be split into two tensors after merging. The axis can be split in two modes: front-back split or odd-even split.preandaftercan be 1. For example, whendimis 3, the dimensions ofxafter merging are[a*b*c, d, e*f*g*...]. Since the elements of theafteraxis are stored contiguously and the computation is element-wise, thecutaxis and theafteraxis are merged, and the dimensions ofxbecome[pre, cut].Filter the
preaxis ofxbased on the input parametergroup_index:$$ sum = \text{Sum}(group\_index) $$$$ x = x[ : sum, : ] $$Here,
sumdenotes the sum of all elements ingroup_index. Ifgroup_indexis not provided, skip this step.Split
xbased on the input parameterinterleaved:If
interleaved=True(odd-even split):$$ A = x[ : , ::2], \quad B = x[ : , 1::2] $$If
interleaved=False(front-back split):$$ h = x.shape[1] // 2 $$$$ A = x[ : , : h], \quad B = x[ : , h : ] $$Perform Variant SwiGlu computation based on
alpha,limit,bias, andclamp_mode:When
clamp_mode=0(the clamp operation is performed before silu):$$ A = A.clamp(min=\text{None}, max=limit) $$$$ B = B.clamp(min=-limit, max=limit) $$$$ y\_glu = A \cdot sigmoid(\alpha \cdot A) $$$$ y = y\_glu \cdot (B + bias) $$When
clamp_mode=1(the clamp operation is performed after silu; requires underlying support for the V2 API):$$ y\_glu = A \cdot sigmoid(A) $$$$ y\_glu = y\_glu.clamp(min=\text{None}, max=limit) $$$$ B = B.clamp(min=-limit, max=limit) $$$$ y = y\_glu \cdot B $$The number of dimensions of the reshaped output tensor
yis the same as that ofxbefore axis merging. The size along thedimaxis is half of that ofx, and the other dimensions are the same as those ofx.
Prototype
cann_ops_nn.clipped_swiglu(
x,
*,
group_index=None,
dim=-1,
alpha=1.702,
limit=7.0,
bias=1.0,
interleaved=True,
clamp_mode=0,
) -> TensorParameters
| Name | Type | Type | Description | Data Type | Dimension (Shape) |
|---|---|---|---|---|---|
x | Tensor | Required | Input x in the formula. The size along the dim dimension must be even. | torch.float16, torch.bfloat16, torch.float32 | 1-8 dimensions |
group_index | Tensor | Optional | group_index in the formula. The i-th element indicates the number of batches of x to be processed by the i-th group. Passing None indicates no grouping. | torch.int64 | 1 dimension. Elements must be greater than or equal to 0. The number of supported groups is determined by the UB space size. |
dim | int | Optional | Dimension index for merging and splitting x. Value range: [-x.dim(), x.dim()-1]. Default Value: -1. | - | - |
alpha | float | Optional | Scaling parameter of the SwiGlu Variant. Recommended Value: 1.702. Default Value: 1.702. | - | - |
limit | float | Optional | Threshold of the SwiGlu Variant. The value must be greater than 0. Recommended Value: 7.0. Default Value: 7.0. | - | - |
bias | float | Optional | Bias parameter of the SwiGlu Variant. Recommended Value: 1.0. Default Value: 1.0. | - | - |
interleaved | bool | Optional | Method of splitting x. True indicates odd-even splitting, and False indicates front-back splitting. Default Value: True. | - | - |
clamp_mode | int | Optional | Order of the clamp operation and the silu operation. 0 indicates clamp before silu, and 1 indicates clamp after silu. Default Value: 0. | - | - |
Return Values
| Name | Type | Description | Data Type | Dimension (Shape) |
|---|---|---|---|---|
y | Tensor | ClippedSwiglu activation result. | Same as x | Same as x, but the dimension corresponding to dim is x.shape[dim] // 2 |
Constraints
- This API supports calls in single-operator mode and TorchAir graph mode.
xandgroup_indexmust both be NPU tensors; optional tensors can be passed asNone.clamp_modesupports only the values0or1; if theaclnnClippedSwigluV2kernel is not registered on the target chip,aclnnClippedSwigluis called, andclamp_mode=1is ignored and executed asclamp_mode=0.
Deterministic Computation
Defaults to a deterministic implementation.
Example
Single-operator mode call:
import torch import torch_npu import cann_ops_nn x = torch.randn(32, 128, dtype=torch.float16).npu() group_index = torch.randint(1, 10, (2, ), dtype=torch.int64).npu() y = cann_ops_nn.clipped_swiglu(x, group_index=group_index, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True, clamp_mode=1) print("y:============", y.shape, y.cpu())Call in graph mode (torchair):
import torch import torch_npu import torchair import cann_ops_nn npu_backend = "npu" class NetModel(torch.nn.Module): def __init__(self): super().__init__() def forward( self, x, group_index, dim, alpha, limit, bias, interleaved, clamp_mode ): return cann_ops_nn.clipped_swiglu( x, group_index=group_index, dim=dim, alpha=alpha, limit=limit, bias=bias, interleaved=interleaved, clamp_mode=clamp_mode ) def clipped_swiglu_test(): x = torch.randn(32, 128, dtype=torch.float16).npu() group_index = torch.randint(1, 10, (2, ), dtype=torch.int64).npu() model = NetModel() config = torchair.CompilerConfig() npu_backend = torchair.get_npu_backend(compiler_config=config) model = torch.compile(model, backend=npu_backend, dynamic=True, fullgraph=True) y = model(x, group_index=group_index, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True, clamp_mode=1) print("y:============", y.shape, y.cpu()) if __name__ == "__main__": clipped_swiglu_test()