aclnnQuantMatmulActivationQuantWeightNz

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

  • Formula:

    • Ascend 950PR&950DT products:

      Supports MX quantization mode. For the input and output data type combinations 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 the "aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclnnQuantMatmulActivationQuantWeightNz" API to execute the computation.

aclnnStatus aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize(
  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 aclnnQuantMatmulActivationQuantWeightNz(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    x1 Input Input x1 in the formula.
    • Does not support empty tensors.
    • Supports non-contiguous tensors when the last two axes are transposed. Non-contiguous tensors are not supported along other axes.
    • When transposeX1 is false, each dimension of x1 indicates: (batch, m, k), and batch may not exist.
    • When transposeX1 is true, each dimension of x1 indicates: (batch, k, m), and batch may not exist.
    • When the data types of x1, x2, and y are all FLOAT4_E2M1 (MXFP4 use case), x1 does not support transposition, that is, transposeX1 cannot be true.
    FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1 ND 2-6 ✓
    x2 Input Input x2 in the formula.
    • Does not support empty tensors.
    • In the NZ format, the shape supports 4-8 dimensions.
    • If transposeX2 is true, each dimension of x2 indicates: (batch, k1, n1, n0, k0), where batch may not exist, k0 = 32, and n0 = 16.
    • If transposeX2 is false, each dimension of x2 indicates: (batch, n1, k1, k0, n0), where batch may not exist, k0 = 16, and n0 = 32.
    • k in the x1 shape and k1 in the x2 shape must satisfy ceil(k / k0) = k1, and n1 in the x2 shape and n in y must satisfy ceil(n / n0) = n1.
    • Use the aclnnCalculateMatmulWeightSizeV2 and aclnnTransMatmulWeight APIs to convert the input format from ND to NZ.
    FLOAT8_E4M3FN, FLOAT4_E2M1 NZ 4-8 ✓
    x1ScaleOptional Optional input Input x1Scale in the formula.
    • Does not support empty tensors.
    • If x1Scale is FLOAT8_E8M0, x1Scale is 3-dimensional. Each dimension indicates: (m, ceil(k / 64), 2) if transposeX1 is false, and (ceil(k / 64), m, 2) if transposeX1 is true.
    FLOAT8_E8M0 ND 3-7 ✓
    x2Scale Input Indicates the quantization parameter, the input x2Scale in the formula.
    • Does not support empty tensors.
    • If x2Scale is FLOAT8_E8M0, x2Scale is a 3D tensor, and each dimension indicates: (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 Input bias in the formula.
    • Does not support empty tensors.
    • Supports the 1D shape (n,) or the 3D shape (batch, 1, n), where n is the same as the n of x2.
    • When the shape of y is 2D, 4D, 5D, or 6D, only the 1D shape (n,) is supported for bias.
    • If this parameter is not used, pass in 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 Used to specify the quantization group sizes in the m, n, and k directions of the input. Concatenated from groupSizeM, groupSizeN, and groupSizeK in the three directions, with each value occupying 16 bits. In total, they occupy the lower 48 bits of the int64_t groupSize (the upper 16 bits of groupSize are invalid). For the formula, see Formula 1 below the table. For scenarios where groupSize is not supported, pass 0. INT64 - - -
    activationType Input Activation type. Supports {"gelu_tanh", "gelu_erf"}. STRING - - -
    quantMode Input Quantization mode. Supports {"mx"}. STRING - - -
    roundMode Input Indicates the 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 Indicates the calculation method of mxscaleOut, corresponding to scaleAlg in the formula.
    • Supports values 0, 1, and 2, where 0 indicates scenario 1, 1 indicates scenario 2, and 2 indicates scenario 3.
    • When yDtype is FLOAT4_E2M1, only values 0 and 2 are supported.
    • When yDtype is FLOAT8_E4M3FN/FLOAT8_E5M2, values 0 and 1 are supported.
    INT64 - - -
    dstTypeMax Input Indicates the value of maxType, corresponding to Amax(DType) in the formula.
    • When scaleAlg is 0 or 1, dstTypeMax does not take effect and no interception is performed. The recommended input value is 0.0.
    • When scaleAlg is 2, dstTypeMax supports values 0.0 and 6.0-12.0. A value of 0.0 indicates using the default maximum value of the target type, and a value of 6.0-12.0 indicates using the specified value.
    DOUBLE - - -
    yOut Output Output y in the formula, the calculation result of the matmul and activation after dynamic quantization.
    • Does not support empty tensors.
    • The shape is the same as the matmul calculation result, (batch, m, n), where batch may not exist.
    FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1 ND 2-6 -
    yScaleOut Output Quantization scale corresponding to each group after dynamic quantization.
    • Does not support empty tensors.
    • On the last axis, the shape is the value of the corresponding axis of y divided by 32 and rounded up, and then padded to an even number, with 0 as the padding value.
    • The yScale output needs to be interleaved for every two rows of data.
    • The shape is the same as the matmul 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 contains the operator computation 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 The input x1, x2, x1Scale, x2Scale, yOut, or yScaleOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type and data format of x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut are not within the supported range.
    The shape of x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut does not meet the validation conditions.
    x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut is an empty tensor.
    The values of activationType, quantMode, roundMode, scaleAlg, dstTypeMax, groupSize, and transposeX1 are not within the supported range.

aclnnQuantMatmulActivationQuantWeightNz

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Workspace size applied on the Device side, obtained by calling the first-phase API aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize.
    executor Input Op executor. Contains the operator computation flow.
    stream Input Stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation:

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

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

    • When k or n is 1, the weightNz feature cannot be used. This API does not support this use case.

    • Before calling this API, aclnnTransMatmulWeight or aclnnNpuFormatCast can be called to convert x2 in ND format to the NZ format. When using the converted x2, pad it with 0s to prevent dirty data from being introduced.

    • 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.

    • Shape of x2 when transposeX2 is false: (batch, n1, k1, k0, n0). Shape of x2 when transposeX2 is true: (batch, k1, n1, n0, k0). batch represents the preceding 0-4 dimensions, and 0 indicates that batch does not exist. k is the same as k in the shape of x1.

    • The transpose states of x1 and x2 are determined by both the transpose flags and strides. Changing either one is sufficient (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 preceding description of the shape when the flag is true).
      • Method 2: Keep the flag as false and pass in the tensor as a transposed view (the shape remains the shape for false, for example, x2 is (batch, k, n) with the second-to-last dimension of the stride being 1). The API automatically processes the tensor as transposed.
    • x1Scale and x2Scale do not carry transposition flags. Their shapes must be consistent with the transposition states of x1 and x2 (when transposed, x2Scale is (batch, n, ceil(k/64), 2); when non-transposed, it is (batch, ceil(k/64), n, 2)).

    • When the last two dimensions of x1 are equal (m = k) or the last two dimensions of x2 are equal (k = n), determine the transposition state based on the transposeX1/transposeX2 flags instead of the stride.

    • x1 supports a non-contiguous tensor with the last two axes transposed. A non-contiguous tensor in other use cases is not supported.

    • x2 supports a non-contiguous tensor with the last two axes transposed. A non-contiguous tensor in other use cases is not supported.

    • If the data type of x1 is FLOAT8_E5M2, the data type of x2 must be FLOAT8_E4M3FN.

    • 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 | | 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 Type | x1 Data Type | x2 Data Type | x1 Shape | x2 Shape | x1Scale Shape | x2Scale Shape | Bias Shape | yScale Shape | [gsM, gsN, gsK] | groupSize | |-------|--------|--------|--------|--------|-------------|-------------|------------|---------------------------------------|--|--| |MX full quantization|FLOAT8_E4M3FN|FLOAT8_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 quantization|FLOAT8_E5M2|FLOAT8_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 quantization|FLOAT4_E2M1|FLOAT4_E2M1|
  • 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|

    - 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):
      - x1 does not support transposition, that is, transposeX1 cannot be set to true.
      - 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 following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

    x1 is FLOAT8_E4M3FN, x2 is FLOAT8_E4M3FN (NZ format), x1Scale is FLOAT8_E8M0, x2Scale is FLOAT8_E8M0, the activation function is gelu_tanh, and scaleAlg is 0 (use case 1).

    #include <iostream>
    #include <memory>
    #include <cmath>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_cast.h"
    #include "aclnnop/aclnn_quant_matmul_activation_quant_weight_nz.h"
    #include "aclnnop/aclnn_trans_matmul_weight.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 for 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 device memory
        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 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);
        // Compute 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 aclCreateTensor 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();
    }
    
    template <typename T>
    int CreateAclTensorX2(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                          aclDataType dataType, aclTensor** tensor)
    {
        auto size = static_cast<uint64_t>(GetShapeSize(shape));
    
        const aclIntArray* mat2Size = aclCreateIntArray(shape.data(), shape.size());
        std::unique_ptr<const aclIntArray, aclnnStatus (*)(const aclIntArray*)> mat2SizePtr(mat2Size, aclDestroyIntArray);
        auto ret = aclnnCalculateMatmulWeightSizeV2(mat2Size, dataType, &size);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCalculateMatmulWeightSizeV2 failed. ERROR: %d\n", ret); return ret);
        size *= sizeof(T);
    
        // Call aclrtMalloc to allocate device memory (aligned size)
        ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
        // Copy only the original ND data
        auto originalSize = static_cast<size_t>(GetShapeSize(shape) * sizeof(T));
        ret = aclrtMemcpy(*deviceAddr, originalSize, hostData.data(), originalSize, ACL_MEMCPY_HOST_TO_DEVICE);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
        // Clear the remaining area to prevent dirty data
        if (size > originalSize) {
            ret = aclrtMemset(static_cast<uint8_t*>(*deviceAddr) + originalSize, size - originalSize, 0, size - originalSize);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemset 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];
        }
    
        std::vector<int64_t> storageShape;
        storageShape.push_back(GetShapeSize(shape));
    
        // Call the aclCreateTensor API to create an aclTensor.
        *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                                  storageShape.data(), storageShape.size(), *deviceAddr);
        return 0;
    }
    
    int AclnnQuantMatmulWeightNzActivationQuantTest(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 the inputs and outputs, which need to be custom-built according to the API.
        int64_t m = 5;
        int64_t k = 64;
        int64_t n = 128;
        bool transposeX1 = false;
        bool transposeX2 = true;
        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 = {n, k};
        std::vector<int64_t> x1ScaleShape = {m, (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, 2};
        std::vector<int64_t> x2ScaleShape = {n, (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, 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(n * k, 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(n * (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE * 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 the 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 the x2 aclTensor in the AI processor-affine data layout format.
        ret = CreateAclTensorX2(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, and replace it with the specific API name.
        uint64_t workspaceSize = 0;
        aclOpExecutor* executor = nullptr;
        // Call the first-phase API of aclnnTransMatmulWeight.
        ret = aclnnTransMatmulWeightGetWorkspaceSize(x2, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeightGetWorkspaceSize failed. ERROR: %d\n", ret);
                  return ret);
        // Allocate device memory according to the workspaceSize calculated by the first-phase API.
        void* workspaceTransAddr = nullptr;
        std::unique_ptr<void, aclError (*)(void*)> workspaceTransAddrPtr(nullptr, aclrtFree);
        if (workspaceSize > 0) {
            ret = aclrtMalloc(&workspaceTransAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
            workspaceTransAddrPtr.reset(workspaceTransAddr);
        }
        // Call the second-phase API of aclnnTransMatmulWeight.
        ret = aclnnTransMatmulWeight(workspaceTransAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeight failed. ERROR: %d\n", ret); return ret);
    
        workspaceSize = 0;
        executor = nullptr;
        int64_t groupSizeValue = 4295032864;
        char activationType[] = "gelu_tanh";
        char quantMode[] = "mx";
        char roundMode[] = "rint";
        ret = aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize(
            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("aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
                  return ret);
        // Allocate device memory according to 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 aclnnQuantMatmulActivationQuantWeightNz.
        ret = aclnnQuantMatmulActivationQuantWeightNz(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulActivationQuantWeightNz failed. ERROR: %d\n", ret);
                  return ret);
        // 4. (Boilerplate) Synchronously wait for the task execution to complete.
        ret = aclrtSynchronizeStream(stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
        // 5. Obtain the output value and copy the result from device memory to the host side. Modify it according to 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 the device/stream. For details, see the acl API documentation.
        // Set deviceId based on the actual device in use.
        int32_t deviceId = 0;
        aclrtStream stream;
        auto ret = AclnnQuantMatmulWeightNzActivationQuantTest(deviceId, stream);
        CHECK_FREE_RET(ret == ACL_SUCCESS,
                      LOG_PRINT("AclnnQuantMatmulWeightNzActivationQuantTest failed. ERROR: %d\n", ret);
                      return ret);
        Finalize(deviceId, stream);
        return 0;
    }