situ_mx_quant

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: Fuses the Situ activation function with dynamic MX (Microscaling) quantization into one operator. The Situ activation is applied to the input x, and then the activation result is quantized with MX quantization to output the quantized result and scale. The bottom layer encapsulates aclnnSituMxQuant.

  • Formula:

    1. Situ activation:
    $$ situ_a = \beta \times \tanh(gate / \beta) \times sigmoid(gate) $$

    When linear_beta > 0:

    $$ up = linear\_beta \times \tanh(up / linear\_beta) $$
    $$ situOut = situ_a \times up $$

    When activate_left is true, gate takes the first half of x and up takes the second half; when activate_left is false, gate takes the second half of x and up takes the first half. 2. MX quantization (OCP algorithm):

    $$ shared\_exp = floor(log2(max(|situOut_i|))) - emax $$
    $$ y\_scale = 2^{shared\_exp} (E8M0) $$
    $$ y = cast\_to\_fp8(situOut / y\_scale) $$

Prototype

cann_ops_nn.situ_mx_quant(
    x,
    *,
    beta=1.0,
    linear_beta=0.0,
    activate_left=False,
    dst_type=36,
    round_mode="rint",
) -> (Tensor, Tensor)

Parameters

Parameter Type Optional/Required Description Data Type Dimension (shape)
x Tensor Required Input data, corresponding to x in the formula. Non-contiguous tensors are not supported. The supported data format is ND. float16, bfloat16 Dimensions 1-7, with the last dimension being 2H
beta float Optional beta parameter for Situ activation, corresponding to β in the formula. Default: 1.0. - -
linear_beta float Optional The linear_beta parameter of Situ activation, corresponding to linear_beta in the formula. Default: 0.0. - -
activate_left bool Optional Specifies whether gate takes the first half or the second half of x, corresponding to activate_left in the formula. Defaults to false. - -
dst_type int Optional Specifies the data type of output y, corresponding to the target type of cast_to_fp8 in the formula. Currently, only the input range {35, 36} is supported, which corresponds to the data type of output y as {35: FLOAT8_E5M2, 36: FLOAT8_E4M3FN}. Defaults to 36. INT -
round_mode str Optional Quantization rounding mode, which is the rounding mode of cast in the formula. Supported values: "rint", "round", "floor". Default: "rint". - -

Return Values

Output Name Output Type Optional/Required Description Data Type Dimension (shape)
y Tensor Required Quantization output, which is y in the corresponding formula. Non-contiguous tensors are not supported. Only the ND data format is supported. FLOAT8_E4M3FN, FLOAT8_E5M2 x.shape[:-1]+[H]
y_scale Tensor Required Scale of MX quantization (E8M0 format), corresponding to y_scale in the corresponding formula. Non-contiguous tensors are not supported. Only the ND data format is supported. FLOAT8_E8M0 x.shape[:-1]+[ceil(H/64), 2]

where H = x.shape[-1] / 2.

Constraints

  • x must be an NPU tensor.
  • The number of dimensions of x must be greater than or equal to 1, and the last dimension must be an even number.
  • The data type of x must be torch.float16 or torch.bfloat16.
  • beta must be greater than 0.
  • dst_type supports 36 (FLOAT8_E4M3FN) or 35 (FLOAT8_E5M2).
  • round_mode must be "rint".
  • axis is fixed to -1 (last dimension). Other axes are not currently supported.
  • Empty tensors and non-contiguous tensors are not supported.
  • The shape constraints of y_scale are as follows:
    • H = x.shape[-1] / 2
    • scaleNum = ceil(H / 64)
    • y_scale.shape = x.shape[:-1] + [scaleNum, 2]
  • This API supports both training and inference use cases.
  • This API can be called in single-operator mode and TorchAir graph mode.

Deterministic Computation

Defaults to a deterministic implementation.

Example

  • Single-operator mode call (eager)

    import torch
    import torch_npu
    import cann_ops_nn
    
    # FP16 -> FP8_E4M3FN
    x = torch.randn(16, 128, dtype=torch.float16).npu()
    y, y_scale = cann_ops_nn.situ_mx_quant(
        x, beta=1.0, dst_type=36, round_mode="rint",
    )
    print("y:============", y.shape, y.cpu())
    print("y_scale:============", y_scale.shape, y_scale.cpu().view(torch.uint8))
    
    # BF16 -> FP8_E5M2 + linear_beta
    x_bf16 = torch.randn(32, 256, dtype=torch.bfloat16).npu()
    y_bf16, y_scale_bf16 = cann_ops_nn.situ_mx_quant(
        x_bf16, beta=0.5, linear_beta=2.0, activate_left=False, dst_type=35, round_mode="rint",
    )
    print("y_bf16:============", y_bf16.shape, y_bf16.cpu())
  • Graph mode (torchair) call

    import torch
    import torch_npu
    import torchair
    import cann_ops_nn
    
    
    class NetModel(torch.nn.Module):
        def __init__(self):
            super().__init__()
    
        def forward(self, x):
            return cann_ops_nn.situ_mx_quant(
                x, beta=1.0, dst_type=36, round_mode="rint",
            )
    
    
    def situ_mx_quant_test():
        x = torch.randn(16, 128, dtype=torch.bfloat16).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, y_scale = model(x)
        print("y:============", y.shape, y.cpu())
        print("y_scale:============", y_scale.shape, y_scale.cpu().view(torch.uint8))
    
    
    if __name__ == "__main__":
        situ_mx_quant_test()