aclnnTransQuantParamV3

📄 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: Converts the data type of the scale parameter used in quantization computation from FLOAT32 to the UINT64 and INT64 types required by the hardware. Compared with aclnnTransQuantParamV2, the roundMode input is added to select the conversion mode for data value conversion during data type conversion.

  • Formula:

    1. out is in 64-bit format and is initialized to 0.

    2. If roundMode is 1, scale is rounded by bit to the upper 19 bits; if roundMode is 0, no processing is performed.

      scale=Round(scale)scale = Round(scale)
    3. scale retains the high 19 bits at the bit level (that is, bits 13-31, with the low 13 bits cleared), writes them to the low 32 bits of out, and sets bit 46 to 1.

      out=out ∣ (scale & 0xFFFFE000) ∣ (1≪46)out = out\ |\ (scale\ \&\ 0xFFFFE000)\ |\ (1\ll46)
    4. Perform subsequent calculations based on the offset value:

      • If offset does not exist, no further computation is performed.
      • If offset exists:
        1. Process the offset value as int, with a range of [-256, 255].

          offset=Max(Min(INT(Round(offset)),255),−256)offset = Max(Min(INT(Round(offset)),255),-256)
        2. Retain the lower 9 bits of offset and store them in bits 37 to 45 of out.

          out=(out & 0x4000FFFFFFFF) ∣ ((offset & 0x1FF)≪37)out = (out\ \&\ 0x4000FFFFFFFF)\ |\ ((offset\ \&\ 0x1FF)\ll37)

Function Prototype

Each operator uses a two-phase API. You must first call the aclnnTransQuantParamV3GetWorkspaceSize API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the aclnnTransQuantParamV3 API to perform the computation.

aclnnStatus aclnnTransQuantParamV3GetWorkspaceSize(
  const aclTensor* scale,
  const aclTensor* offset,
  int64_t          roundMode,
  const aclTensor* out,
  uint64_t*        workspaceSize,
  aclOpExecutor**  executor)
aclnnStatus aclnnTransQuantParamV3(
  void                *workspace,
  uint64_t             workspaceSize,
  aclOpExecutor       *executor,
  const aclrtStream    stream)

aclnnTransQuantParamV3GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    scale(aclTensor*) Input The scale value in quantization. It corresponds to `scale` in the formula.
    • Empty tensors are not supported.
    • The shape is 1D (t,), where t = 1 or n, or 2D (1, n), where n is the same as the shape n of the right matrix in the matmul computation.
    • Ensure that the scale data contains no NaN or Inf.
    FLOAT32 ND 1-2 ×
    offset (aclTensor*) Input Optional parameter. The offset value in quantization. It corresponds to `offset` in the formula.
    • Empty tensors are not supported.
    • The shape is 1D (t,) or 2D (1, n), where t = 1 or n. n is the same as the shape n of the right matrix in the matmul computation.
    • Ensure that the offset data contains no NaN or Inf.
    FLOAT32 ND 1-2 ×
    roundMode (int64_t) Input Round mode for padding FP32 to FP19 in the quantization computation. Corresponds to `roundMode` in the formula description. Only the following values are supported: 0 (compatible with V2), 1 (improved precision) - - - -
    out (aclTensor*) Output Computation output of quantization. Corresponds to `out` in the formula.
    • Empty tensors are not supported.
    • When the shape of the input scale is 1-dimensional, the shape of out is also 1-dimensional, and the shape size of this dimension is the maximum of the single-dimension shape sizes of scale and offset (if not nullptr). When the shape of the input scale is 2-dimensional, the dimensions and shape size of out are exactly the same as those of the input scale.
    UINT64, INT64 ND 1-2 √
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied for on the device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor that contains the operator computation flow. - - - - -
  • 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:

    Error Code Error code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input scale or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of scale, offset, or out is not within the supported range.
    The shape of scale or offset is not within the supported range.
    The value of roundMode is not within the supported range.

aclnnTransQuantParamV3

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Size of the workspace allocated on the Device, obtained by calling the first-phase API aclnnTransQuantParamV3GetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream that specifies the task to be executed.
  • Return Value

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

Constraints

  • Atlas inference products, Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products: This API can be used together with matmul operators (such as aclnnQuantMatmulV4).
  • Atlas inference products, Atlas A2 products, Atlas A3 products: This API cannot be used together with grouped matmul operators (such as aclnnGroupedMatmulV4).
  • The shapes of scale, offset, and out are described as follows:
    • When there is no offset, the out shape is the same as the scale shape.
      • If out is used as the input of a matmul operator (such as aclnnQuantMatmulV4), supported shapes are 1D (1,), (n,) or 2D (1, n), where n is the same as the shape n of the right matrix (corresponding parameter x2) in the matmul computation.
      • If out is used as a grouped matmul class operator input (such as aclnnGroupedMatmulV4), it is only used when the grouping mode is m-axis grouping (corresponding parameter groupType is 0). Its shape supports 1D (g,) or 2D (g, 1), (g, n), where n is consistent with the shape n of the right matrix (corresponding parameter x2) in the grouped matmul computation, and g is consistent with the number of groups (corresponding parameter groupListOptional's shape size) in the grouped matmul computation.
    • When offset is present, use it only as the input of a matmul operator (such as aclnnQuantMatmulV4):
      • The shapes of offset, scale, and out support 1D (1,), (n,) or 2D (1, n), where n is consistent with the shape n of the right matrix (corresponding parameter x2) in the matmul computation.
      • When the input scale's shape is 1D, the out shape is also 1D, and its shape size is the maximum of the single-dimension shape sizes of scale and offset.
      • When the shape of the input scale is 2D, the shape of out has exactly the same dimensions and size as the shape of the input scale.
  • Deterministic computation:
    • aclnnTransQuantParamV3 defaults to a deterministic implementation.

Example

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

#include <memory>
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_trans_quant_param_v3.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-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-side memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

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

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

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

int aclnnTransQuantParamV3Test(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 as required by the API.
    std::vector<int64_t> offsetShape = {3};
    std::vector<int64_t> scaleShape = {3};
    std::vector<int64_t> outShape = {3};
    void* scaleDeviceAddr = nullptr;
    void* offsetDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* scale = nullptr;
    aclTensor* offset = nullptr;
    aclTensor* out = nullptr;
    std::vector<float> scaleHostData = {1, 1, 1};
    std::vector<float> offsetHostData = {1, 1, 1};
    std::vector<uint64_t> outHostData = {1, 1, 1};
    int64_t roundMode = 1;
    // 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 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 out aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_UINT64, &out);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> outTensorPtr(out, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> outDeviceAddrPtr(outDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Change it to the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnTransQuantParamV3.
    ret = aclnnTransQuantParamV3GetWorkspaceSize(scale, offset, roundMode, out, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransQuantParamV3GetWorkspaceSize 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*)> workspaceAddrPtr(nullptr, aclrtFree);
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
        workspaceAddrPtr.reset(workspaceAddr);
    }
    // Call the second-phase API of aclnnTransQuantParamV3.
    ret = aclnnTransQuantParamV3(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransQuantParamV3 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. Change it according to the API definition.
    auto size = GetShapeSize(outShape);
    std::vector<uint64_t> resultData(size, 0);
    ret = aclrtMemcpy(
        resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(resultData[0]),
        ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("result[%ld] is: %lu\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 = aclnnTransQuantParamV3Test(deviceId, stream);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransQuantParamV3Test failed. ERROR: %d\n", ret); return ret);

    Finalize(deviceId, stream);
    return 0;
}