aclnnQuantMatmulWeightNz

Applicable Products

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

Function

  • Description: Performs quantized matrix multiplication computation. Similar APIs include aclnnMm (matrix multiplication that supports only a 2D tensor as input) and aclnnBatchMatMul (matrix multiplication that supports only 3D tensors, where the first dimension is the batch dimension). Supports T-C, T-T, K-C, K-T, G-B, B-B, and MX quantization modes.

  • Formula:

    Atlas inference products, Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products
    • Without x1Scale and bias:
    out=x1@x2∗x2Scale+x2Offsetout = x1@x2 * x2Scale + x2Offset
    • bias INT32:
    out=(x1@x2+bias)∗x2Scale+x2Offsetout = (x1@x2 + bias) * x2Scale + x2Offset
    • With x1Scale, no bias:
    out=x1@x2∗x2Scale∗x1Scaleout = x1@x2 * x2Scale * x1Scale
    • With x1Scale, bias INT32:
    out=(x1@x2+bias)∗x2Scale∗x1Scaleout = (x1@x2 + bias) * x2Scale * x1Scale
    • With x1Scale, bias FLOAT32:
    out=x1@x2∗x2Scale∗x1Scale+biasout = x1@x2 * x2Scale * x1Scale + bias
    Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products
    • bias BFLOAT16/FLOAT32 (no x2Offset in this scenario):
    out=x1@x2∗x2Scale+biasout = x1@x2 * x2Scale + bias
    • x1Scale, no bias:
    out=x1@x2∗x2Scale∗x1Scaleout = x1@x2 * x2Scale * x1Scale
    • x1Scale, bias INT32 (this scenario has no x2Offset):
    out=(x1@x2+bias)∗x2Scale∗x1Scaleout = (x1@x2 + bias) * x2Scale * x1Scale
    • x1Scale, bias BFLOAT16/FLOAT16/FLOAT32 (this scenario has no x2Offset):
    out=x1@x2∗x2Scale∗x1Scale+biasout = x1@x2 * x2Scale * x1Scale + bias
    • x1 is INT8, x2 is INT32, x1Scale is FLOAT32, x2Scale is UINT64, and yOffset is FLOAT32:
    out=((x1@(x2∗x2Scale))+yOffset)∗x1Scaleout = ((x1 @ (x2*x2Scale)) + yOffset) * x1Scale
    Ascend 950PR&950DT products
    • G-B && B-B && MX quantization mode:out[m,n]=∑j=0kLoops−1((∑k=0gsK−1(x1Slice∗x2Slice))∗(x1Scale[m/gsM,j]∗x2Scale[j,n/gsN]))+bias[n]out[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 is a vector of length groupSizeK from row m of x1, and x2Slice is a vector of length groupSizeK from column n of x2; slicing along the K axis starts from j*groupSizeK, the value range of j is [0, kLoops), kLoops = ceil(K / groupSizeK), and K is the length of the K axis. The last slice may be shorter than groupSizeK.

Function Prototype

Each operator uses a two-phase API. Call the "aclnnQuantMatmulWeightNzGetWorkspaceSize" API first to obtain the workspace size required for the calculation and the executor that includes the calculation sub-computation stream of the operator, and then call the "aclnnQuantMatmulWeightNz" API to perform the calculation.

aclnnStatus aclnnQuantMatmulWeightNzGetWorkspaceSize(
    const aclTensor *x1,
    const aclTensor *x2,
    const aclTensor *x1Scale,
    const aclTensor *x2Scale,
    const aclTensor *yScale,
    const aclTensor *x1Offset,
    const aclTensor *x2Offset,
    const aclTensor *yOffset,
    const aclTensor *bias,
    bool             transposeX1,
    bool             transposeX2,
    int64_t          groupSize,
    aclTensor       *out,
    uint64_t        *workspaceSize,
    aclOpExecutor   **executor)
aclnnStatus aclnnQuantMatmulWeightNz(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnQuantMatmulWeightNzGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x1 Input Input x1 in the formula.
    • Supports non-contiguous tensors with the last two axes transposed. Non-contiguous tensors in other use cases are not supported.
    • When transposeX1 is false, the dimensions are: (batch, m, k), and batch may not exist.
    • When transposeX1 is true, the dimensions are: (batch, k, m), and batch may not exist.
    INT41,3, INT8, HIFLOAT81,2, FLOAT8_E4M3FN1,2, FLOAT4_E2M11,2 ND 2-6 ✓
    x2 Input Input x2 in the formula.
    • When transposeX2 is true, the dimensions are: (batch, k1, n1, n0, k0). batch may not exist. k0 = 32, n0 = 16.
    • When transposeX2 is false, the dimensions are: (batch, n1, k1, k0, n0). batch may not exist. k0 = 16, n0 = 32.
    • k in the x1 shape and k1 in the x2 shape must satisfy ceil(k / k0) = k1,
      n1 in the x2 shape and n in out must satisfy ceil(n / n0) = n1.
    INT41,3, INT8, INT321,3, HIFLOAT81,2, FLOAT4_E2M11,2, FLOAT321,2, FLOAT8_E4M3FN1,2 NZ 4-8 ✓
    x1Scale Input Optional quantization parameter, which is the input x1Scale in the formula.
    • When x1Scale is FLOAT8_E8M0, the dimensions are: (batch, m, ceil(k / 64), 2) when transposeX1 is false, and (batch, ceil(k / 64), m, 2) when transposeX1 is true. batch is the same as the batch dimension of x1.
    • When x1Scale is FLOAT32, the shape is 1D (t, ), where t = m and m is the same as the m of x1.
    FLOAT321, FLOAT8_E8M01,2 ND 1, 3-7 -
    x2Scale Input Represents the quantization parameter, which is the input x2Scale in the formula.
    • When x2Scale is FLOAT8_E8M0, each dimension is as follows: (batch, ceil(k / 64), n, 2) if transposeX2 is false, and (batch, n, ceil(k / 64), 2) if transposeX2 is true. batch must be consistent with the batch dimension of x2.
    • When x2Scale is of another dtype, the shape is 1-dimensional (t, ), where t = 1 or n, and n is consistent with the n of x2.
    • When the data types of x1 and x2 are HIFLOAT8 and x2 is in NZ format, x2Scale supports UINT64 and INT64 in the static quantization scenario, and both x1Scale and x2Scale support FLOAT32 in the dynamic quantization scenario.
    • When the original input types do not match the type combination in Constraints, call the aclnn API of the TransQuantParamV2 operator in advance to convert scale to the INT64 or UINT64 data type.
    UINT64, INT64, FLOAT321, BFLOAT161, FLOAT8_E8M01, 2, FLOAT161, 2 ND 1, 3-7 -
    yScale Input Dequantization scale parameter of output y. The shape is 2D (1, n), where n is the same as the n of x2. UINT641, 2, INT641, 2 ND 2 -
    x1Offset Input Reserved parameter. Not supported in the current version. Pass in nullptr or an empty tensor. - - - -
    x2Offset Input Optional quantization parameter, input x2Offset in the formula. shape is 1D (t, ), where t = 1 or n, and n is the same as the n of x2. FLOAT32 ND 1 -
    yOffset Input The input yOffset in the formula. - FLOAT32 ND 1 -
    bias Input Optional parameter, the input bias in the formula.
    • Supports 1D (n, ) or 3D (batch, 1, n) shape, where n is the same as the n of x2.
    • When the shape of out is 2, 4, 5, or 6 dimensions, the shape of bias supports only 1D (n, ).
    INT32, BFLOAT161, FLOAT161, FLOAT321 ND 1, 3 -
    transposeX1 Input Indicates whether the input shape of x1 contains transpose. - BOOL - - -
    transposeX2 Input Indicates whether the input shape of x2 contains transpose. - BOOL - - -
    groupSize Input Quantization group size in the m, n, and k directions for input. Consists of three values in three directions, groupSizeM, groupSizeN, and groupSizeK, concatenated together. Each value occupies 16 bits, taking up the lower 48 bits of the int64_t groupSize in total (the upper 16 bits are invalid). For the calculation formula, see Formula 1 below the table. In the use case where groupSize is not supported, pass in 0. INT64 - - -
    out Output Output out in the formula.
    • Supports shapes with 2-6 dimensions: (batch, m, n). batch may not exist.
    • Supports broadcast between the batch dimensions of x1 and x2. The output batch is the same as the batch after broadcast, m is the same as m of x1, and n satisfies ceil(n / n0) = n1 together with n1 and n0 of x2.
    FLOAT16, INT8, BFLOAT161, INT321, FLOAT321, 2 ND 2-6 -
    workspaceSize Output Returns the size of the workspace that needs to be applied by the Device side. - - - - -
    executor Output Returns the op executor, which includes the calculation flow of the operator. - - - - -
    • Formula 1:groupSize=groupSizeK∣groupSizeN<<16∣groupSizeM<<32groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32
      Atlas inference products
      • The superscript "1" in the data type column of the table above indicates a data type not supported by this series.
      • x2 does not support non-contiguous tensors.
      • yScale is not supported.
      • groupSize is not supported. Pass 0 for groupSize.
    Atlas A2 products, Atlas A3 products
    • The superscript "2" in the data type column of the table above indicates a data type not supported by this series.
    • x2 does not support non-contiguous tensors.
    • yScale is not supported.
    • groupSize is not supported. Pass 0 for groupSize.
Ascend 950PR&950DT products
  • The superscript "3" in the data type column of the table above indicates a data type not supported by this series.
  • x2 supports the non-contiguous tensor where the last two axes are transposed. The non-contiguous tensor in other scenarios is not supported.
  • Passing a non-zero value for groupSize is supported.
  • In the full quantization scenario, when m of input x1 or n of x2 is 0, the output is an empty tensor.
  • 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, x2Scale, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x1, x2, bias, x1Scale, x2Scale, x2Offset, or out is out of the supported range.
    The shape of x1, x2, bias, x1Scale, x2Scale, x2Offset, or out does not meet the check requirements.
    x1, x2, bias, x1Scale, x2Scale, x2Offset, or out is an empty tensor, and the empty tensor is not in the preceding supported empty tensor use cases.
    The input yScale, x1Offset, and yOffset are not nullptr and are not empty tensors.
    The input groupSize does not meet the check requirements.
  • aclnnQuantMatmulWeightNz

    • Parameters:

      Parameter Input/Output Description
      workspace Input Workspace memory address applied by the Device side.
      workspaceSize Input Size of the workspace applied by the Device side, obtained by calling the first-phase API aclnnQuantMatmulWeightNzGetWorkspaceSize.
      executor Input Op executor, includes the calculation sub-computation stream.
      stream Input Stream for task execution.
    • Return value

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

    Constraints

    • Deterministic computation:
      • aclnnQuantMatmulWeightNz defaults to a deterministic implementation.
    Atlas A2 products, Atlas A3 products
    • The last dimension size of x1 cannot exceed 65535. However, if the dtype of x1 and x2 is INT8, the dtype of x2Scale is FLOAT32 or BFLOAT16, and both x2Scale and x1Scale have a dimension of 1, a size greater than 65535 is supported. The last dimension of x1 refers to m when transposeX1 is true, or k when transposeX1 is false.

    • The last dimension size of x2 cannot exceed 65535. However, if the dtype of x1 and x2 is INT8, the dtype of x2Scale is FLOAT32 or BFLOAT16, and both x2Scale and x1Scale have a dimension of 1, a size greater than 65535 is supported. The last dimension of x2 refers to k when transposeX2 is true, or n when transposeX2 is false.

    • Supports calling aclnnTransMatmulWeight before this interface to process x2 in ND format, obtaining the data layout format with AI processor affinity.

    • When either of the last two dimensions of the original ND is 1, the weightNz feature cannot be used, and this API does not support such a scenario.

    • The input and output support the following data type combinations:

    | x1 | x2 | x1Scale | x2Scale | x2Offset | yOffset | Bias | Out | | ---- | ----- | ------------ | ---------------- | ------------- | ------- | --------------------------- | ----------------- | | INT8 | INT8 | null | UINT64/INT64 | null | null | null/INT32 | FLOAT16 | | INT8 | INT8 | null | UINT64/INT64 | null/FLOAT32 | null | null/INT32 | INT8 | | INT8 | INT8 | null/FLOAT32 | FLOAT32/BFLOAT16 | null | null | null/INT32/BFLOAT16/FLOAT32 | BFLOAT16 | | INT8 | INT8 | FLOAT32 | FLOAT32 | null | null | null/INT32/FLOAT16/FLOAT32 | FLOAT16 | | INT8 | INT8 | null | FLOAT32/BFLOAT16 | null | null | null/INT32 | INT32 | | INT4 | INT4 | null/FLOAT32 | BFLOAT16 | null/FLOAT32 | null | null/BFLOAT16 | BFLOAT16 | | INT4 | INT4 | null/FLOAT32 | FLOAT32 | null/FLOAT32 | null | null/BFLOAT16 | BFLOAT16 | | INT4 | INT4 | null/FLOAT32 | UINT64 | null/FLOAT32 | null | null/INT32 | FLOAT16 | | INT4 | INT4 | null/FLOAT32 | FLOAT32 | null/FLOAT32 | null | null/INT32 | FLOAT16 | | INT8 | INT32 | FLOAT32 | UINT64 | null | FLOAT32 | null | FLOAT16/BFLOAT16 |

    • Constraint on x1: When the data type is INT8 and the data type of x2 is INT32, transposeX1 must be false. Dimensions: (m, k), where k must be an even number and less than 29576.
    • Constraint on yOffset: The shape supports 1 dimension (n). It is an auxiliary result computed offline during the computation process, with the value required to be 8*x2*x2Scale, and accumulated along the first dimension.
    Atlas inference products
    • The size of the last dimension of x1 cannot exceed 65535. The last dimension of x1 refers to m when transposeX1 is true, or k when transposeX1 is false.

    • The size of the last dimension of x2 cannot exceed 65535. The last dimension of x2 refers to k when transposeX2 is true or n when transposeX2 is false.

    • Before calling this API, you can use aclnnTransMatmulWeight to process x2 in ND format to obtain the AI processor affinity data layout format.

    • When either of the last two dimensions of the original ND is 1, the weightNz feature cannot be used, and this API does not support such a scenario.

    • The input and output support the following data type combinations:

    | x1 | x2 | x1Scale | x2Scale | x2Offset | Bias | Out | | ---- | ---- | ------- | ------------ | ------------- | ------------------ | ------- | | INT8 | INT8 | null | UINT64/INT64 | null | null/INT32 | FLOAT16 | | INT8 | INT8 | null | UINT64/INT64 | null/FLOAT32 | null/INT32 | INT8 | | INT8 | INT8 | FLOAT | FLOAT | null | null/INT32/FLOAT32 | FLOAT16 |

    • When x1Scale is not null, only K-C quantization is supported.
    Ascend 950PR&950DT products
    • Before calling this API, you can use aclnnTransMatmulWeight or aclnnNpuFormatCast to process x2 in ND format to obtain the NZ format. When using it, you must pad with 0s to prevent dirty data.

    • When either of the last two dimensions of the original ND is 1, the weightNz feature cannot be used, and this API does not support such a scenario.

    • T-C Quantization && T-T Quantization Scenario Constraints:

    - The input and output support the following data type combinations:

    | x1 | x2 | x1Scale | x2Scale | x2Offset | yScale | Bias | Out | | --------------- | ----------- | ----------- | --------------- | ------------ | -------| -------------------------- | ----------------------| | INT8 | INT8 | null | UINT64/ INT64 | null | null | null/INT32 | FLOAT16/ BFLOAT16 | | INT8 | INT8 | null | UINT64/ INT64 | null/FLOAT32 | null | null/INT32 | INT8 | | INT8 | INT8 | null | FLOAT32/BFLOAT16 | null | null | null/INT32/FLOAT32/BFLOAT16| BFLOAT16 | | INT8 | INT8 | null | FLOAT32/BFLOAT16 | null | null | null/INT32 | INT32 | | HIFLOAT8 | HIFLOAT8 | null | UINT64/INT64 | null | null | null/FLOAT32 | FLOAT16/BFLOAT16/FLOAT32 | | FLOAT8_E4M3FN | FLOAT8_E4M3FN | null | UINT64/INT64 | null | null | null/FLOAT32 | FLOAT16/BFLOAT16/FLOAT32 |

    - In the T-T quantization scenario, null is passed to x1Scale, and the shape of x2Scale is (1,).
    - In the T-C quantization scenario, x1Scale is passed as null, and the shape of x2Scale is (n,), where n is consistent with n of x2.
    - Dynamic T-C or dynamic T-T quantization is not supported.
    • K-C Quantization && K-T Quantization Scenario Constraints:

    - The input and output support the following data type combinations:

    | x1 | x2 | x1Scale | x2Scale | x2Offset | yScale | Bias | Out | | -------------------- | -------------------- | ------- | --------------- | -------- | -------| ------------------------- | ------------------------- | | INT8 | INT8 | FLOAT32 | FLOAT32/BFLOAT16| null | null | null/INT32/FLOAT32/BFLOAT16 | BFLOAT16 | | INT8 | INT8 | FLOAT32 | FLOAT32 | null | null | null/INT32/FLOAT32/FLOAT16 | FLOAT16 | | FLOAT8_E4M3FN | FLOAT8_E4M3FN | FLOAT32 | FLOAT32 | null | null | null/FLOAT32 | FLOAT16/BFLOAT16/FLOAT32 | | HIFLOAT8 | HIFLOAT8 | FLOAT32 | FLOAT32 | null | null | null/FLOAT32 | FLOAT16/BFLOAT16/FLOAT32 |

    - In the K-C quantization scenario, the shape of x1Scale is (m,), and the shape of x2Scale is (n,), where m is the same as m of x1 and n is the same as n of x2.
    - In the K-T quantization scenario, the shape of x1Scale is (m,), and the shape of x2Scale is (1,), where m matches the m of x1.
    - When the data types of x1 and x2 are FLOAT8_E4M3FN and HIFLOAT8, only transA=false is supported.
    • G-B quantization && B-B quantization scenario constraints:

    - The input and output support the following data type combinations:

    | x1 | x2 | x1Scale | x2Scale | x2Offset | yScale | Bias | Out | | -------------------- | -------------------- | ------- | --------------- | -------- | -------| ------------------------- | ------------------------- | | FLOAT8_E4M3FN | FLOAT8_E4M3FN | FLOAT32 | FLOAT32 | null | null | null | FLOAT16/BFLOAT16/ FLOAT32 | | HIFLOAT8 | HIFLOAT8 | FLOAT32 | FLOAT32 | null | null | null | FLOAT16/BFLOAT16/ FLOAT32 |

    - Relationship between x1, x2, x1Scale, x2Scale, and groupSize values:

    | Quantization Type | x1 Shape | x2 Shape | x1Scale Shape | x2Scale Shape | yScale Shape | [gsM, gsN, gsK] | groupSize | |-------|--------|--------|-------------|-------------|------------|---|---| |B-B quantization|

  • non-transpose: (batch, m, k)
  • |
  • Non-transposed: (batch, k, n)
  • Transposed: (batch, n, k)
  • |
  • Non-transpose: (batch, ceil(m / 128), ceil(k / 128))
  • |
  • Non-transposed: (batch, ceil(k / 128), ceil(n / 128))
  • Transposed: (batch, ceil(n / 128), ceil(k / 128))
  • |null|[128, 128, 128]|549764202624| |G-B quantization|
  • non-transpose: (batch, m, k)
  • |
  • Non-transposed: (batch, k, n)
  • Transposed: (batch, n, k)
  • |
  • Non-transpose: (batch, m, ceil(k / 128))
  • |
  • Non-transposed: (batch, ceil(k / 128), ceil(n / 128))
  • Transposed: (batch, ceil(n / 128), ceil(k / 128))
  • |null|[1, 128, 128]|4303356032|

    - Note: In the table above, gsM, gsK, and gsN denote groupSizeM, groupSizeK, and groupSizeN respectively. Dimensions with gsM, gsK, or gsN set to 0 are automatically inferred. The table above lists the case where automatic inference is not used.
    - In the G-B quantization and B-B quantization scenarios, x1 supports only non-transpose, and the transpose attribute of x2 must be consistent with that of x2Scale (when an axis in the shape has a size of 1 and the case is not a dynamic graph NZ scenario, the transpose attributes of x and scale can be inconsistent).
    - Batch consistency: The B-B quantization scenario does not support batch consistency. Even if the batch consistency switch is enabled, the output cannot be guaranteed to meet batch consistency requirements.
    • MX quantization scenario constraints:

    - The input and output support the following data type combinations:

    | x1 | x2 | x1Scale | x2Scale | x2Offset | yScale | Bias | Out | |---------------| ------------- | ----------- | ----------- | -------- | ------ | -------------| --------------------------- | | FLOAT8_E4M3FN | FLOAT8_E4M3FN | FLOAT8_E8M0 | FLOAT8_E8M0 | null | null | null/FLOAT32 | FLOAT16/BFLOAT16/FLOAT32 | | FLOAT4_E2M1 | FLOAT4_E2M1 | FLOAT8_E8M0 | FLOAT8_E8M0 | null | null | null/FLOAT32 | FLOAT16/BFLOAT16/FLOAT32 |

    - 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 | [groupSizeM, groupSizeN, groupSizeK] | groupSize | |-------|--------|--------|--------|--------|-------------|-------------|------------|---------------------------------------|--|--| |MX full quantization|FLOAT8_E4M3FN|FLOAT8_E4M3FN|

  • non-transpose: (batch, m, k)
  • |
  • Non-transposed: (batch, k, n)
  • Transposed: (batch, n, k)
  • |
  • non-transpose: (batch, m, ceil(k / 64), 2)
  • |
  • non-transpose: (batch, ceil(k / 64), n, 2)
  • transpose: (batch, n, ceil(k / 64), 2)
  • |(n,) or (batch, 1, n)|null|[1, 1, 32]|4295032864| |MX full quantization|FLOAT4_E2M1|FLOAT4_E2M1|
  • non-transpose: (batch, m, k)
  • |
  • Non-transposed: (batch, k, n)
  • Transposed: (batch, n, k)
  • |
  • non-transpose: (batch, m, ceil(k / 64), 2)
  • |
  • non-transpose: (batch, ceil(k / 64), n, 2)
  • transpose: (batch, n, ceil(k / 64), 2)
  • |(n,) or (batch, 1, n)|null|[1, 1, 32]|4295032864|

    - In the MX full quantization scenario, when the data types of x1 and x2 are FLOAT8_E4M3FN/FLOAT4_E2M1, 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.
    - In the MX full quantization scenario, when the data types of x1 and x2 are FLOAT4_E2M1, the following conditions must be met:
      - The inner axes of x1 and x2 must be even, and k must be greater than 2.
      - transposeX1 must be false.
      - When transposeX2 is false, n must be greater than 2.
      - When transposeX2 is true, n must be greater than 1.
    • The dtype and shape requirements in pseudo-quantization scenarios are as follows:

    | Quantization Type | x1 Dtype | x2 Dtype | x1Scale Dtype | x2Scale Dtype | Bias Dtype | yScale Dtype | Out Dtype | x1 Shape | x2 Shape | x1Scale Shape | x2Scale Shape | Bias Shape | yScale Shape | [groupSizeM, groupSizeN, groupSizeK] | |---------------| ------------| -------------- |--------------|-------------|--------- | -------- |--------| ---------- | --------------| ------------ |---------- | ------------| ---------------------------------------|-------| | MX quantization |FLOAT8_E4M3FN |FLOAT4_E2M1 |FLOAT8_E8M0 |FLOAT8_E8M0 |null/BFLOAT16/FLOAT16| null |BFLOAT16/FLOAT16|(m, k) |(n, k) |(m, ceil(k / 64), 2) |(n, ceil(k / 64), 2) |(1, n) | null | [0, 0, 32] / [1, 1, 32] | | MX quantization |FLOAT8_E4M3FN |FLOAT32 |FLOAT8_E8M0 |FLOAT8_E8M0 |null/BFLOAT16/FLOAT16| null |BFLOAT16/FLOAT16|(m, k) |(n, k/8)|(m, ceil(k / 64), 2) |(n, ceil(k / 64), 2) |(1, n) | null | [0, 0, 32] / [1, 1, 32] | | T-CG quantization |FLOAT8_E4M3FN |FLOAT4_E2M1 |null |BFLOAT16/FLOAT16 |null| uint64/int64 |BFLOAT16/FLOAT16|(m, k) |(k, n) |null |(k/32, n) |null |(1, n) | [0, 0, 32] / [1, 1, 32] | | T-CG quantization |FLOAT8_E4M3FN |FLOAT32 |null |BFLOAT16/FLOAT16 |null| uint64/int64 |BFLOAT16/FLOAT16|(m, k) |(k, n/8)|null |(k/32, n) |null |(1, n) | [0, 0, 32] / [1, 1, 32] |

    - Constraints:
      - In MX quantization mode, k must be 8-aligned and n must be 8-aligned.
      - In the T-CG quantization mode, k must be aligned to 32 and greater than or equal to 64, and n must be aligned to 8.
      - When x1 is FLOAT8_E4M3FN and x2 is FLOAT32, x2 indicates a tightly packed data format in which one FLOAT32 stores 8 FLOAT4_E2M1 values.
      - In the MX quantization mode, the data type of bias must be the same as that of out; in the T-CG quantization mode, the data type of x2Scale must be the same as that of out.

    Example

    The sample code is as follows, for reference only. For details about compilation and execution, see Compile and Run Samples.

    • Ascend 950PR&950DT products: In the MM_MX_A8W4 scenario, call aclnnWeightQuantPreprocess first to synchronously preprocess weight and weightScale, and then call this interface to perform matrix multiplication.

      #include <cstring>
      #include <iostream>
      #include <memory>
      #include <vector>
      
      #include "acl/acl.h"
      #include "aclnn/opdev/float4_e2m1.h"
      #include "aclnnop/aclnn_quant_matmul_weight_nz.h"
      #include "aclnnop/aclnn_weight_quant_preprocess.h"
      
      #define CHECK_RET(cond, return_expr) \
          do {                             \
              if (!(cond)) {               \
                  return_expr;             \
              }                            \
          } while (0)
      
      #define LOG_PRINT(message, ...)         \
          do {                                \
              printf(message, ##__VA_ARGS__); \
          } while (0)
      
      #define CEIL_DIV(x, y) (((x) + (y) - 1) / (y))
      
      int64_t GetShapeSize(const std::vector<int64_t>& shape)
      {
          int64_t shapeSize = 1;
          for (auto dim : shape) {
              shapeSize *= dim;
          }
          return shapeSize;
      }
      
      class AclRuntimeGuard {
      public:
          explicit AclRuntimeGuard(int32_t deviceId) : deviceId_(deviceId) {}
      
          ~AclRuntimeGuard()
          {
              if (stream_ != nullptr) {
                  aclrtDestroyStream(stream_);
              }
              if (deviceSet_) {
                  aclrtResetDevice(deviceId_);
              }
              if (aclInited_) {
                  aclFinalize();
              }
          }
      
          int Init(aclrtStream* stream)
          {
              auto ret = aclInit(nullptr);
              CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
              aclInited_ = true;
      
              ret = aclrtSetDevice(deviceId_);
              CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
              deviceSet_ = true;
      
              ret = aclrtCreateStream(stream);
              CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
              stream_ = *stream;
              return ACL_SUCCESS;
          }
      
      private:
          int32_t deviceId_;
          aclrtStream stream_ = nullptr;
          bool aclInited_ = false;
          bool deviceSet_ = false;
      };
      
      template <typename T>
      int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& viewShape,
                          const std::vector<int64_t>& viewStrides, const std::vector<int64_t>& storageShape,
                          aclDataType dataType, aclFormat format, void** deviceAddr, aclTensor** tensor)
      {
          auto size = hostData.size() * sizeof(T);
          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);
      
          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);
      
          const int64_t* strides = viewStrides.empty() ? nullptr : viewStrides.data();
          *tensor = aclCreateTensor(viewShape.data(), viewShape.size(), dataType, strides, 0, format, storageShape.data(),
                                    storageShape.size(), *deviceAddr);
          CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed.\n"); return ACL_ERROR_INVALID_PARAM);
          return ACL_SUCCESS;
      }
      
      std::vector<uint8_t> PackFp4(const std::vector<float>& data)
      {
          std::vector<uint8_t> packedData((data.size() + 1) / 2, 0);
          for (size_t i = 0; i < data.size(); i += 2) {
              uint8_t low = op::Float4E2M1(data[i]).value;
              uint8_t high = i + 1 < data.size() ? op::Float4E2M1(data[i + 1]).value : 0;
              packedData[i / 2] = static_cast<uint8_t>((high << 4) | low);
          }
          return packedData;
      }
      
      float Bf16ToFloat(uint16_t value)
      {
          uint32_t bits = static_cast<uint32_t>(value) << 16;
          float result;
          std::memcpy(&result, &bits, sizeof(result));
          return result;
      }
      
      int AclnnQuantMatmulWeightNzA8W4PreprocessTest(int32_t deviceId)
      {
          aclrtStream stream = nullptr;
          AclRuntimeGuard runtime(deviceId);
          auto ret = runtime.Init(&stream);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
      
          const int64_t m = 5;
          const int64_t k = 64;
          const int64_t n = 128;
          const int64_t kGroupSize = 32;
          const int64_t scaleK = CEIL_DIV(k, 64);
          const bool transposeX1 = false;
          const bool transposeX2 = false;
      
          std::vector<int64_t> x1Shape = {m, k};
          std::vector<int64_t> x1Strides = {k, 1};
          std::vector<int64_t> weightViewShape = {k, n};
          std::vector<int64_t> weightStorageShape = {n, k};
          std::vector<int64_t> weightStrides = {1, k};
          std::vector<int64_t> x1ScaleShape = {m, scaleK, 2};
          std::vector<int64_t> x1ScaleStrides = {scaleK * 2, 2, 1};
          std::vector<int64_t> weightScaleViewShape = {scaleK, n, 2};
          std::vector<int64_t> weightScaleStorageShape = {n, scaleK, 2};
          std::vector<int64_t> weightScaleStrides = {2, scaleK * 2, 1};
          std::vector<int64_t> outWeightStorageShape = {CEIL_DIV(k, 32), CEIL_DIV(n, 16), 16, 32};
          std::vector<int64_t> outShape = {m, n};
          std::vector<int64_t> outStrides = {n, 1};
      
          std::vector<uint8_t> x1HostData(GetShapeSize(x1Shape), 0b00111000); // FLOAT8_E4M3FN 1.0
          std::vector<float> weightFloatData(GetShapeSize(weightStorageShape), 1.0f);
          std::vector<uint8_t> weightHostData = PackFp4(weightFloatData);
          std::vector<uint8_t> x1ScaleHostData(GetShapeSize(x1ScaleShape), 0b01111111); // FLOAT8_E8M0 1.0
          std::vector<uint8_t> weightScaleHostData(GetShapeSize(weightScaleStorageShape),
                                                   0b10000101); // FLOAT8_E8M0 64.0
          std::vector<uint8_t> outWeightHostData(GetShapeSize(outWeightStorageShape) / 2, 0);
          std::vector<uint8_t> outWeightScaleHostData(GetShapeSize(weightScaleStorageShape), 0);
          std::vector<uint16_t> outHostData(GetShapeSize(outShape), 0);
      
          void* x1DeviceAddr = nullptr;
          void* weightDeviceAddr = nullptr;
          void* x1ScaleDeviceAddr = nullptr;
          void* weightScaleDeviceAddr = nullptr;
          void* outWeightDeviceAddr = nullptr;
          void* outWeightScaleDeviceAddr = nullptr;
          void* outDeviceAddr = nullptr;
          aclTensor* x1 = nullptr;
          aclTensor* weight = nullptr;
          aclTensor* x1Scale = nullptr;
          aclTensor* weightScale = nullptr;
          aclTensor* outWeight = nullptr;
          aclTensor* outWeightScale = nullptr;
          aclTensor* out = nullptr;
      
          ret = CreateAclTensor(x1HostData, x1Shape, x1Strides, x1Shape, ACL_FLOAT8_E4M3FN, ACL_FORMAT_ND, &x1DeviceAddr,
                                &x1);
          std::unique_ptr<void, aclError (*)(void*)> x1DeviceAddrPtr(x1DeviceAddr, aclrtFree);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x1Ptr(x1, aclDestroyTensor);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
      
          ret = CreateAclTensor(weightHostData, weightViewShape, weightStrides, weightStorageShape, ACL_FLOAT4_E2M1,
                                ACL_FORMAT_ND, &weightDeviceAddr, &weight);
          std::unique_ptr<void, aclError (*)(void*)> weightDeviceAddrPtr(weightDeviceAddr, aclrtFree);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> weightPtr(weight, aclDestroyTensor);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
      
          ret = CreateAclTensor(x1ScaleHostData, x1ScaleShape, x1ScaleStrides, x1ScaleShape, ACL_FLOAT8_E8M0, ACL_FORMAT_ND,
                                &x1ScaleDeviceAddr, &x1Scale);
          std::unique_ptr<void, aclError (*)(void*)> x1ScaleDeviceAddrPtr(x1ScaleDeviceAddr, aclrtFree);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x1ScalePtr(x1Scale, aclDestroyTensor);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
      
          ret = CreateAclTensor(weightScaleHostData, weightScaleViewShape, weightScaleStrides, weightScaleStorageShape,
                                ACL_FLOAT8_E8M0, ACL_FORMAT_ND, &weightScaleDeviceAddr, &weightScale);
          std::unique_ptr<void, aclError (*)(void*)> weightScaleDeviceAddrPtr(weightScaleDeviceAddr, aclrtFree);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> weightScalePtr(weightScale, aclDestroyTensor);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
      
          // Retain the transpose stride of weight so that QuantMatmul can identify the transposed layout from tensor metadata when transposeX2=false.
          ret = CreateAclTensor(outWeightHostData, weightViewShape, weightStrides, outWeightStorageShape, ACL_FLOAT4_E2M1,
                                ACL_FORMAT_FRACTAL_NZ_C0_32, &outWeightDeviceAddr, &outWeight);
          std::unique_ptr<void, aclError (*)(void*)> outWeightDeviceAddrPtr(outWeightDeviceAddr, aclrtFree);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> outWeightPtr(outWeight, aclDestroyTensor);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
      
          ret = CreateAclTensor(outWeightScaleHostData, weightScaleViewShape, weightScaleStrides, weightScaleStorageShape,
                                ACL_FLOAT8_E8M0, ACL_FORMAT_ND, &outWeightScaleDeviceAddr, &outWeightScale);
          std::unique_ptr<void, aclError (*)(void*)> outWeightScaleDeviceAddrPtr(outWeightScaleDeviceAddr, aclrtFree);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> outWeightScalePtr(outWeightScale, aclDestroyTensor);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
      
          ret = CreateAclTensor(outHostData, outShape, outStrides, outShape, ACL_BF16, ACL_FORMAT_ND, &outDeviceAddr, &out);
          std::unique_ptr<void, aclError (*)(void*)> outDeviceAddrPtr(outDeviceAddr, aclrtFree);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> outPtr(out, aclDestroyTensor);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
      
          uint64_t workspaceSize = 0;
          aclOpExecutor* executor = nullptr;
          ret = aclnnWeightQuantPreprocessGetWorkspaceSize(weight, weightScale, nullptr, nullptr, ACL_FLOAT8_E4M3FN,
                                                           ACL_FLOAT8_E8M0, kGroupSize, outWeight, outWeightScale, nullptr,
                                                           nullptr, &workspaceSize, &executor);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantPreprocessGetWorkspaceSize failed. ERROR: %d\n", ret);
                    return ret);
      
          void* preprocessWorkspaceAddr = nullptr;
          std::unique_ptr<void, aclError (*)(void*)> preprocessWorkspacePtr(nullptr, aclrtFree);
          if (workspaceSize > 0) {
              ret = aclrtMalloc(&preprocessWorkspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
              CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate preprocess workspace failed. ERROR: %d\n", ret); return ret);
              preprocessWorkspacePtr.reset(preprocessWorkspaceAddr);
          }
      
          ret = aclnnWeightQuantPreprocess(preprocessWorkspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantPreprocess failed. ERROR: %d\n", ret); return ret);
          ret = aclrtSynchronizeStream(stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream after preprocess failed. ERROR: %d\n", ret);
                    return ret);
      
          workspaceSize = 0;
          executor = nullptr;
          // The output of WeightQuantPreprocess already meets the QuantMatmul input requirements and can be directly used as x2 and x2Scale.
          ret = aclnnQuantMatmulWeightNzGetWorkspaceSize(x1, outWeight, x1Scale, outWeightScale, nullptr, nullptr, nullptr,
                                                         nullptr, nullptr, transposeX1, transposeX2, kGroupSize, out,
                                                         &workspaceSize, &executor);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
                    return ret);
      
          void* matmulWorkspaceAddr = nullptr;
          std::unique_ptr<void, aclError (*)(void*)> matmulWorkspacePtr(nullptr, aclrtFree);
          if (workspaceSize > 0) {
              ret = aclrtMalloc(&matmulWorkspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
              CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate matmul workspace failed. ERROR: %d\n", ret); return ret);
              matmulWorkspacePtr.reset(matmulWorkspaceAddr);
          }
      
          ret = aclnnQuantMatmulWeightNz(matmulWorkspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNz failed. ERROR: %d\n", ret); return ret);
          ret = aclrtSynchronizeStream(stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream after matmul failed. ERROR: %d\n", ret);
                    return ret);
      
          std::vector<uint16_t> resultData(GetShapeSize(outShape), 0);
          ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
                            resultData.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 (size_t i = 0; i < resultData.size(); ++i) {
              LOG_PRINT("result[%zu] is: %.1f\n", i, Bf16ToFloat(resultData[i]));
          }
          return ACL_SUCCESS;
      }
      
      int main()
      {
          // WeightQuantPreprocess currently supports only <term>Ascend 950PR&950DT products</term>.
          int32_t deviceId = 0;
          auto ret = AclnnQuantMatmulWeightNzA8W4PreprocessTest(deviceId);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("AclnnQuantMatmulWeightNzA8W4PreprocessTest failed. ERROR: %d\n", ret);
                    return ret);
          return 0;
      }
    • Atlas A2 products, Atlas A3 products:

      The following is sample code for the scenario where x2 is in NZ format (transposeX2=false).

      #include <iostream>
      #include <memory>
      #include <vector>
      
      #include "acl/acl.h"
      #include "aclnnop/aclnn_permute.h"
      #include "aclnnop/aclnn_quant_matmul_weight_nz.h"
      #include "aclnnop/aclnn_trans_matmul_weight.h"
      #include "aclnnop/aclnn_trans_quant_param_v2.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, 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);
      
          // 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();
      }
      
      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());
          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
          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 the host-side data to the device-side 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];
          }
      
          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 aclnnQuantMatmulWeightNzTest(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 input and output. Customize the construction based on the API.
          std::vector<int64_t> x1Shape = {5, 32};
          std::vector<int64_t> x2Shape = {32, 32};
          std::vector<int64_t> biasShape = {32};
          std::vector<int64_t> offsetShape = {32};
          std::vector<int64_t> scaleShape = {32};
          std::vector<int64_t> outShape = {5, 32};
          void *x1DeviceAddr = nullptr;
          void *x2DeviceAddr = nullptr;
          void *scaleDeviceAddr = nullptr;
          void *quantParamDeviceAddr = nullptr;
          void *offsetDeviceAddr = nullptr;
          void *biasDeviceAddr = nullptr;
          void *outDeviceAddr = nullptr;
          aclTensor *x1 = nullptr;
          aclTensor *x2 = nullptr;
          aclTensor *bias = nullptr;
          aclTensor *scale = nullptr;
          aclTensor *quantParam = nullptr;
          aclTensor *offset = nullptr;
          aclTensor *out = nullptr;
          std::vector<int8_t> x1HostData(5 * 32, 1);
          std::vector<int8_t> x2HostData(32 * 32, 1);
          std::vector<int32_t> biasHostData(32, 1);
          std::vector<float> scaleHostData(32, 1);
          std::vector<float> offsetHostData(32, 1);
          std::vector<uint16_t> outHostData(5 * 32, 1);  // Actually in float16 half-precision mode.
          // Create the x1 aclTensor.
          ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_INT8, &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 NZ format.
          ret = CreateAclTensorX2(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_INT8, &x2);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> x2HPTensorPtr(x2, aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> x2HPDeviceAddrPtr(x2DeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create the scale aclTensor.
          ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> scaleTensorPtr(scale, aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> scaleDeviceAddrPtr(scaleDeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create the quantParam aclTensor.
          ret = CreateAclTensor(scaleHostData, scaleShape, &quantParamDeviceAddr, aclDataType::ACL_UINT64, &quantParam);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> quantParamTensorPtr(quantParam,
                                                                                            aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> quantParamDeviceAddrPtr(quantParamDeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create the offset aclTensor.
          ret = CreateAclTensor(offsetHostData, offsetShape, &offsetDeviceAddr, aclDataType::ACL_FLOAT, &offset);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> offsetTensorPtr(offset, aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> offsetDeviceAddrPtr(offsetDeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create the bias aclTensor.
          ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_INT32, &bias);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> biasTensorPtr(bias, aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> biasDeviceAddrPtr(biasDeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create the out aclTensor.
          ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &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);
          bool transposeX1 = false;
          bool transposeX2 = false;
      
          // 3. Call the CANN operator library API, and replace it with the actual API name.
          uint64_t workspaceSize = 0;
          aclOpExecutor *executor;
          void *workspaceAddr = 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 based on the workspaceSize computed by the first-phase API.
          std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtrTrans(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);
              workspaceAddrPtrTrans.reset(workspaceAddr);
          }
          // Call the second-phase API of aclnnTransMatmulWeight.
          ret = aclnnTransMatmulWeight(workspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeight failed. ERROR: %d\n", ret); return ret);
      
          // For a scale of the FLOAT data type, the aclnn API of the TransQuantParamV2 operator must be called in advance.
          // Call the first-phase API of aclnnTransQuantParamV2.
          ret = aclnnTransQuantParamV2GetWorkspaceSize(scale, offset, quantParam, &workspaceSize, &executor);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransQuantParamV2GetWorkspaceSize failed. ERROR: %d\n", ret);
                    return ret);
          // Allocate device memory based on the workspaceSize computed by the first-phase API.
          workspaceAddr = nullptr;
          std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtrV2(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);
              workspaceAddrPtrV2.reset(workspaceAddr);
          }
          // Call the second-phase API of aclnnTransQuantParamV2.
          ret = aclnnTransQuantParamV2(workspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransQuantParamV2 failed. ERROR: %d\n", ret); return ret);
      
          // Call the aclnnQuantMatmulWeightNz first-phase API.
          workspaceSize = 0;
          ret = aclnnQuantMatmulWeightNzGetWorkspaceSize(x1, x2, nullptr, quantParam, nullptr, nullptr, nullptr, nullptr,
                                                        bias, transposeX1, transposeX2, 0, out, &workspaceSize,
                                                        &executor);
      
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
                    return ret);
          // Allocate device memory based on the workspaceSize calculated by the first-phase API.
      
          std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtrNZ(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);
              workspaceAddrPtrNZ.reset(workspaceAddr);
          }
          // Call the aclnnQuantMatmulWeightNz second-phase API.
          ret = aclnnQuantMatmulWeightNz(workspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNz failed. ERROR: %d\n", ret); return ret);
      
          // 4. (boilerplate) Wait synchronously 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 the device memory to the host memory. Modify the code according to the API definition.
          auto size = GetShapeSize(outShape);
          std::vector<uint16_t> resultData(
              size, 0);  // uint16_t stores the raw bit pattern of FP16; the bit pattern is printed as an integer below. To print the floating-point value, decode it to float in FP16 format first.
          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: %u\n", i, resultData[i]);
          }
          return ACL_SUCCESS;
      }
      
      int main()
      {
          // 1. (boilerplate) Initialize device/stream. For details, see the acl API manual.
          // Set deviceId based on the actual device.
          int32_t deviceId = 0;
          aclrtStream stream;
          auto ret = aclnnQuantMatmulWeightNzTest(deviceId, stream);
          CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNzTest failed. ERROR: %d\n", ret);
                        return ret);
      
          Finalize(deviceId, stream);
          return 0;
      }
    • Atlas inference products: The following is the sample code for the scenario where x2 is in NZ format (transposeX2=true).

      #include <iostream>
      #include <memory>
      #include <vector>
      
      #include "acl/acl.h"
      #include "aclnnop/aclnn_permute.h"
      #include "aclnnop/aclnn_quant_matmul_weight_nz.h"
      #include "aclnnop/aclnn_trans_matmul_weight.h"
      #include "aclnnop/aclnn_trans_quant_param_v2.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) Initialize resources.
          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 side.
          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 data on the host side to the memory on the device side.
          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 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();
      }
      
      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());
          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 memory on the device side.
          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 data on the host side to the memory on the device side.
          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];
          }
      
          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 aclnnQuantMatmulWeightNzTest(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 input and output, which need to be customized according to the API.
          std::vector<int64_t> x1Shape = {5, 32};
          std::vector<int64_t> x2Shape = {32, 32};
          std::vector<int64_t> x2TransposedShape = {32, 32};
          std::vector<int64_t> biasShape = {32};
          std::vector<int64_t> offsetShape = {32};
          std::vector<int64_t> scaleShape = {32};
          std::vector<int64_t> outShape = {5, 32};
          void *x1DeviceAddr = nullptr;
          void *x2DeviceAddr = nullptr;
          void *x2TransposedDeviceAddr = nullptr;
          void *scaleDeviceAddr = nullptr;
          void *quantParamDeviceAddr = nullptr;
          void *offsetDeviceAddr = nullptr;
          void *biasDeviceAddr = nullptr;
          void *outDeviceAddr = nullptr;
          aclTensor *x1 = nullptr;
          aclTensor *x2 = nullptr;
          aclTensor *x2Transposed = nullptr;
          aclTensor *bias = nullptr;
          aclTensor *scale = nullptr;
          aclTensor *quantParam = nullptr;
          aclTensor *offset = nullptr;
          aclTensor *out = nullptr;
          std::vector<int8_t> x1HostData(5 * 32, 1);
          std::vector<int8_t> x2HostData(32 * 32, 1);
          std::vector<int8_t> x2TransposedHostData(32 * 32, 1);
          std::vector<int32_t> biasHostData(32, 1);
          std::vector<float> scaleHostData(32, 1);
          std::vector<float> offsetHostData(32, 1);
          std::vector<uint16_t> outHostData(5 * 32, 1);  // Actually in float16 half-precision format.
          // Create x1 aclTensor.
          ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_INT8, &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 in NZ format.
          ret = CreateAclTensorX2(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_INT8, &x2);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> x2HPTensorPtr(x2, aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> x2HPDeviceAddrPtr(x2DeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create x2Transposed aclTensor in NZ format.
          ret = CreateAclTensorX2(x2TransposedHostData, x2TransposedShape, &x2TransposedDeviceAddr,
                                  aclDataType::ACL_INT8, &x2Transposed);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> x2TransposedHPTensorPtr(x2Transposed,
                                                                                                aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> x2TransposedHPDeviceAddrPtr(x2TransposedDeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create scale aclTensor.
          ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> scaleTensorPtr(scale, aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> scaleDeviceAddrPtr(scaleDeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create quantParam aclTensor.
          ret = CreateAclTensor(scaleHostData, scaleShape, &quantParamDeviceAddr, aclDataType::ACL_UINT64, &quantParam);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> quantParamTensorPtr(quantParam,
                                                                                            aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> quantParamDeviceAddrPtr(quantParamDeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create offset aclTensor.
          ret = CreateAclTensor(offsetHostData, offsetShape, &offsetDeviceAddr, aclDataType::ACL_FLOAT, &offset);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> offsetTensorPtr(offset, aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> offsetDeviceAddrPtr(offsetDeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create bias aclTensor.
          ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_INT32, &bias);
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> biasTensorPtr(bias, aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void *)> biasDeviceAddrPtr(biasDeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, return ret);
          // Create out aclTensor.
          ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &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);
          bool transposeX1 = false;
          bool transposeX2 = true;
      
          // 3. Call CANN operator library APIs. Replace with the actual API name.
          uint64_t workspaceSize = 0;
          aclOpExecutor *executor;
          void *workspaceAddr = nullptr;
      
          // The shape of x2 needs to be transposed to the nk format before transdata.
          std::vector<int64_t> dimsData = {1, 0};
          // Create the dims aclIntArray.
          aclIntArray *dims = aclCreateIntArray(dimsData.data(), dimsData.size());
          // Call the first-phase API of aclnnPermute.
          ret = aclnnPermuteGetWorkspaceSize(x2, dims, x2Transposed, &workspaceSize, &executor);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnPermuteGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
          // Allocate device memory using the workspaceSize calculated by the first-phase API.
          std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtrPermute(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);
              workspaceAddrPtrPermute.reset(workspaceAddr);
          }
          // Call the second-phase API of aclnnPermute.
          ret = aclnnPermute(workspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnPermute failed. ERROR: %d\n", ret); return ret);
      
          workspaceSize = 0;
          // Call the first-phase API of aclnnTransMatmulWeight.
          ret = aclnnTransMatmulWeightGetWorkspaceSize(x2Transposed, &workspaceSize, &executor);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeightGetWorkspaceSize failed. ERROR: %d\n", ret);
                    return ret);
          // Allocate device memory using the workspaceSize calculated by the first-phase API.
          std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtrTrans(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);
              workspaceAddrPtrTrans.reset(workspaceAddr);
          }
          // Call the second-phase API of aclnnTransMatmulWeight.
          ret = aclnnTransMatmulWeight(workspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeight failed. ERROR: %d\n", ret); return ret);
      
          // For the scale of the FLOAT data type, the aclnn API of the TransQuantParamV2 operator must be called in advance.
          // Call the first-phase API of aclnnTransQuantParamV2.
          ret = aclnnTransQuantParamV2GetWorkspaceSize(scale, offset, quantParam, &workspaceSize, &executor);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransQuantParamV2GetWorkspaceSize failed. ERROR: %d\n", ret);
                    return ret);
          // Allocate device memory using the workspaceSize calculated by the first-phase API.
          workspaceAddr = nullptr;
          std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtrV2(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);
              workspaceAddrPtrV2.reset(workspaceAddr);
          }
          // Call the second-phase API aclnnTransQuantParamV2.
          ret = aclnnTransQuantParamV2(workspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransQuantParamV2 failed. ERROR: %d\n", ret); return ret);
      
          // Call the first-phase API aclnnQuantMatmulWeightNz.
          workspaceSize = 0;
          ret = aclnnQuantMatmulWeightNzGetWorkspaceSize(x1, x2Transposed, nullptr, quantParam, nullptr, nullptr,
                                                        nullptr, nullptr, bias, transposeX1, transposeX2, 0, out,
                                                        &workspaceSize, &executor);
      
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
                    return ret);
          // Allocate device memory based on the workspaceSize calculated by the first-phase API.
      
          std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtrNZ(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);
              workspaceAddrPtrNZ.reset(workspaceAddr);
          }
          // Call the second-phase API aclnnQuantMatmulWeightNz.
          ret = aclnnQuantMatmulWeightNz(workspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNz failed. ERROR: %d\n", ret); return ret);
      
          // 4. (Boilerplate) Synchronize and wait for 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, copy the result from device memory to host memory, and modify it according to the definition of the specific API.
          auto size = GetShapeSize(outShape);
          std::vector<uint16_t> resultData(
              size, 0);  // uint16_t stores the raw FP16 bit pattern; the bit pattern is printed below as an integer. To print a floating-point value, decode it to a float in FP16 format first.
          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: %u\n", i, resultData[i]);
          }
          return ACL_SUCCESS;
      }
      
      int main()
      {
          // 1. (Boilerplate) Initialize device/stream. For details, see the acl API manual.
          // Set deviceId based on the actual device.
          int32_t deviceId = 0;
          aclrtStream stream;
          auto ret = aclnnQuantMatmulWeightNzTest(deviceId, stream);
          CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNzTest failed. ERROR: %d\n", ret);
                        return ret);
      
          Finalize(deviceId, stream);
          return 0;
      }
    • Ascend 950PR&950DT products: The following is the sample code for the scenario where x2 is in NZ format (transposeX2=true).

      #include <cstring>
      #include <iostream>
      #include <memory>
      #include <vector>
      #include "acl/acl.h"
      #include "aclnnop/aclnn_npu_format_cast.h"
      #include "aclnnop/aclnn_quant_matmul_weight_nz.h"
      #include "aclnn/opdev/float4_e2m1.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, 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 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);
          CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed.\n"); return ACL_ERROR_INVALID_PARAM);
          return 0;
      }
      
      void Finalize(int32_t deviceId, aclrtStream stream)
      {
          aclrtDestroyStream(stream);
          aclrtResetDevice(deviceId);
          aclFinalize();
      }
      
      // Convert the uint16_t representation of bfloat16 to the float representation.
      float Bf16ToFloat(uint16_t h)
      {
          uint32_t sign = (h & 0x8000U) ? 0x80000000U : 0x00000000U; // sign bit
          uint32_t exponent = (h >> 7) & 0x00FFU;                    // exponent bits
          uint32_t mantissa = h & 0x007FU;                           // mantissa bits
          // The exponent offset remains unchanged.
          // Shift the mantissa left by 23 - 7, and pad the rest with 0s.
          uint32_t fBits = sign | (exponent << 23) | (mantissa << (23 - 7));
          // Use memcpy to avoid strict aliasing violations.
          float result;
          std::memcpy(&result, &fBits, sizeof(float));
          return result;
      }
      
      uint64_t GetStorageTensorSize(const int64_t* storageShape, uint64_t storageShapeSize, aclDataType dataType)
      {
          uint64_t elementCount = 1;
          for (uint64_t i = 0; i < storageShapeSize; ++i) {
              elementCount *= static_cast<uint64_t>(storageShape[i]);
          }
          if (dataType == aclDataType::ACL_FLOAT) {
              return elementCount * sizeof(float);
          }
          if (dataType == aclDataType::ACL_FLOAT4_E2M1) {
              return (elementCount + 1) / 2;
          }
          return 0;
      }
      
      int CreateAclTensorFp4(const std::vector<float>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                             aclTensor** tensor)
      {
          auto elementCount = GetShapeSize(shape);
          auto size = (elementCount + 1) / 2;
          std::vector<uint8_t> packedData(size, 0);
          for (int64_t i = 0; i < elementCount; i += 2) {
              uint8_t low = op::Float4E2M1(hostData[i]).value;
              uint8_t high = (i + 1 < elementCount) ? op::Float4E2M1(hostData[i + 1]).value : 0;
              packedData[i / 2] = (high << 4) | low;
          }
          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);
          ret = aclrtMemcpy(*deviceAddr, size, packedData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
      
          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];
          }
          *tensor = aclCreateTensor(shape.data(), shape.size(), aclDataType::ACL_FLOAT4_E2M1, strides.data(), 0,
                                    aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(), *deviceAddr);
          CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed.\n"); return ACL_ERROR_INVALID_PARAM);
          return 0;
      }
      
      int CreateAclTensorWithFormat(const std::vector<int64_t>& shape, int64_t** storageShape, uint64_t* storageShapeSize,
                                    void** deviceAddr, aclDataType dataType, aclTensor** tensor, aclFormat format)
      {
          auto size = GetStorageTensorSize(*storageShape, *storageShapeSize, dataType);
          CHECK_RET(size > 0, LOG_PRINT("unsupported data type. ERROR: %d\n", static_cast<int>(dataType));
                    return ACL_ERROR_INVALID_PARAM);
          // 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);
          std::vector<uint8_t> hostData(size, 0);
          // Call aclrtMemcpy to copy host-side data to the device-side 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];
          }
      
          *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, format, *storageShape,
                                    *storageShapeSize, *deviceAddr);
          CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed.\n"); return ACL_ERROR_INVALID_PARAM);
          return 0;
      }
      
      int aclnnQuantMatmulWeightNzTest(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. They 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;
          int64_t groupSize = 32;
          int64_t numGroups = (k + groupSize - 1) / groupSize;
          int64_t scaleMidDim = (numGroups + 1) / 2;
          std::vector<int64_t> x1Shape = {m, k};
          std::vector<int64_t> x2Shape = {n, k};
          std::vector<int64_t> x1ScaleShape = {m, scaleMidDim, 2};
          std::vector<int64_t> x2ScaleShape = {n, scaleMidDim, 2};
          std::vector<int64_t> outShape = {m, n};
          void* x1DeviceAddr = nullptr;
          void* x2DeviceAddr = nullptr;
          void* x2NzFp4DeviceAddr = nullptr;
          void* x1ScaleDeviceAddr = nullptr;
          void* x2ScaleDeviceAddr = nullptr;
          void* outDeviceAddr = nullptr;
          aclTensor* x1 = nullptr;
          aclTensor* x2 = nullptr;
          aclTensor* x1Scale = nullptr;
          aclTensor* x2Scale = nullptr;
          aclTensor* bias = nullptr;
          aclTensor* out = nullptr;
          std::vector<uint8_t> x1HostData(m * k, 0b00111000);                    // 1.0 in float8_e4m3
          std::vector<float> x2HostData(n * k, 1);                               // Input is fp32, packed into fp4 and then converted to Nz.
          std::vector<uint8_t> x1ScaleHostData(m * scaleMidDim * 2, 0b01111111); // 1.0 in float8_e8m0
          std::vector<uint8_t> x2ScaleHostData(n * scaleMidDim * 2,
                                               0b10000101); // 1.0 * 64 in float8_e8m0. Per the documentation, the input needs to be scaled up by 64x.
          std::vector<uint16_t> outHostData(m * n, 0);      // Actually bfloat16
          int64_t* dstShape = nullptr;
          uint64_t dstShapeSize = 0;
          aclTensor* x2NzFp4 = nullptr;
          int actualFormat;
      
          // 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 (directly constructed in fp4_e2m1 ND format).
          ret = CreateAclTensorFp4(x2HostData, x2Shape, &x2DeviceAddr, &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 the 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 the 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 the out aclTensor.
          ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_BF16, &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);
      
          // 3. Call the CANN operator library API. Change it to the specific API name.
          uint64_t workspaceSize = 0;
          aclOpExecutor* executor = nullptr;
          // x2 is already in fp4_e2m1 ND format; use NpuFormatCast to convert it to fp4 NZ format.
          // Use ACL_FLOAT8_E4M3FN to infer C0=32, which matches the Ascend-affine format of fp4.
          aclDataType additionalDtype = aclDataType::ACL_FLOAT8_E4M3FN;
          ret = aclnnNpuFormatCastCalculateSizeAndFormat(x2, 29, additionalDtype, &dstShape, &dstShapeSize, &actualFormat);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCastCalculateSizeAndFormat failed. ERROR: %d\n", ret);
                    return ret);
      
          // Create the output tensor in fp4 NZ format.
          ret = CreateAclTensorWithFormat(x2Shape, &dstShape, &dstShapeSize, &x2NzFp4DeviceAddr, aclDataType::ACL_FLOAT4_E2M1,
                                          &x2NzFp4, static_cast<aclFormat>(actualFormat));
          std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x2NzFp4TensorPtr(x2NzFp4, aclDestroyTensor);
          std::unique_ptr<void, aclError (*)(void*)> x2NzFp4DeviceAddrPtr(x2NzFp4DeviceAddr, aclrtFree);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("CreateAclTensorWithFormat failed. ERROR: %d\n", ret); return ret);
      
          // Call aclnnNpuFormatCast to directly convert x2 from fp32 ND to fp4 NZ.
          ret = aclnnNpuFormatCastGetWorkspaceSize(x2, x2NzFp4, &workspaceSize, &executor);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
          // Allocate device memory based on the workspaceSize calculated by the first-phase API.
          void* workspaceNzAddr = nullptr;
          std::unique_ptr<void, aclError (*)(void*)> workspaceNzAddrPtr(nullptr, aclrtFree);
          if (workspaceSize > 0) {
              ret = aclrtMalloc(&workspaceNzAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
              CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
              workspaceNzAddrPtr.reset(workspaceNzAddr);
          }
      
          // Call the second-phase API of aclnnNpuFormatCast.
          ret = aclnnNpuFormatCast(workspaceNzAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCast failed. ERROR: %d\n", ret); return ret);
      
          // 4. (boilerplate) Wait synchronously for the task execution to complete.
          ret = aclrtSynchronizeStream(stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
      
          // Call the first-phase API of aclnnQuantMatmulWeightNz.
          workspaceSize = 0;
          executor = nullptr;
          ret = aclnnQuantMatmulWeightNzGetWorkspaceSize(x1, x2NzFp4, x1Scale, x2Scale, nullptr, nullptr, nullptr, nullptr,
                                                         bias, transposeX1, transposeX2, groupSize, out, &workspaceSize,
                                                         &executor);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
                    return ret);
          // Allocate device memory according to the workspaceSize computed 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 aclnnQuantMatmulWeightNz.
          ret = aclnnQuantMatmulWeightNz(workspaceAddr, workspaceSize, executor, stream);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNz failed. ERROR: %d\n", ret); return ret);
      
          // 4. (boilerplate) Wait synchronously 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. Modify it according to the API definition.
          auto size = GetShapeSize(outShape);
          std::vector<uint16_t> resultData(size,
                                           0); // uint16_t stores the raw bit pattern of BF16; the code below converts it to float through Bf16ToFloat and prints the floating-point value.
          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: %.1f\n", i, Bf16ToFloat(resultData[i]));
          }
          return ACL_SUCCESS;
      }
      
      int main()
      {
          // 1. (boilerplate) Initialize the device/stream. For details, see the acl API manual.
          // Set deviceId based on the actual device.
          int32_t deviceId = 0;
          aclrtStream stream;
          auto ret = aclnnQuantMatmulWeightNzTest(deviceId, stream);
          CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNzTest failed. ERROR: %d\n", ret); return ret);
      
          Finalize(deviceId, stream);
          return 0;
      }