dequant_situ_quant

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: Performs fused computation of dequantization (Dequant), Situ activation, and quantization (Quant) on input x. The underlying implementation calls aclnnDequantSituQuant.

  • Formula:

    1. The dequantization path varies depending on the data type of input x:
    • INT8 path:

      $$ dequantOut_i = cast\_to\_float(x_i) \times weight\_scale_i + bias_i $$
    • INT32 path:

      $$ dequantOut_i = cast\_to\_float(x_i) \times weight\_scale_i \times activation\_scale_i + bias_i $$
    • BFLOAT16/FLOAT16 path (pre-dequantization):

      $$ dequantOut_i = cast\_to\_float(x_i) $$
    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 dequantOut and up takes the second half. When activate_left is false, gate takes the second half of dequantOut and up takes the first half. 3. Quantization:

    • static mode:

      $$ y_i = trunc(situOut_i / quant\_scale_i + quant\_offset_i) $$
    • dynamic mode:

      $$ scale_i = absmax(situOut_i) / 127 $$
      $$ y_i = trunc(situOut_i / scale_i) $$

Prototype

cann_ops_nn.dequant_situ_quant(
    x,
    *,
    weight_scale=None,
    activation_scale=None,
    bias=None,
    quant_scale=None,
    quant_offset=None,
    group_index=None,
    beta=4.0,
    linear_beta=25.0,
    activate_left=True,
    quant_type="dynamic",
) -> (Tensor, Tensor)

Parameters

Parameter Type Required/Optional Description Data Type Shape
x Tensor Required Input data, corresponding to x in the formula. Non-contiguous tensors are not supported. The supported data format is ND. int8, int32, bfloat16, float16 INT8: 2-8 dimensions; others: 2 dimensions, with the last dimension being 2H
weight_scale Tensor Optional Dequantization weight scale, corresponding to weight_scale in the formula. Non-contiguous is not supported. ND is the only supported data format. float32 1D with shape (2H,) or (1,)
activation_scale Tensor Optional Dequantization activation scale, corresponding to activation_scale in the formula. Non-contiguous is not supported. ND is the only supported data format. float32 1D, shape (1,)
bias Tensor Optional Dequantization bias, corresponding to bias in the formula. Non-contiguous tensors are not supported. Supports ND data format. float32 1D, shape (2H,) or (1,)
quant_scale Tensor Optional Quantization scale, corresponding to quant_scale in the formula. Non-contiguous tensors are not supported. The supported data format is ND. float32 1 dimension, with shape (H,) or (1,)
quant_offset Tensor Optional Quantization offset, corresponding to quant_offset in the formula. Non-contiguous tensors are not supported. The supported data format is ND. float32 1 dimension, with shape (H,) or (1,)
group_index Tensor Optional MoE group index. Non-contiguous tensors are not supported. ND data format is supported. int64 1 dimension, shape (K,)
beta float Optional Beta parameter of Situ activation, corresponding to β in the formula. Defaults to 4.0. - -
linear_beta float Optional linear_beta parameter of the Situ activation, corresponding to linear_beta in the formula. Defaults to 25.0. - -
activate_left bool Optional Specifies whether gate takes the first half or the second half of dequantOut, corresponding to activate_left in the formula. Defaults to true. - -
quant_type str Optional Quantization mode, corresponding to the static/dynamic mode in the formula. Supported values: "static" and "dynamic". Defaults to "dynamic". - -

Return Values

Output Name Output Type Required/Optional Description Data Type Shape
y Tensor Required Quantization output, corresponding to y in the formula. Non-contiguous tensors are not supported. Only the ND data format is supported. int8 INT8: x.shape[:-1]+[H]; others: [M, H]
y_scale Tensor Required Dynamic quantization scale, i.e., the scale in the corresponding formula (meaningful only in dynamic mode). Non-contiguous tensors are not supported. The supported data format is ND. float32 INT8: x.shape[:-1]; others: [M]

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

Constraints

  • x and the optional tensors must all be NPU tensors; None can be passed for an optional tensor.

  • The last dimension of x must be an even number. If the data type of x is INT8, the number of dimensions must be ≥ 2; if the data type of x is INT32/BF16/FLOAT16, the number of dimensions must be 2.

  • beta cannot be 0.

  • quant_scale is required when quant_type is "static".

  • Empty tensors are supported (an empty output is returned directly when x.size(0) == 0).

  • The constraints on quant_type are as follows:

    quant_typeMeaningquant_scalequant_offset
    "static"Static quantizationRequiredOptional
    "dynamic"Dynamic quantizationOptional (used as smoothScale)Not effective
  • The input constraints for each data type are as follows:

    x Data TypeRequired inputOptional inputProhibited Input
    INT8x, weight_scalebias, quant_scale, quant_offsetactivation_scale, group_index
    INT32x, weight_scale, activation_scalebias, group_indexquant_scale, quant_offset
    BF16x—weight_scale, activation_scale, bias, quant_scale, quant_offset, group_index
    FLOAT16x—weight_scale, activation_scale, bias, quant_scale, quant_offset, group_index
  • 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
    
    # INT8, dynamic quantization
    x = torch.randint(-127, 127, (16, 64), dtype=torch.int8).npu()
    weight_scale = torch.full((64,), 0.1, dtype=torch.float32).npu()
    
    y, y_scale = cann_ops_nn.dequant_situ_quant(
        x, weight_scale=weight_scale,
        beta=4.0, linear_beta=25.0, activate_left=True, quant_type="dynamic",
    )
    print("y:============", y.shape, y.cpu())
    print("y_scale:============", y_scale.shape, y_scale.cpu())
    
    # BF16, pre-dequantization
    x_bf16 = torch.randn(32, 128, dtype=torch.bfloat16).npu()
    y_bf16, y_scale_bf16 = cann_ops_nn.dequant_situ_quant(
        x_bf16, beta=4.0, linear_beta=25.0, activate_left=True, quant_type="dynamic",
    )
    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, weight_scale, quant_scale):
            return cann_ops_nn.dequant_situ_quant(
                x, weight_scale=weight_scale, quant_scale=quant_scale,
                beta=4.0, linear_beta=25.0, activate_left=True, quant_type="static",
            )
    
    
    def dequant_situ_quant_test():
        x = torch.randint(-127, 127, (16, 64), dtype=torch.int8).npu()
        weight_scale = torch.full((64,), 0.1, dtype=torch.float32).npu()
        quant_scale = torch.tensor([1.0], dtype=torch.float32).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, weight_scale, quant_scale)
        print("y:============", y.shape, y.cpu())
        print("y_scale:============", y_scale.shape, y_scale.cpu())
    
    
    if __name__ == "__main__":
        dequant_situ_quant_test()