aclnnAscendAntiQuant

📄 View Source Code

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: Dequantizes the input x based on the input scale and offset.
  • Formula:
    • If sqrtMode is true and offset is None, the formula is as follows:

      y=cast_to_dst_type((x)∗scale∗scale)y = cast\_to\_dst\_type((x) * scale * scale)
    • If sqrtMode is true and offset is not None, the formula is as follows:

      y=cast_to_dst_type((x+offset)∗scale∗scale)y = cast\_to\_dst\_type((x + offset) * scale * scale)
    • If sqrtMode is false and offset is None, the calculation formula is as follows:

      y=cast_to_dst_type((x)∗scale)y = cast\_to\_dst\_type((x) * scale)
    • If sqrtMode is false and offset is not None, the calculation formula is as follows:

      y=cast_to_dst_type((x+offset)∗scale)y = cast\_to\_dst\_type((x + offset) * scale)

Function Prototype

Each operator uses a two-phase API. First, call "aclnnAscendAntiQuantGetWorkspaceSize" to obtain the workspace size required for the computation and the executor that contains the operator computation process. Then, call "aclnnAscendAntiQuant" to perform the computation.

aclnnStatus aclnnAscendAntiQuantGetWorkspaceSize(
  const aclTensor* x,
  const aclTensor* scale,
  const aclTensor* offset,
  int64_t          dstType,
  bool             sqrtMode,
  const aclTensor* y,
  uint64_t*        workspaceSize,
  aclOpExecutor**  executor)
aclnnStatus aclnnAscendAntiQuant(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnAscendAntiQuantGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Input to be dequantized. Corresponds to x in the corresponding formula.
    • Supports empty Tensor;
    • when the data type is INT32, each element is used as 8 INT4 elements;
    • when the data type is INT4, the tail axis of the shape is even.
    INT4, INT8, INT32, HIFLOAT8, FLOAT8_E4M3, FLOAT8_E5M2 ND 0-8 √
    scale (aclTensor*) Input Scale value in dequantization. Corresponds to scale in the corresponding formula.
    • Supports empty tensors;
    • The number of dimensions of scale must be the same as that of x, or scale must be 1-dimensional;
    • If x is 1-dimensional, the shape of scale must be [1] or the same as that of x;
    • If scale is 1-dimensional, its size must be 1, x[-1], or x[-2];
    • If scale is multi-dimensional, at most one dimension can be non-1, and this non-1 dimension can only be the -1 or -2 axis;
    • When input x is of the INT32 type and the dequantization axis is the tail axis, the tail axis size of scale must be 8 times that of x;
    • When x is of the HIFLOAT8, FLOAT8_E4M3, or FLOAT8_E5M2 type, scale supports only FLOAT32.
    FLOAT32, BFLOAT16 ND 1-8 √
    offset (aclTensor*) Input Offset value in dequantization. Corresponds to the offset in the corresponding formula.
    • Supports empty tensors;
    • The data type and shape must be the same as those of scale.
    FLOAT32, BFLOAT16 ND 1-8 √
    dstType (int64_t) Input Specifies the output data type. Value: 1 or 27, indicating FLOAT16 and BFLOAT16 respectively. - - - -
    sqrtMode (bool) Input Specifies how scale participates in the computation. Corresponds to sqrtMode in the formula. When the data type of x is HIFLOAT8, FLOAT8_E4M3, or FLOAT8_E5M2, sqrtMode is false. - - - -
    y (aclTensor*) Output Dequantization output. y in the corresponding formula.
    • Supports empty tensors.
    • When input x is of the INT32 type, the tail axis size of the shape is 8 times the tail axis size of input x. In other cases, the shape is the same as input x.
    FLOAT16, BFLOAT16 ND 0-8 √
    workspaceSize (uint64_t*) Output Size of the workspace to be requested on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor that contains the operator computation process. - - - - -
    • Atlas inference products:
      • Data type:
        • The input x supports only INT8.
        • The inputs scale and offset, and the output y do not support BFLOAT16.
      • The input dstType supports only the value 1, which indicates FLOAT16.
      • Input parameters scale and offset support only 1D tensors, and their sizes can only be equal to the size of the last dimension of x or 1. If x is of the int32 type, the size must be 8 times the size of the last dimension of x.
    • Atlas A2 products, Atlas A3 products:
      • Input parameter x supports only INT4, INT8, and INT32.
      • Input parameters scale and offset support only 1D tensors, and their sizes can only be equal to the size of the last dimension of x or 1. If x is of the int32 type, the size must be 8 times the size of the last dimension of x.
  • Return Value

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

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

    Error Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input x, scale, or y is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x, scale, offset, or y is not supported.
    dstType is out of the valid value range.
    When the data type of x is INT4, the dequantization axis size of x is not an even number.
    When the data type of x is INT4, x is a non-contiguous tensor.
    When the data type of x is INT32, the dequantization axis of y is not 8 times the dequantization axis size of x, or the sizes of other axes of x and y are inconsistent.

aclnnAscendAntiQuant

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Workspace size allocated on the device, obtained from the first-phase API aclnnAscendAntiQuantGetWorkspaceSize.
    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 Error Codes.

Constraints

  • When the data type of input x is INT4, x does not support non-contiguous tensors.
  • Deterministic computation:
    • aclnnAscendAntiQuant defaults to a deterministic implementation.

Example

The following sample code is for reference only. For details, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_ascend_anti_quant.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 shape_size = 1;
    for (auto i : shape) {
        shape_size *= i;
    }
    return shape_size;
}

int Init(int32_t deviceId, aclrtStream* stream)
{
    // Boilerplate for resource initialization.
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
    return 0;
}

template <typename T>
int CreateAclTensor(
    const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
    aclTensor** tensor)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    // Call aclrtMalloc to allocate device memory.
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);

    // Call aclrtMemcpy to copy host data to device memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

    // 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. For details, see the acl API documentation.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the input and output as required by the API.
    std::vector<int64_t> selfShape = {4, 2};
    std::vector<int64_t> scaleShape = {1};
    std::vector<int64_t> offsetShape = {1};
    std::vector<int64_t> outShape = {4, 2};
    void* selfDeviceAddr = nullptr;
    void* scaleDeviceAddr = nullptr;
    void* offsetDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* self = nullptr;
    aclTensor* scale = nullptr;
    aclTensor* offset = nullptr;
    aclTensor* out = nullptr;
    std::vector<int8_t> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7};
    std::vector<float> scaleHostData = {1};
    std::vector<float> offsetHostData = {1};
    std::vector<short> outHostData = {0, 0, 0, 0, 0, 0, 0, 0};
    // Create the self aclTensor.
    ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_INT8, &self);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the scale aclTensor.
    ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the offset aclTensor
    ret = CreateAclTensor(offsetHostData, offsetShape, &offsetDeviceAddr, aclDataType::ACL_FLOAT, &offset);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the out aclTensor
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    int64_t dstType = 1;
    bool sqrtMode = false;

    // 3. Call the CANN operator library API. Replace it with the actual API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnAscendAntiQuant
    ret = aclnnAscendAntiQuantGetWorkspaceSize(self, scale, offset, dstType, sqrtMode, out, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAscendAntiQuantGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);
    // Allocate device memory based on workspaceSize computed 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 aclnnAscendAntiQuant
    ret = aclnnAscendAntiQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAscendAntiQuant failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) 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 host memory, and view the data in resultData. Modify the code based on the API definition.
    auto size = GetShapeSize(outShape);
    std::vector<short> resultData(size, 0);
    ret = aclrtMemcpy(
        resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(short),
        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: %hd\n", i, resultData[i]);
    }

    // 6. Destroy aclTensor. Modify the code based on the API definition.
    aclDestroyTensor(self);
    aclDestroyTensor(scale);
    aclDestroyTensor(offset);
    aclDestroyTensor(out);

    // 7. Release device resources. Modify the code based on the API definition.
    aclrtFree(selfDeviceAddr);
    aclrtFree(scaleDeviceAddr);
    aclrtFree(offsetDeviceAddr);
    aclrtFree(outDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}