aclnnQuantize

📄 View Source Code

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DT√
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products√
Atlas training products×

Function

  • Description: Quantizes the input tensor x.

  • Formula:

    out=round((x/scales)+zeroPoints)out=round((x/scales)+zeroPoints)

Function Prototype

Each operator is divided into a two-phase API. The "aclnnQuantizeGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnQuantize" API is called to perform the computation.

aclnnStatus aclnnQuantizeGetWorkspaceSize(
  const aclTensor* x,
  const aclTensor* scales,
  const aclTensor* zeroPoints,
  aclDataType      dtype,
  int32_t          axis,
  aclTensor*       out,
  uint64_t*        workspaceSize,
  aclOpExecutor**  executor)
aclnnStatus aclnnQuantize(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnQuantizeGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    x (aclTensor*) Input Represents the source data tensor to be quantized. Corresponds to `x` in the formula. Supports null tensor. FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    scales (aclTensor*) Input Represents the tensor that scales x during quantization. Corresponds to `scales` in the formula.
    • Supports null tensor.
    • size must be 1 or equal to the size of the axis dimension in input x.
    • If the dtype of `x` is not FLOAT32, it must be consistent with the dtype of `x`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    zeroPoints (aclTensor*) Input Represents the tensor that offsets x during quantization, corresponding to `zeroPoints` in the formula.
    • Supports null tensor.
    • Supports passing a null pointer.
    • The size must be 1 or equal to the size of the axis dimension in input x, and equal to the size of scales.
    INT32, INT8, UINT8, FLOAT32, BFLOAT16 ND 1 √
    dstType (aclDataType) Input Specifies the data type of the output. Supports configuration as ACL_INT8, ACL_UINT8, ACL_INT32, ACL_HIFLOAT8, ACL_FLOAT8_E4M3FN, and ACL_FLOAT8_E5M2. - - - -
    axis (int32_t) Input Represents the element-wise axis for quantization, with other axes performing broadcast.
    • When the sizes of both input scales and zeroPoints are 1, this parameter is not actually used.
    • The supported range is less than the number of dimensions of input x and greater than or equal to the negative value of the number of dimensions of x.
    - - - -
    out (aclTensor*) Output Represents the quantized output tensor. Corresponds to `out` in the formula.
    • Supports null tensor.
    • Its shape must be consistent with `x`, and the data type is specified by the input parameter `dstType`.
    INT8, UINT8, INT32, HIFLOAT8, FLOAT8_E4M3FN, FLOAT8_E5M2 ND 1-8 √
    workspaceSize(uint64_t*) Output Returns the workspace size to be allocated on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas inference products:

      • Data type:

        • The input parameters x and scales do not support BFLOAT16 or FLOAT32.

        • The input parameter zeroPoints does not support FLOAT32. When the data type is BFLOAT16, the data types of x and scales are both BFLOAT16.

        • The output parameter out supports only INT8, UINT8, and INT32.

      • The input parameter dstType supports only the values ACL_INT8, ACL_UINT8, and ACL_INT32.

    • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products:

      • Data type:

        • The input parameter zeroPoints does not support FLOAT32. When the data type is BFLOAT16, the data types of x and scales are both BFLOAT16.

        • The output out supports only INT8, UINT8, and INT32.

      • The input parameter dstType supports only ACL_INT8, ACL_UINT8, and ACL_INT32.

  • Return Value

    aclnnStatus: return code. For details, see aclnn Return Code.

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

    Return Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input x, scales, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, or dimension of x, scales, zeroPoints, or out is not within the supported range.
    The axis specified by the input exceeds the number of dimensions of the input x.
    dstType is not within the valid value range.
    The sizes of the input scales and zeroPoints are not equal.
    The size of the input scales and zeroPoints, when not equal to 1, does not match the size of the axis specified by the input axis.
    The data type of the input out does not match the value of the input dstTyped.

aclnnQuantize

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied for on the Device side.
    workspaceSize Input Workspace size applied for on the Device side, obtained from the first-phase API aclnnQuantizeGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return Value

    aclnnStatus: return code. For details, see aclnn Return Code.

Constraints

  • Deterministic computation:

    • aclnnQuantize defaults to a deterministic implementation.

Example

The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_quantize.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)

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 apply for 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 data from the host to the device memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

    // Calculate the strides of the contiguous tensor.
    std::vector<int64_t> strides(shape.size(), 1);
    for (int64_t i = shape.size() - 2; i >= 0; i--) {
        strides[i] = shape[i + 1] * strides[i + 1];
    }

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

int main()
{
    // 1. (Boilerplate) Initialize the device/stream. See the ACL API manual.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    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> xShape = {4, 2};
    std::vector<int64_t> scalesShape = {2};
    std::vector<int64_t> zeroPointsShape = {2};
    std::vector<int64_t> outShape = {4, 2};
    void* xDeviceAddr = nullptr;
    void* scalesDeviceAddr = nullptr;
    void* zeroPointsDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* scales = nullptr;
    aclTensor* zeroPoints = nullptr;
    aclTensor* out = nullptr;

    aclDataType dataType = ACL_INT32;
    int32_t axis = 1;
    std::vector<float> scalesHostData = {1.0, -3.0};
    std::vector<int32_t> zeroPointsData = {2, 10};
    std::vector<float> xHostData = {0.3382, -0.0919, 0.7564, 0.0234, 3.1024, 1.0761, 0.4228, 1.4621};
    std::vector<int32_t> outHostData = {8, 0};

    // Create the x aclTensor.
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the scales aclTensor.
    ret = CreateAclTensor(scalesHostData, scalesShape, &scalesDeviceAddr, aclDataType::ACL_FLOAT, &scales);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the zeroPoints aclTensor.
    ret = CreateAclTensor(zeroPointsData, zeroPointsShape, &zeroPointsDeviceAddr, aclDataType::ACL_INT32, &zeroPoints);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the out aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, dataType, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Replace with the actual API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnQuantize.
    ret = aclnnQuantizeGetWorkspaceSize(x, scales, zeroPoints, dataType, axis, out, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantizeGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory based on the workspaceSize calculated by the first-phase API.
    void* workspaceAddr = nullptr;
    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);
    }
    // Call the second-phase API of aclnnQuantize.
    ret = aclnnQuantize(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantize 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 memory to the host memory. Modify based on the specific API definition.
    auto outSize = GetShapeSize(outShape);
    std::vector<int32_t> outData(outSize, 0);
    ret = aclrtMemcpy(
        outData.data(), outData.size() * sizeof(outData[0]), outDeviceAddr, outSize * sizeof(outData[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 < outSize; i++) {
        LOG_PRINT("out[%ld] is: %d\n", i, outData[i]);
    }

    // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(scales);
    aclDestroyTensor(zeroPoints);
    aclDestroyTensor(out);

    // 7. Release device resources. Modify based on the specific API definition.
    aclrtFree(xDeviceAddr);
    aclrtFree(scalesDeviceAddr);
    aclrtFree(zeroPointsDeviceAddr);
    aclrtFree(outDeviceAddr);

    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}