aclnnQuantMatmulV3

Notice: This API will be deprecated in later versions. Use the latest aclnnQuantMatmulV5 API instead.

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. 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 (3D matrix multiplication only, where the first dimension is the batch dimension). Supports T-C && T-T quantization mode.

  • Formula:

    • Without bias:

      out=x1@x2∗scale+offsetout = x1@x2 * scale + offset
    • bias INT32:

      out=(x1@x2+bias)∗scale+offsetout = (x1@x2 + bias) * scale + offset
    • Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products: Supports bias in BFLOAT16/FLOAT32 (no offset in this scenario).out=x1@x2∗scale+biasout = x1@x2 * scale + bias

Function Prototype

Each operator uses a two-phase API. Call "aclnnQuantMatmulV3GetWorkspaceSize" first to obtain the workspace size required for the computation and the executor that contains the operator computation flow, and then call "aclnnQuantMatmulV3" to execute the computation.

aclnnStatus aclnnQuantMatmulV3GetWorkspaceSize(
    const aclTensor *x1,
    const aclTensor *x2,
    const aclTensor *scale,
    const aclTensor *offset,
    const aclTensor *bias,
    bool             transposeX1,
    bool             transposeX2,
    const aclTensor *out,
    uint64_t        *workspaceSize,
    aclOpExecutor   **executor)
aclnnStatus aclnnQuantMatmulV3(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnQuantMatmulV3GetWorkspaceSize

  • 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 whose last two axes are transposed. Non-contiguous tensors in other use cases are not supported.
    • When transposeX1 is false, the shape is (batch, m, k); when transposeX1 is true, the shape is (batch, k, m). batch is optional.
    INT8, INT32, INT4 ND 2-6 ✓
    x2 Input Input x2 in the formula.
    • ND:
      • Supports non-contiguous tensors with the last two axes transposed; non-contiguous tensors in other use cases are not supported.
      • When transposeX2 is false, the shape is (batch, k, n); when transposeX2 is true, the shape is (batch, n, k). The batch dimension is optional, and k is the same as the k in the shape of x1.
    • NZ:
      • When transposeX2 is true, the shape is (batch, k1, n1, n0, k0). The batch dimension is optional, where k0=32, n0=16, and the k in the shape of x1 and the k1 in the shape of x2 must satisfy ceil(k / 32) = k1.
      • When transposeX2 is false, the shape is (batch, n1, k1, k0, n0). The batch dimension is optional, where k0=16, n0=32, and the k in the shape of x1 and the k1 in the shape of x2 must satisfy ceil(k / 16) = k1.
    INT8, INT32, INT4 ND, NZ 2-8 (ND), 4-8 (NZ) ✓
    scale Input Specifies the quantization parameter, which is the input scale in the formula. (t,), t = 1 or n, where n is the same as the n of x2
    When the data type of the original input does not match the type combinations in [Constraints](#constraints), call the aclnn API of the TransQuantParamV2 operator in advance to convert scale to the INT64 or UINT64 type.
    UINT64, INT64, FLOAT32, BFLOAT16 ND 1 ×
    offset Input Input offset in the formula. (t,), t = 1 or n, where n is the same as n of x2
    When the data type of out is INT8, offset can be present. For other input data types, nullptr must be passed in.
    FLOAT32 ND 1 ×
    bias Optional input The bias input in the formula. Shape: 1D (n,) or 3D (batch, 1, n), 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.
    INT32, BFLOAT16, FLOAT32 ND 1, 3 ×
    transposeX1 Input Indicates whether the input shape of x1 contains transpose. If transposeX1 is false, the shape is (batch, m, k)
    If transposeX1 is true, the shape is (batch, k, m)
    batch is optional.
    bool - - ×
    transposeX2 Input Indicates whether the input shape of x2 contains transpose.
    • ND: When transposeX2 is false, the shape is (batch, k, n).
      When transposeX2 is true, the shape is (batch, n, k).
      batch can be omitted, and k is the same as k in the shape of x1.
    • NZ:
      • When transposeX2 is true, the shape is (batch, k1, n1, n0, k0), where batch can be omitted, k0 = 32, n0 = 16, and the k in the shape of x1 and k1 in the shape of x2 must satisfy the following relationship: ceil(k / 32) = k1.
      • When transposeX2 is false, the shape is (batch, n1, k1, k0, n0), where batch can be omitted, k0 = 16, n0 = 32, and the k in the shape of x1 and k1 in the shape of x2 must satisfy the following relationship: ceil(k / 16) = k1.
    bool - - ×
    out Output The output out in the formula. (batch, m, n), where batch can be omitted and the batch dimensions of x1 and x2 support broadcast.
    The output batch is the same as the batch after broadcast, m is the same as m of x1, and n is the same as n of x2.
    FLOAT16, INT8, BFLOAT16, INT32 ND 2-6 ✓
    workspaceSize Output Returns the size of the workspace to be allocated on the Device. - - - - -
    executor Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas inference products:
      • x1 and x2 support INT8.
      • scale supports UINT64 and INT64.
      • bias supports INT32.
      • out supports FLOAT16 and INT8.
    • Atlas A2 products, Atlas A3 products:
      • x1 and x2 support INT8, INT32, and INT4.
      • The scale data type supports UINT64, INT64, FLOAT32, and BFLOAT16.
      • bias supports INT32, BFLOAT16, and FLOAT32. When x1 and x2 are INT32 or INT4, the shape of bias only supports 1D (n,).
      • When x1 and x2 are INT32 or INT4, transposeX1 only supports false.
      • out supports FLOAT16, INT8, BFLOAT16, and INT32.
    • Ascend 950PR&950DT products:
      • x1 and x2 support INT8 and INT4
      • The scale data type supports UINT64, INT64, FLOAT32, and BFLOAT16.
      • bias supports INT32, BFLOAT16, and FLOAT32
      • out supports FLOAT16, INT8, BFLOAT16, and INT32.
      • Under the full quantization scenario, when x2 is in ND format, the output is an empty tensor if m of input x1 is 0 or n of x2 is 0. Under the A8W8 full quantization scenario, when x2 is in NZ format, the output is an empty tensor if m of input x1 is 0 or n of x2 is 0.
  • 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, scale, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type and data format of x1, x2, bias, scale, offset, or out are not within the supported range.
    The shape of x1, x2, bias, scale, offset, or out does not meet the verification conditions.
    x1, x2, bias, scale, offset, or out is an empty tensor and does not fall into the supported empty tensor use cases described above.

aclnnQuantMatmulV3

  • Parameters:

    Parameters Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Size of the workspace allocated on the Device side, obtained by calling the first-phase API aclnnQuantMatmulV3GetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation:

    • Atlas training products, Atlas inference products: aclnnQuantMatmulV3 defaults to a deterministic implementation.
    • Ascend 950PR&950DT products: aclnnQuantMatmulV3 defaults to a deterministic implementation.
  • 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.
      • When the input x2 is in NZ format, the scenario where transposeX2 is false is not supported.
    • Before calling this API, you can call aclnnTransMatmulWeight to convert x2 in ND format to NZ format.
  • Atlas A2 products, Atlas A3 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. When the data type of x1 is INT32 or INT4, it is an INT4 quantization scenario, and currently only the case where transposeX1 is false is supported. When the data type of x1 is INT4, the dimension representation is (batch, m, k), and k must be an even number. When the data type of x1 is INT32, each INT32 value stores eight INT4 values, and the corresponding dimension representation is (batch, m, k // 8), and k must be a multiple of 8.
    • 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. When the input x2 is in NZ format, the scenario where transposeX2 is false is not supported.
      • When the data type is INT4, if transposeX2 is true, the shape is (n, k) and k must be even; if transposeX2 is false, the shape is (k, n) and n must be even.
      • When the data type is INT32, each INT32 value stores eight INT4 values. If transposeX2 is true, the shape is (n, k // 8) and k must be a multiple of 8; if transposeX2 is false, the shape is (k, n // 8) and n must be a multiple of 8.
      • You can use the aclnnConvertWeightToINT4Pack API to convert x2 from INT32 (one INT32 stores one INT4 in bits 0–3) to INT32 (one INT32 stores eight INT4 values) or INT4 (one INT4 represents one INT4 value). For details, see the aclnnConvertWeightToINT4Pack API.
    • Before calling this API, you can call aclnnTransMatmulWeight to convert x2 in ND format to NZ format.
  • Ascend 950PR&950DT products:
    • In the A4W4 full quantization scenario, only the ND format is supported for x2.
    • In the A8W8 full quantization use case, x2 supports the ND and NZ formats. Before calling this API, you can convert x2 from the ND format to the NZ format by calling aclnnTransMatmulWeight or aclnnNpuFormatCast. Zero padding must be used during the conversion to prevent dirty data.
    • In the A8W8 full quantization scenario, if any of the last two dimensions of the original ND-format x2 is 1 (that is, n=1 or k=1), conversion to the NZ format is not supported, and x2 should use the ND format.

The input and output support the following data type combinations. The following combinations support the T-C && T-T quantization mode:

NOTE When the original input types do not meet the following type combinations, call the aclnn API of the TransQuantParamV2 operator in advance to convert scale to the INT64 or UINT64 data type.

  • Atlas inference products:
x1x2ScaleOffsetBiasOut
INT8INT8UINT64/INT64nullnull/INT32FLOAT16
INT8INT8UINT64/INT64null/FLOAT32null/INT32INT8
  • Atlas A2 products, Atlas A3 products:
x1x2ScaleOffsetBiasOut
INT8INT8UINT64/INT64nullnull/INT32FLOAT16
INT8INT8UINT64/INT64null/FLOAT32null/INT32INT8
INT8INT8FLOAT32/BFLOAT16nullnull/INT32/BFLOAT16/FLOAT32BFLOAT16
INT4/INT32INT4/INT32UINT64/INT64nullnull/INT32FLOAT16
INT8INT8FLOAT32/BFLOAT16nullnull/INT32INT32
  • Ascend 950PR&950DT products:
x1x2ScaleOffsetBiasOut
INT8INT8UINT64/INT64nullnull/INT32FLOAT16/BFLOAT16
INT8INT8UINT64/INT64null/FLOAT32null/INT32INT8
INT8INT8FLOAT32/BFLOAT16nullnull/INT32/BFLOAT16/FLOAT32BFLOAT16
INT8INT8FLOAT32/BFLOAT16nullnull/INT32INT32
INT4INT4UINT64/INT64nullnull/INT32FLOAT16

Example

  • Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products:

The following sample code is for the common use case and is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <memory>
#include <vector>

#include "acl/acl.h"
#include "aclnnop/aclnn_quant_matmul_v3.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.
    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-side data to 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];
    }

    // Call the aclCreateTensor API to create an aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                              shape.data(), shape.size(), *deviceAddr);
    return 0;
}

void Finalize(int32_t deviceId, aclrtStream stream)
{
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
}

int aclnnQuantMatmulV3Test(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. Custom construction is required based on the API.
    std::vector<int64_t> x1Shape = {5, 2};
    std::vector<int64_t> x2Shape = {2, 3};
    std::vector<int64_t> biasShape = {3};
    std::vector<int64_t> offsetShape = {3};
    std::vector<int64_t> scaleShape = {3};
    std::vector<int64_t> outShape = {5, 3};
    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 = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
    std::vector<int8_t> x2HostData = {1, 1, 1, 1, 1, 1};
    std::vector<int32_t> biasHostData = {1, 1, 1};
    std::vector<float> scaleHostData = {1, 1, 1};
    std::vector<uint64_t> quantParamHostData(scaleHostData.size(), 0);
    std::vector<float> offsetHostData = {1, 1, 1};
    std::vector<uint16_t> outHostData = {1, 1, 1, 1, 1, 1, 1, 1,
                                        1, 1, 1, 1, 1, 1, 1};  // It is actually in float16 half-precision mode.
    // 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.
    ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_INT8, &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 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(quantParamHostData, 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 = false;

    // 3. Call the CANN operator library API. Change it to the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor = nullptr;

    // For the scale of the FLOAT data type, call the aclnn API of the TransQuantParamV2 operator 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
    void *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 first-phase API of aclnnQuantMatmulV3
    ret = aclnnQuantMatmulV3GetWorkspaceSize(x1, x2, quantParam, nullptr, bias, transposeX1, transposeX2, out,
                                            &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3GetWorkspaceSize 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 *)> workspaceAddrPtrV3(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);
        workspaceAddrPtrV3.reset(workspaceAddr);
    }

    // Call the second-phase API of aclnnQuantMatmulV3
    ret = aclnnQuantMatmulV3(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3 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 and copy the result from the device to the host. Modify it according to the definition of the specific API
    auto size = GetShapeSize(outShape);
    std::vector<uint16_t> resultData(
        size, 0);  // fp16 data cannot be printed directly in C. Read it as uint16 and convert it to fp16 in binary
    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: %hu\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 = aclnnQuantMatmulV3Test(deviceId, stream);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3Test failed. ERROR: %d\n", ret); return ret);

    Finalize(deviceId, stream);
    return 0;
}
  • Atlas A2 products and Atlas A3 products: The sample code for the use case where x2 is in NZ format is as follows (transposeX2=false), for reference only. For details about compilation and execution, see Compile and Run Samples.

    #include <iostream>
    #include <memory>
    #include <vector>
    
    #include "acl/acl.h"
    #include "aclnnop/aclnn_permute.h"
    #include "aclnnop/aclnn_quant_matmul_v3.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 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 data from the host 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 data from the host 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];
        }
    
        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 aclnnQuantMatmulV3Test(int32_t deviceId, aclrtStream &stream)
    {
        auto ret = Init(deviceId, &stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    
        // 2. Construct inputs and outputs, which need to be customly constructed according to the API
        std::vector<int64_t> x1Shape = {5, 2};
        std::vector<int64_t> x2Shape = {2, 3};
        std::vector<int64_t> biasShape = {3};
        std::vector<int64_t> offsetShape = {3};
        std::vector<int64_t> scaleShape = {3};
        std::vector<int64_t> outShape = {5, 3};
        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 = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
        std::vector<int8_t> x2HostData = {1, 1, 1, 1, 1, 1};
        std::vector<int32_t> biasHostData = {1, 1, 1};
        std::vector<float> scaleHostData = {1, 1, 1};
        std::vector<float> offsetHostData = {1, 1, 1};
        std::vector<uint16_t> outHostData = {1, 1, 1, 1, 1, 1, 1, 1,
                                            1, 1, 1, 1, 1, 1, 1};  // actually float16 half-precision format
        // 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 NZ x2 aclTensor
        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, which must be changed to the actual API name.
        uint64_t workspaceSize = 0;
        aclOpExecutor *executor = nullptr;
        void *workspaceAddr = nullptr;
        // Call the first-phase API 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 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 aclnnTransMatmulWeight.
        ret = aclnnTransMatmulWeight(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeight failed. ERROR: %d\n", ret); return ret);
    
        // For scale of the FLOAT data type, the aclnn API of the TransQuantParamV2 operator must be called in advance.
        // Call the first-phase API 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 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 aclnnQuantMatmulV3.
        workspaceSize = 0;
        ret = aclnnQuantMatmulV3GetWorkspaceSize(x1, x2, quantParam, nullptr, bias, transposeX1, transposeX2, out,
                                                &workspaceSize, &executor);
    
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3GetWorkspaceSize 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 *)> workspaceAddrPtrV3(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);
            workspaceAddrPtrV3.reset(workspaceAddr);
        }
        // Call the second-phase API of aclnnQuantMatmulV3.
        ret = aclnnQuantMatmulV3(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3 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, copy the result from device memory to the host side, and modify the code based on the specific API definition.
        auto size = GetShapeSize(outShape);
        std::vector<uint16_t> resultData(
            size, 0);  // fp16 data cannot be printed directly in C. Read it out as uint16 and manually convert the binary value to fp16.
        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: %hu\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 = aclnnQuantMatmulV3Test(deviceId, stream);
        CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3Test failed. ERROR: %d\n", ret); return ret);
    
        Finalize(deviceId, stream);
        return 0;
    }
  • Atlas A2 products and Atlas A3 products: The following is a code example for the INT4 quantization use case (x1 and x2 are of the INT4 data type, transposeX2=false), for reference only. For details about the compilation and execution process, see Compile and Run Samples.

    #include <iostream>
    #include <memory>
    #include <vector>
    
    #include "acl/acl.h"
    #include "aclnnop/aclnn_convert_weight_to_int4_pack.h"
    #include "aclnnop/aclnn_quant_matmul_v3.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 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)
    {
        // Obtain the number of memory bytes to allocate and copy through hostData.
        auto size = hostData.size() * sizeof(T);
        // Call aclrtMalloc to allocate device-side 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-side data to 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];
        }
    
        // Call the aclCreateTensor API to create an aclTensor.
        *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                                  shape.data(), shape.size(), *deviceAddr);
        return 0;
    }
    
    void Finalize(int32_t deviceId, aclrtStream stream)
    {
        aclrtDestroyStream(stream);
        aclrtResetDevice(deviceId);
        aclFinalize();
    }
    
    int aclnnQuantMatmulV3Test(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. Custom construction is required based on the API.
        int64_t m = 16;
        int64_t k = 8;
        int64_t n = 32;
        aclDataType x1Dtype = aclDataType::ACL_INT4;
        aclDataType x2Int4PackDtype = aclDataType::ACL_INT4;
        std::vector<int64_t> x1Shape = {m, k};
        std::vector<int64_t> x2Shape = {k, n};
        std::vector<int64_t> x2Int4PackShape = {k, n};
        std::vector<int64_t> biasShape = {n};
        std::vector<int64_t> scaleShape = {n};
        std::vector<int64_t> outShape = {m, n};
        void *x1DeviceAddr = nullptr;
        void *x2DeviceAddr = nullptr;
        void *x2Int4PackDeviceAddr = nullptr;
        void *scaleDeviceAddr = nullptr;
        void *quantParamDeviceAddr = nullptr;
        void *offsetDeviceAddr = nullptr;
        void *biasDeviceAddr = nullptr;
        void *outDeviceAddr = nullptr;
        aclTensor *x1 = nullptr;
        aclTensor *x2 = nullptr;
        aclTensor *x2Int4Pack = nullptr;
        aclTensor *bias = nullptr;
        aclTensor *scale = nullptr;
        aclTensor *quantParam = nullptr;
        aclTensor *offset = nullptr;
        aclTensor *out = nullptr;
        std::vector<int8_t> x1HostData(m * k / 2, 17);  // int8: 0001 0001
        std::vector<int8_t> x2HostData(k * n, 1);
        std::vector<int8_t> x2Int4PackHostData(n * k / 2, 1);
        std::vector<int32_t> biasHostData(n, 1);
        std::vector<float> scaleHostData(n, 1);
        std::vector<uint16_t> outHostData(m * n, 1);
    
        // Create the x1 aclTensor.
        ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, x1Dtype, &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.
        ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_INT32, &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 x2Int4Pack aclTensor.
        ret =
            CreateAclTensor(x2Int4PackHostData, x2Int4PackShape, &x2Int4PackDeviceAddr, x2Int4PackDtype, &x2Int4Pack);
        std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> x2Int4PackTensorPtr(x2Int4Pack,
                                                                                          aclDestroyTensor);
        std::unique_ptr<void, aclError (*)(void *)> x2Int4PackDeviceAddrPtr(x2Int4PackDeviceAddr, 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 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 change it to the specific API name.
        uint64_t workspaceSize = 0;
        aclOpExecutor *executor = nullptr;
    
        // Call the aclnnConvertWeightToINT4Pack API first to construct the x2 input data.
        // Call the first-phase API of aclnnConvertWeightToINT4Pack.
        ret = aclnnConvertWeightToINT4PackGetWorkspaceSize(x2, x2Int4Pack, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS,
                  LOG_PRINT("aclnnConvertWeightToINT4PackGetWorkspaceSize failed. ERROR: %d\n", ret);
                  return ret);
        // Allocate device memory based on the workspaceSize calculated by the first-phase API.
        void *workspaceAddr = nullptr;
        std::unique_ptr<void, aclError (*)(void *)> workspaceINT4PackAddrPtr(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);
            workspaceINT4PackAddrPtr.reset(workspaceAddr);
        }
        // Call the second-phase API of aclnnConvertWeightToINT4Pack.
        ret = aclnnConvertWeightToINT4Pack(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvertWeightToINT4Pack failed. ERROR: %d\n", ret); return ret);
    
        // For scale of the FLOAT data type, call the aclnn API of the TransQuantParamV2 operator 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 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 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 first-phase API of aclnnQuantMatmulV3.
        ret = aclnnQuantMatmulV3GetWorkspaceSize(x1, x2Int4Pack, quantParam, nullptr, bias, transposeX1, transposeX2,
                                                out, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3GetWorkspaceSize failed. ERROR: %d\n", ret);
                  return ret);
        // Allocate device memory based on the workspaceSize calculated by the first-phase API.
        workspaceAddr = nullptr;
        std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtrV3(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);
            workspaceAddrPtrV3.reset(workspaceAddr);
        }
    
        // Call the second-phase API of aclnnQuantMatmulV3.
        ret = aclnnQuantMatmulV3(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3 failed. ERROR: %d\n", ret); return ret);
    
        // 4. (boilerplate) Synchronize and wait for the task execution to finish.
        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 based on the specific API definition.
        auto size = GetShapeSize(outShape);
        std::vector<uint16_t> resultData(
            size, 0);  // In C, fp16 data cannot be printed directly. Read it as uint16 and manually convert the binary value to fp16.
        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: %hu\n", i, resultData[i]);
        }
        return ACL_SUCCESS;
    }
    
    int main()
    {
        // 1. (boilerplate) Initialize device/stream. For details, see the acl API manual.
        // Set deviceId according to the actual device.
        int32_t deviceId = 0;
        aclrtStream stream;
        auto ret = aclnnQuantMatmulV3Test(deviceId, stream);
        CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3Test failed. ERROR: %d\n", ret); return ret);
    
        Finalize(deviceId, stream);
        return 0;
    }
  • Atlas inference products: The sample code for the use case where x2 is in NZ format (transposeX2=true) is as follows, for reference only. For details about compilation and execution, see Compile and Run Samples.

    #include <iostream>
    #include <memory>
    #include <vector>
    
    #include "acl/acl.h"
    #include "aclnnop/aclnn_permute.h"
    #include "aclnnop/aclnn_quant_matmul_v3.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-side 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-side data to 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];
        }
    
        // 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-side 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 host-side data to 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];
        }
    
        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 aclnnQuantMatmulV3Test(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. Custom construction is required based on the API.
        std::vector<int64_t> x1Shape = {5, 2};
        std::vector<int64_t> x2Shape = {2, 3};
        std::vector<int64_t> x2TransposedShape = {3, 2};
        std::vector<int64_t> biasShape = {3};
        std::vector<int64_t> offsetShape = {3};
        std::vector<int64_t> scaleShape = {3};
        std::vector<int64_t> outShape = {5, 3};
        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 = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
        std::vector<int8_t> x2HostData = {1, 1, 1, 1, 1, 1};
        std::vector<int8_t> x2TransposedHostData = {1, 1, 1, 1, 1, 1};
        std::vector<int32_t> biasHostData = {1, 1, 1};
        std::vector<float> scaleHostData = {1, 1, 1};
        std::vector<float> offsetHostData = {1, 1, 1};
        std::vector<uint16_t> outHostData = {1, 1, 1, 1, 1, 1, 1, 1,
                                            1, 1, 1, 1, 1, 1, 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 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 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 = true;
    
        // 3. Call the CANN operator library API and replace with the actual API name.
        uint64_t workspaceSize = 0;
        aclOpExecutor *executor = nullptr;
        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 aclnnPermute first-phase API
        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 computed 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 aclnnPermute second-phase API
        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 aclnnTransMatmulWeight first-phase API
        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 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 aclnnTransMatmulWeight second-phase API
        ret = aclnnTransMatmulWeight(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeight failed. ERROR: %d\n", ret); return ret);
    
        // For scale of the FLOAT data type, the aclnn API of the TransQuantParamV2 operator needs to be called in advance
        // Call the aclnnTransQuantParamV2 first-phase API
        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 first-phase API of aclnnQuantMatmulV3.
        workspaceSize = 0;
        ret = aclnnQuantMatmulV3GetWorkspaceSize(x1, x2Transposed, quantParam, nullptr, bias, transposeX1, transposeX2,
                                                out, &workspaceSize, &executor);
    
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3GetWorkspaceSize 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 *)> workspaceAddrPtrV3(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);
            workspaceAddrPtrV3.reset(workspaceAddr);
        }
        // Call the second-phase API of aclnnQuantMatmulV3.
        ret = aclnnQuantMatmulV3(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3 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 host memory. Modify it based on the specific API definition.
        auto size = GetShapeSize(outShape);
        std::vector<uint16_t> resultData(
            size, 0);  // fp16 data cannot be printed directly in C. Read it as uint16 and manually convert it to fp16 in binary.
        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: %hu\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 in use.
        int32_t deviceId = 0;
        aclrtStream stream;
        auto ret = aclnnQuantMatmulV3Test(deviceId, stream);
        CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulV3Test failed. ERROR: %d\n", ret); return ret);
    
        Finalize(deviceId, stream);
        return 0;
    }