aclnnQuantMatmulActivationQuant

📄 View Source Code

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: Fused quantized matrix multiplication, activation, and dynamic quantization computation. Currently supports the gelu activation (including gelu_tanh and gelu_erf) and the MX quantization mode. The minimum supported number of input dimensions is 2, and the maximum is 6. Similar APIs include aclnnMm (supports only 2D tensors as matrix multiplication inputs) and aclnnBatchMatMul (supports only 3D matrix multiplication, where the first dimension is the batch dimension). Based on these APIs, this API fuses the gelu activation and dynamic MX quantization to improve hardware computation efficiency.

  • Formula:

    • Ascend 950PR&950DT products:

      Supports the MX quantization mode. For the combinations of input and output data types corresponding to different quantization modes, see Constraints.

      QuantMatmul MX quantization mode matmulOut[m,n]=∑j=0kLoops−1((∑k=0gsK−1(x1Slice∗x2Slice))∗(x1Scale[m/gsM,j]∗x2Scale[j,n/gsN]))+bias[n]matmulOut[m,n] = \sum_{j=0}^{kLoops-1} ((\sum_{k=0}^{gsK-1} (x1Slice * x2Slice))* (x1Scale[m/gsM, j] * x2Scale[j, n/gsN]))+bias[n]

      where gsM, gsN, and gsK represent groupSizeM, groupSizeN, and groupSizeK, respectively; x1Slice represents the vector with a length of groupSizeK in row m of x1, and x2Slice represents the vector with a length of groupSizeK in column n of x2; both are sliced along the K axis starting from j*groupSizeK, j takes values in the range [0, kLoops), kLoops = ceil(K / groupSizeK), and K is the length of the K axis; supports the last slice with a length less than groupSizeK. bias is included only in MX quantization mode.

      Activation Formula
      • gelu_tanh (high-performance approximation):

        activationOut=GELU(matmulOut)=matmulOut×Φ(matmulOut)=0.5∗matmulOut∗(1+tanh(2/π∗(matmulOut+0.044715∗matmulOut3)))activationOut=GELU(matmulOut)=matmulOut × Φ(matmulOut)=0.5 * matmulOut * (1 + tanh( \sqrt{2 / \pi} * (matmulOut + 0.044715 * matmulOut^{3})))
      • gelu_erf:

        activationOut=GELU(matmulOut)=0.5∗matmulOut∗(1+erf(matmulOut/2))activationOut=GELU(matmulOut)=0.5 * matmulOut * (1 + erf(matmulOut / \sqrt{2}))
      Dynamic Quantization Formula
      • Scenario 1, when scaleAlg is 0:

        • The input activationOut is grouped along the last axis by k=32k=32 values, and each group of k values {{Vi}i=1k}\{\{V_i\}_{i=1}^{k}\} is dynamically quantized into {mxscale1,{Pi}i=1k}, k=32\{mxscale1, \{P_i\}_{i=1}^{k}\},\space k = 32
        shared_exp=floor(log2(maxi(∣Vi∣)))−emaxmxscale=2shared_expPi=cast_to_dst_type(Vi/mxscale,round_mode), i from 1 to kshared\_exp = floor(log_2(max_i(|V_i|))) - emax \\ mxscale = 2^{shared\_exp}\\ P_i = cast\_to\_dst\_type(V_i/mxscale, round\_mode), \space i\space from\space 1\space to\space k\\
        • The quantized PiP_{i} values form the output yOut according to the corresponding positions of ViV_{i}, and mxscale is output as yScaleOut for each group along the last axis.

        • emax: The exponent of the maximum normal number of the corresponding data type.

          DataTypeEmax
          FLOAT4_E2M12
          FLOAT8_E4M3FN8
          FLOAT8_E5M215
      • Scenario 2: When scaleAlg is 1, only FP8 types are involved:

        • The input activationOut is divided into blocks of k=32k = 32 elements along the tail axis, and a block scale factor Sfp32bS_{fp32}^b is computed for each block separately. All elements in the block are then mapped to the target low-precision type FP8 using the same Sfp32bS_{fp32}^b. If the last block contains fewer than k=32k = 32 elements, the missing values are treated as 0 and the block is processed as a complete block.

        • Find the maximum absolute value in the block:

          Amax(Dfp32b)=max({∣di∣}i=1k)Amax(D_{fp32}^b)=max(\{|d_{i}|\}_{i=1}^{k})
        • Map FP32 to within the range representable by the target data type FP8, where Amax(DType)Amax(DType) is the maximum value representable by the target precision:

          Sfp32b=Amax(Dfp32b)Amax(DType)S_{fp32}^b = \frac{Amax(D_{fp32}^b)}{Amax(DType)}
        • Convert the block scale factor Sfp32bS_{fp32}^b to the representable scale value Sue8m0bS_{ue8m0}^b in FP8 format.

        • Extract the unbiased exponent EintbE_{int}^b and mantissa MfixpbM_{fixp}^b from the block floating-point scale factor Sfp32bS_{fp32}^b.

        • To ensure no overflow during quantization, round up the exponent and keep it within the representable range of FP8:

          Eintb={Eintb+1, ifSfp32b is a normal number, andEintb<254 andMfixpb>0Eintb+1, ifSfp32b is a subnormal number, andMfixpb>0.5Eintb, otherwiseE_{int}^b = \begin{cases} E_{int}^b + 1, & \text{ if} S_{fp32}^b \text{ is a normal number, and} E_{int}^b < 254 \text{ and} M_{fixp}^b > 0 \\ E_{int}^b + 1, & \text{ if} S_{fp32}^b \text{ is a subnormal number, and} M_{fixp}^b > 0.5 \\ E_{int}^b, & \text{ otherwise} \end{cases}
        • Calculate the block scale factor: Sue8m0b=2EintbS_{ue8m0}^b=2^{E_{int}^b}

        • Calculate the block conversion factor: Rfp32b=1fp32(Sue8m0b)R_{fp32}^b=\frac{1}{fp32(S_{ue8m0}^b)}

        • Apply to the final quantization step. For each element within a block, di=DType(dfp32i⋅Rfp32n)d^i = DType(d_{fp32}^i \cdot R_{fp32}^n). The final quantized output is (Sb,[di]i=1k)\left(S^b, [d^i]_{i=1}^k\right), where SbS^b represents the block scale factor, i.e., Sue8m0bS_{ue8m0}^b, and [di]i=1k[d^i]_{i=1}^k represents the quantized data within the block.

      • Use case 3: when scaleAlg is 2, only the FP4_E2M1 type is involved:

        • When dstTypeMax = 0.0/6.0/7.0:
          • The input x is grouped along the axis dimension in groups of k = blocksize elements, and each group of k numbers {{Vi}i=1k}\{\{V_i\}_{i=1}^{k}\} is dynamically quantized to {mxscale1,{Pi}i=1k}\{mxscale1, \{P_i\}_{i=1}^{k}\}, k = blocksize:shared_exp={ceil(log2(maxi(∣Vi∣)))−emax, iftheone/twobitsprecedingthehighbitofthemantissa are 1, and the mantissa is not all 0floor(log2(maxi(∣Vi∣)))−emax, otherwiseshared\_exp = \begin{cases} ceil(log_2(max_i(|V_i|))) - emax, & \text{ if} the one/two bits preceding the high bit of the mantissa \text{ are 1, and the mantissa is not all 0} \\ floor(log_2(max_i(|V_i|))) - emax, & \text{ otherwise} \end{cases} \\ Pi=cast_to_dst_type(Vi/mxscale,round_mode), i from 1 to blocksizeP_i = cast\_to\_dst\_type(V_i/mxscale, round\_mode), \space i\space from\space 1\space to\space blocksize\\
          • ​The quantized PiP_{i} are combined into the output yOut according to the positions of the corresponding ViV_{i}, and mxscale is combined into the output mxscaleOut according to the corresponding groupings along the axis dimension.
        • When dstTypeMax != 0.0/6.0/7.0:
          • The long vector is divided into blocks, each with a length of k. A block scale factor Sfp32bS_{fp32}^b is computed separately for each block, and then all elements in the block are mapped to the target low-precision type using the same Sfp32bS_{fp32}^b. If the last block has fewer than k elements, the missing values are treated as 0, and the block is processed as a complete one.
          • Find the maximum absolute value in the block:Amax(Dfp32b)=max({∣di∣}i=1k)Amax(D_{fp32}^b)=max(\{|d_{i}|\}_{i=1}^{k})
          • Map FP32 to within the range representable by the target data type, where if dst_max_value=0, Amax(DType)Amax(DType) is the maximum value representable by the target precision; if dst_max_value!=0, Amax(DType)Amax(DType) is the value passed in for dst_max_value.Sfp32b=Amax(Dfp32b)Amax(DType)S_{fp32}^b = \frac{Amax(D_{fp32}^b)}{Amax(DType)}
          • Convert the block quantization scale factor Sfp32bS_{fp32}^b to a scale value Sue8m0bS_{ue8m0}^b representable in the FP8 format.
          • Extract the unbiased exponent EintbE_{int}^b and the mantissa MfixpbM_{fixp}^b from the floating-point quantization scale factor Sfp32bS_{fp32}^b of the block.
          • To ensure no overflow during quantization, round up the exponent and keep it within the representable range of FP8:Eintb={Eintb+1, ifSfp32b is a normal number, andEintb<254 andMfixpb>0Eintb, otherwiseE_{int}^b = \begin{cases} E_{int}^b + 1, & \text{ if} S_{fp32}^b \text{ is a normal number, and} E_{int}^b < 254 \text{ and} M_{fixp}^b > 0 \\ E_{int}^b, & \text{ otherwise} \end{cases}
          • Calculate the block scale factor: Sue8m0b=2EintbS_{ue8m0}^b=2^{E_{int}^b}
          • Calculate the block conversion factor: Rfp32b=1fp32(Sue8m0b)R_{fp32}^b=\frac{1}{fp32(S_{ue8m0}^b)}
          • Apply to the final quantization step. For each element within a block, di=DType(dfp32i⋅Rfp32n)d^i = DType(d_{fp32}^i \cdot R_{fp32}^n). The final quantized output is (Sb,[di]i=1k)\left(S^b, [d^i]_{i=1}^k\right), where SbS^b represents the block scale factor, i.e., Sue8m0bS_{ue8m0}^b, and [di]i=1k[d^i]_{i=1}^k represents the quantized data within the block.
          • ​The quantized PiP_{i} are combined into the output yOut according to the positions of the corresponding ViV_{i}, and mxscale is combined into the output mxscaleOut according to the corresponding groupings along the axis dimension.

Function Prototype

Each operator uses a two-phase API. Call "aclnnQuantMatmulActivationQuantGetWorkspaceSize" first to obtain the workspace size required for the calculation and the executor that includes the calculation process of the operator, and then call "aclnnQuantMatmulActivationQuant" to perform the calculation.

aclnnStatus aclnnQuantMatmulActivationQuantGetWorkspaceSize(
  const aclTensor *x1,
  const aclTensor *x2,
  const aclTensor *x1ScaleOptional,
  const aclTensor *x2Scale,
  const aclTensor *biasOptional,
  bool             transposeX1,
  bool             transposeX2,
  int64_t          groupSize,
  char            *activationType,
  char            *quantMode,
  char            *roundMode,
  int64_t          scaleAlg,
  double           dstTypeMax,
  aclTensor       *yOut,
  aclTensor       *yScaleOut,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnQuantMatmulActivationQuant(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnQuantMatmulActivationQuantGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x1 Input The input x1 in the formula.
    • Empty tensors are not supported.
    • Supports non-contiguous tensors when the last two axes are transposed. Non-contiguous tensors are not supported along other axes.
    • In the case of transposeX1 being false, each dimension of x1 is: (batch, m, k), and batch may not exist.
    • In the case of transposeX1 being true, each dimension of x1 is: (batch, k, m), and batch may not exist.
    FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1 ND 2-6 ✓
    x2 Input The input x2 in the formula.
    • Empty tensors are not supported.
    • Supports non-contiguous tensors when the last two axes are transposed. Non-contiguous tensors are not supported along other axes.
    • When transposeX2 is false, each dimension of x2 indicates (batch, k, n). The batch dimension may not exist.
    • When transposeX2 is true, each dimension of x2 indicates (batch, n, k). The batch dimension may not exist.
    FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1 ND 2-6 ✓
    x1ScaleOptional Optional input The input x1Scale in the formula.
    • Empty tensors are not supported.
    • When x1Scale is FLOAT8_E8M0, x1Scale is 3D. Each dimension indicates (m, ceil(k / 64), 2) when transposeX1 is false, and (ceil(k / 64), m, 2) when transposeX1 is true.
    FLOAT8_E8M0 ND 3-7 ✓
    x2Scale Input Represents the quantization parameter, that is, the input x2Scale in the formula.
    • Empty tensors are not supported.
    • When x2Scale is FLOAT8_E8M0, x2Scale is 3D, and each dimension is as follows: (ceil(k / 64), n, 2) if transposeX2 is false, and (n, ceil(k / 64), 2) if transposeX2 is true.
    FLOAT8_E8M0 ND 3-7 ✓
    biasOptional Optional input The input bias in the formula.
    • Empty tensors are not supported.
    • The shape supports 1D (n,) or 3D (batch, 1, n), where n is the same as that of x2.
    • When y is 2D, 4D, 5D, or 6D, the shape of bias supports only 1D (n,).
    • If this parameter is not used, pass nullptr.
    FLOAT32 ND 1, 3 ×
    transposeX1 Input Indicates whether the input shape of x1 is transposed. - BOOL - - -
    transposeX2 Input Indicates whether the input shape of x2 is transposed. - BOOL - - -
    groupSize Optional input Specifies the quantization group sizes along the m, n, and k dimensions of the input. Consists of three values groupSizeM, groupSizeN, and groupSizeK concatenated for the three dimensions. Each value occupies 16 bits, taking up the lower 48 bits of the int64_t groupSize (the value of the upper 16 bits in groupSize is invalid). For the calculation formula, see Formula 1 below the table. If groupSize is not supported, pass 0. INT64 - - -
    activationType Input Activation type. Supports {"gelu_tanh", "gelu_erf"}. STRING - - -
    quantMode Input The quantization mode. Supports {"mx"}. STRING - - -
    roundMode Input Data conversion mode, corresponding to round_mode in the formula.
    • When yDtype is FLOAT4_E2M1, supports {"rint", "floor", "round"}.
    • When yDtype is FLOAT8_E4M3FN/FLOAT8_E5M2, only supports {"rint"}.
    STRING - - -
    scaleAlg Input Calculation method of mxscaleOut, corresponding to scaleAlg in the formula.
    • When yDtype is FLOAT4_E2M1, the supported values are 0 and 2. The value 0 represents scenario 1, and 2 represents scenario 3 (with dstTypeMax enabled).
    • When yDtype is FLOAT8_E4M3FN/FLOAT8_E5M2, the supported values are 0 and 1. The value 0 represents scenario 1, and 1 represents scenario 2.
    INT64 - - -
    dstTypeMax Input Represents the value of maxType, corresponding to Amax(DType) in the formula.
    • When scaleAlg is 0 or 1, dstTypeMax does not take effect and the value is not validated. 0.0 is recommended.
    • When scaleAlg is 2, dstTypeMax supports values 0.0 and 6.0-12.0. The value 0.0 indicates that the default maximum value of the target type is used, and 6.0-12.0 indicates that the specified value is used.
    DOUBLE - - -
    yOut Output. Output y in the formula, the calculation result of matmul and activation after dynamic quantization.
    • Empty tensors are not supported.
    • The shape is the same as the matmul calculation result, (batch, m, n). The batch dimension may not exist.
    FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1 ND 2-6 -
    yScaleOut Output Quantization scale corresponding to each group after dynamic quantization.
    • Empty tensors are not supported.
    • On the last axis, the shape is the value of the axis corresponding to y divided by 32 and rounded up, padded to an even number with 0.
    • Every two rows of the yScale output need to be interleaved.
    • The shape is the same as that of the matrix multiplication calculation result, (batch, m, ceil(n/64), 2), where batch may not exist.
    FLOAT8_E8M0 ND 3-7 -
    workspaceSize Output Returns the workspace size that needs to be applied on the Device side. - - - - -
    executor Output Returns the op executor, which includes the operator calculation flow. - - - - -
    • Note: An optional input refers to an optional quantization parameter, and passing a null pointer is supported.

    • Formula 1:

      groupSize=groupSizeK∣groupSizeN<<16∣groupSizeM<<32groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32
  • Return value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 x1, x2, x1Scale, x2Scale, yOut, or yScaleOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut is not supported.
    The shape of x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut does not meet the verification requirements.
    x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut is an empty tensor.
    The values of activationType, quantMode, roundMode, scaleAlg, dstTypeMax, groupSize, or transposeX1 are out of the supported range.

aclnnQuantMatmulActivationQuant

  • Parameters

    Parameter Input/Output Description
    workspace Input The workspace memory address applied on the Device side.
    workspaceSize Input The workspace size applied on the Device side, obtained by the first-phase API aclnnQuantMatmulActivationQuantGetWorkspaceSize.
    executor Input Op executor that includes the calculation flow of the operator.
    stream Input Specifies the stream for executing the task.
  • Return value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation:

    • aclnnQuantMatmulActivationQuant defaults to a deterministic implementation.
  • General Constraints:

    • x1 only supports the ND format, and x2 only supports the ND format.

    • When transposeX1 is false, the shape of x1 is (batch, m, k). When transposeX1 is true, the shape of x1 is (batch, k, m). Here, batch represents the first 0 to 4 dimensions, where 0 dimension indicates that batch does not exist.

    • When transposeX2 is false, the shape of x2 is (batch, k, n). When transposeX2 is true, the shape of x2 is (batch, n, k). Here, batch represents the first 0 to 4 dimensions, and 0 dimension means batch does not exist. k is consistent with k in the shape of x1.

    • The transpose states of x1 and x2 are determined by both the transpose flag and stride. Changing either one suffices (the two methods are equivalent; do not use them together):

      • Method 1: Set the corresponding flag transposeX1/transposeX2 to true, and pass in the shape after transposition (see the description of the shape when the flag is true above).
      • Method 2: Keep the flag as false and pass in the tensor with a transposed view (the shape remains the shape when the flag is false; for example, x2 is (batch, k, n) and the second-to-last dimension of the stride is 1). The API automatically processes the tensor as transposed.
    • x1Scale and x2Scale do not carry transpose flags. Their shapes must be consistent with the transpose direction of x1 and x2 (x2Scale is (batch, n, ceil(k/64), 2) when transposed and (batch, ceil(k/64), n, 2) when non-transposed).

    • When the last two dimensions of x1 are equal (m = k) or the last two dimensions of x2 are equal (k = n), transpose is determined by the transposeX1/transposeX2 flags instead of the strides.

    • x1 supports non-contiguous tensors in the case of the last two axes transpose, but non-contiguous tensors in other use cases are not supported.

    • x2 supports non-contiguous tensors in the case of the last two axes transpose, but non-contiguous tensors in other use cases are not supported.

    • bias-related constraints:

      • Optional parameter. Passing in a null pointer is supported, but an empty tensor is not supported.
      • The data type must be FLOAT32.
      • The shape can be 1D (n,) or 3D (batch, 1, n), where n is the same as n in x2.
      • If y has a 2D, 4D, 5D, or 6D shape, the shape of bias only supports 1D (n,).
    • Constraints on groupSize:

      • Takes effect only in the MX quantization mode.
      • The input groupSize is internally decomposed into groupSizeM, groupSizeN, and groupSizeK according to the following formula. Currently, only [0, 0, 0] or [1, 1, 32] is supported, and [0, 0, 0] is automatically deduced as [1, 1, 32].
      groupSize=groupSizeK∣groupSizeN<<16∣groupSizeM<<32groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32
    • The shape of y supports 2-6 dimensions, in the format of (batch, m, n). batch may not exist. m must be the same as the m of x1, and n must be the same as the n of x2.

    MX quantization use case constraints:
    • The input and output support the following data type combinations:

      | x1 | x2 | x1Scale | x2Scale | Bias | y | yScale |
      |---------------|---------------|-------------|-------------|--------------|---------------------------|-------------|
      | FLOAT8_E4M3FN | FLOAT8_E4M3FN | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT8_E4M3FN             | FLOAT8_E8M0 |
      | FLOAT8_E5M2   | FLOAT8_E4M3FN | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT8_E5M2               | FLOAT8_E8M0 |
      | FLOAT8_E5M2   | FLOAT8_E5M2   | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT8_E5M2               | FLOAT8_E8M0 |
      | FLOAT8_E4M3FN | FLOAT8_E5M2   | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT8_E4M3FN             | FLOAT8_E8M0 |
      | FLOAT4_E2M1   | FLOAT4_E2M1   | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT4_E2M1               | FLOAT8_E8M0 |
    • Relationship among the x1 data type, x2 data type, x1, x2, x1Scale, x2Scale, and groupSize:

      Quantization Typex1 Data Typex2 Data Typex1 Shapex2 Shapex1Scale Shapex2Scale ShapeBias ShapeyScale Shape[gsM, gsN, gsK]groupSize
      MX full quantizationFLOAT8_E4M3FNFLOAT8_E4M3FN
    • Non-transposed: (batch_x1, m, k)
    • Non-transposed: (batch_x2, k, n)
    • Transposed: (batch_x2, n, k)
    • Non-transposed: (batch_x1, m, ceil(k / 64), 2)
    • Non-transposed: (batch_x2, ceil(k / 64), n, 2)
    • Transposed: (batch_x2, n, ceil(k / 64), 2)
    • (n,) or (batch_max, 1, n)(batch_max, m, ceil(n / 64), 2)[1, 1, 32]4295032864
      MX full quantizationFLOAT8_E5M2FLOAT8_E4M3FN
    • Non-transposed: (batch_x1, m, k)
    • Non-transposed: (batch_x2, k, n)
    • Transposed: (batch_x2, n, k)
    • Non-transposed: (batch_x1, m, ceil(k / 64), 2)
    • Non-transposed: (batch_x2, ceil(k / 64), n, 2)
    • Transposed: (batch_x2, n, ceil(k / 64), 2)
    • (n,) or (batch_max, 1, n)(batch_max, m, ceil(n / 64), 2)[1, 1, 32]4295032864
      MX full quantizationFLOAT8_E5M2FLOAT8_E5M2
    • Non-transposed: (batch_x1, m, k)
    • Non-transposed: (batch_x2, k, n)
    • Transposed: (batch_x2, n, k)
    • Non-transposed: (batch_x1, m, ceil(k / 64), 2)
    • Non-transposed: (batch_x2, ceil(k / 64), n, 2)
    • Transposed: (batch_x2, n, ceil(k / 64), 2)
    • (n,) or (batch_max, 1, n)(batch_max, m, ceil(n / 64), 2)[1, 1, 32]4295032864
      MX full quantizationFLOAT8_E4M3FNFLOAT8_E5M2
    • Non-transposed: (batch_x1, m, k)
    • Non-transposed: (batch_x2, k, n)
    • Transposed: (batch_x2, n, k)
    • Non-transposed: (batch_x1, m, ceil(k / 64), 2)
    • Non-transposed: (batch_x2, ceil(k / 64), n, 2)
    • Transposed: (batch_x2, n, ceil(k / 64), 2)
    • (n,) or (batch_max, 1, n)(batch_max, m, ceil(n / 64), 2)[1, 1, 32]4295032864
      MX full quantizationFLOAT4_E2M1FLOAT4_E2M1
    • non-transposed: (batch_x1, m, k)
    • transposed: (batch_x1, k, m)
    • Non-transposed: (batch_x2, k, n)
    • Transposed: (batch_x2, n, k)
    • non-transposed: (batch_x1, m, ceil(k / 64), 2)
    • transposed: (batch_x1, ceil(k / 64), m, 2)
    • Non-transposed: (batch_x2, ceil(k / 64), n, 2)
    • Transposed: (batch_x2, n, ceil(k / 64), 2)
    • (n,) or (batch_max, 1, n)(batch_max, m, ceil(n / 64), 2)[1, 1, 32]4295032864
    • Note: In the table above, gsM, gsK, and gsN represent groupSizeM, groupSizeK, and groupSizeN, respectively.

    • In the MX quantization use case, the transpose attribute of x1 must be consistent with that of x1Scale, and the transpose attribute of x2 must be consistent with that of x2Scale.

    • The data type of yOut is determined by the data type of x1, and the two must be the same.

    • MXFP4 use case constraints (the data types of x1, x2, and y are all FLOAT4_E2M1):

      • scaleAlg only supports values 0 and 2.
      • If scaleAlg is 2, dstTypeMax supports values 0.0 and 6.0-12.0.
      • roundMode supports {"rint", "floor", "round"}.
      • The inner axes of x1 and x2 must be even, and k must be greater than 2.
      • The N dimension of y must be even.

Example

The sample code below is for reference only. For details about the compilation and execution process, see Compile and Run Samples.

x1 is FLOAT8_E4M3FN, x2 is FLOAT8_E4M3FN (ND format), x1Scale is FLOAT8_E8M0, x2Scale is FLOAT8_E8M0, activation is gelu_tanh, and scaleAlg is 0 (scenario 1).

#include <iostream>
#include <memory>
#include <cmath>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_quant_matmul_activation_quant.h"
#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)
#define CHECK_FREE_RET(cond, return_expr) \
    do {                                  \
        if (!(cond)) {                    \
            Finalize(deviceId, stream);   \
            return_expr;                  \
        }                                 \
    } while (0)
#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)
int64_t GetShapeSize(const std::vector<int64_t>& shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}
int Init(int32_t deviceId, aclrtStream* stream)
{
    // Boilerplate code: resource initialization.
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
    return 0;
}
template <typename T>
int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                    aclDataType dataType, aclTensor** tensor)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    // Call aclrtMalloc to allocate memory on the device.
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
    // Call aclrtMemcpy to copy host data to the device memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
    // Calculate the strides of the contiguous tensor.
    std::vector<int64_t> strides(shape.size(), 1);
    for (int64_t i = shape.size() - 2; i >= 0; i--) {
        strides[i] = shape[i + 1] * strides[i + 1];
    }
    // Call the aclCreateTensor API to create an aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                              shape.data(), shape.size(), *deviceAddr);
    return 0;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
}

int AclnnQuantMatmulActivationQuantTest(int32_t deviceId, aclrtStream& stream)
{
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct inputs and outputs. Customize the construction based on the API.
    int64_t m = 5;
    int64_t k = 64;
    int64_t n = 128;
    bool transposeX1 = false;
    bool transposeX2 = false;
    constexpr int64_t MX_SCALE_BLOCK_SIZE = 64; // scale block alignment size, used to calculate the scale shape
    std::vector<int64_t> x1Shape = {m, k};
    std::vector<int64_t> x2Shape = {k, n};
    std::vector<int64_t> x1ScaleShape = {m, (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, 2};
    std::vector<int64_t> x2ScaleShape = {(k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, n, 2};
    std::vector<int64_t> outShape = {m, n};
    std::vector<int64_t> outScaleShape = {m, (n + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, 2};
    void* x1DeviceAddr = nullptr;
    void* x2DeviceAddr = nullptr;
    void* x1ScaleDeviceAddr = nullptr;
    void* x2ScaleDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    void* outScaleDeviceAddr = nullptr;
    aclTensor* x1 = nullptr;
    aclTensor* x2 = nullptr;
    aclTensor* x1Scale = nullptr;
    aclTensor* x2Scale = nullptr;
    aclTensor* bias = nullptr;
    aclTensor* out = nullptr;
    aclTensor* outScale = nullptr;
    std::vector<uint8_t> x1HostData(m * k, 0b00111000);                  // 1.0 in float8_e4m3
    std::vector<uint8_t> x2HostData(k * n, 0b00111000);                  // 1.0 in float8_e4m3
    std::vector<uint8_t> x1ScaleHostData(m * (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE * 2, 0b01111111); // 1.0 in float8_e8m0
    std::vector<uint8_t> x2ScaleHostData((k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE * n * 2, 0b01111111); // 1.0 in float8_e8m0
    std::vector<uint8_t> outHostData(m * n, 0);
    std::vector<uint8_t> outScaleHostData(m * (n + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE * 2, 0);
    // Create x1 aclTensor.
    ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &x1);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x1TensorPtr(x1, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> x1DeviceAddrPtr(x1DeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create x2 aclTensor.
    ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &x2);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x2TensorPtr(x2, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> x2DeviceAddrPtr(x2DeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create x1Scale aclTensor.
    ret = CreateAclTensor(x1ScaleHostData, x1ScaleShape, &x1ScaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &x1Scale);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x1ScaleTensorPtr(x1Scale, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> x1ScaleDeviceAddrPtr(x1ScaleDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create x2Scale aclTensor.
    ret = CreateAclTensor(x2ScaleHostData, x2ScaleShape, &x2ScaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &x2Scale);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x2ScaleTensorPtr(x2Scale, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> x2ScaleDeviceAddrPtr(x2ScaleDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create out aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &out);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> outTensorPtr(out, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> outDeviceAddrPtr(outDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create mxscale aclTensor.
    ret = CreateAclTensor(outScaleHostData, outScaleShape, &outScaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0,
                          &outScale);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> outScaleTensorPtr(outScale, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> outScaleDeviceAddrPtr(outScaleDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // 3. Call the CANN operator library API. Change it to the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor = nullptr;
    int64_t groupSizeValue = 4295032864;
    char activationType[] = "gelu_tanh";
    char quantMode[] = "mx";
    char roundMode[] = "rint";
    ret = aclnnQuantMatmulActivationQuantGetWorkspaceSize(x1, x2, x1Scale, x2Scale, bias, transposeX1, transposeX2,
                                                          groupSizeValue, activationType, quantMode, roundMode, 0, 0.0, out,
                                                          outScale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulActivationQuantGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);
    // Allocate device memory based on the workspaceSize calculated by the first-phase API.
    void* workspaceAddr = nullptr;
    std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtr(nullptr, aclrtFree);
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
        workspaceAddrPtr.reset(workspaceAddr);
    }
    // Call the second-phase API of aclnnQuantMatmulActivationQuant
    ret = aclnnQuantMatmulActivationQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulActivationQuant failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Wait synchronously for the task to complete.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
    // 5. Obtain the output values, copy the result from device memory to host memory, and modify it as required by the specific API definition.
    auto size = GetShapeSize(outShape);
    std::vector<uint8_t> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
                      size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]);
    }
    size = GetShapeSize(outScaleShape);
    std::vector<uint8_t> scaleData(size, 0);
    ret = aclrtMemcpy(scaleData.data(), scaleData.size() * sizeof(scaleData[0]), outScaleDeviceAddr,
                      size * sizeof(scaleData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy scale result from device to host failed. ERROR: %d\n", ret);
              return ret);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("scale[%ld] is: %d\n", i, scaleData[i]);
    }
    return ACL_SUCCESS;
}

int main()
{
    // 1. (Boilerplate) Initialize device/stream. For details, see the acl API documentation.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = AclnnQuantMatmulActivationQuantTest(deviceId, stream);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("AclnnQuantMatmulActivationQuantTest failed. ERROR: %d\n", ret);
                  return ret);
    Finalize(deviceId, stream);
    return 0;
}