aclnnDynamicBlockQuantV2

📄 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: Not supported
  • Atlas training products: Not supported

Function

  • Description: For the input tensor, divides the input into multiple data blocks based on the given rowBlockSize and colBlockSize, and performs quantization at the granularity of each data block. In each block, first computes the quantization parameter scaleOut corresponding to the current block, and quantizes the input based on scaleOut. Outputs the final quantization result and the quantization parameter scaleOut for each block.

  • Formula:

    input_max=block_reduce_max(abs(x))input\_max = block\_reduce\_max(abs(x)) scaleOut=min(input_max/(FP8_MAX/HiF8_MAX/DST_TYPE_MAX/INT8_MAX),1/minScale)scaleOut = min(input\_max / (FP8\_MAX/HiF8\_MAX/DST\_TYPE\_MAX / INT8\_MAX), 1/minScale) yOut=cast_to_[FP8/HiF8/INT8](x/scaleOut)yOut = cast\_to\_[FP8/HiF8/INT8](x / scaleOut)

    Where block_reduce_max represents finding the maximum value in each block.

Function Prototype

Each operator uses a two-phase API. Call the "aclnnDynamicBlockQuantV2GetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnDynamicBlockQuantV2" API to perform computation.

aclnnStatus aclnnDynamicBlockQuantV2GetWorkspaceSize(
  const aclTensor   *x,
  double             minScale,
  char              *roundModeOptional,
  int64_t            dstType,
  int64_t            rowBlockSize,
  int64_t            colBlockSize,
  double             dstTypeMax,
  const aclTensor   *yOut,
  const aclTensor   *scaleOut,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnDynamicBlockQuantV2(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnDynamicBlockQuantV2GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Indicates the input Tensor of the operator. It corresponds to `x` in the formula. Does not support null Tensor. FLOAT16, BFLOAT16, FLOAT32 ND 2-3 √
    minScale (double) Input Minimum scale value used in the scaleOut computation. It corresponds to `minScale` in the formula. The value must be greater than or equal to 0. - - - -
    roundModeOptional (char*) Input Optional parameter, specifying the cast-to-output conversion mode. Supported values: rint, round. - - - - -
    dstType (int64_t) Input Specifies the data type of the output yOut. Supported values are 2, 34, 35, 36, representing INT8, HIFLOAT8, FLOAT8_E5M2, and FLOAT8_E4M3FN respectively. - - - -
    rowBlockSize (int64_t) Input Specifies the row size of a block. Supported values: 1, 128, 256, 512. - - - -
    colBlockSize (int64_t) Input Specifies the column size of a block. Supported values: 64, 128, 192, and 256. - - - -
    dstTypeMax (double) Input Maximum value of the target data type.
    • Currently, only HIFLOAT8 is supported as the target data type, and the supported values are 0.0, 15.0, 56.0, 224.0, and 32768.0
    • 0.0 indicates that the original maximum value of the data type is used.
    - - - -
    yOut (aclTensor*) Output Indicates the output tensor after quantization. Corresponds to `yOut` in the formula.
    • Does not support null Tensor.
    • The shape must be the same as that of `x`.
    INT8, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8 ND 2-3 ×
    scaleOut (aclTensor*) Output Indicates the scaleOut used for quantization, corresponding to `scaleOut` in the formula.
    • Does not support null tensors.
    • If the shape of input `x` is [M, N], the shape of output `scaleOut` is [ceil(M/rowBlockSize), ceil(N/colBlockSize)]; if the shape of input `x` is [B, M, N], the shape of output `scaleOut` is [B, ceil(M/rowBlockSize), ceil(N/colBlockSize)].
    FLOAT32 ND 2-3 ×
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be requested by the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - -
    • Atlas A2 products, Atlas A3 products:
      • The parameter roundModeOptional only supports rint.
      • The dstType parameter supports only the value 2, indicating INT8.
      • The parameter rowBlockSize only supports value 1.
      • The colBlockSize parameter supports only the values 1 or 128.
      • The dstTypeMax parameter supports only the value 0.
      • The data type of the parameter yOut only supports INT8.
    • Ascend 950PR&950DT products:
      • The shapes of x, yOut, and scaleOut support only 2D or 3D.
      • The value of the roundModeOptional parameter has a correspondence with the data type of the yOut parameter:
        • When the data type of output yOut is HIFLOAT8, the roundModeOptional parameter supports being set to round.
        • If the data type of output yOut is INT8, FLOAT8_E4M3FN, or FLOAT8_E5M2, the parameter roundModeOptional can be set to rint.
      • The parameter dstType supports 2, 34, 35, and 36, which indicate INT8, HIFLOAT8, FLOAT8_E5M2, and FLOAT8_E4M3FN respectively.
      • yOut supports the data types INT8, HIFLOAT8, FLOAT8_E4M3FN, and FLOAT8_E5M2.
  • 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, yOut, or scaleOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data format or data type of the input or output is not within the supported range.
    The shape of the input or output is not within the supported range.

aclnnDynamicBlockQuantV2

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested by the Device side.
    workspaceSize Input Workspace size requested by the Device side, obtained by the first-phase API aclnnDynamicBlockQuantV2GetWorkspaceSize.
    executor Input Op executor, which contains the operator computation process.
    stream Input Stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation:
    • aclnnDynamicBlockQuantV2 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.

  • Atlas A2 products, Atlas A3 products:

    #include <iostream>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_dynamic_block_quant_v2.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;
    }
    
    void PrintOutResult(std::vector<int64_t>& shape, void** deviceAddr)
    {
        auto size = GetShapeSize(shape);
        std::vector<int8_t> resultData(size, 0);
        auto ret = aclrtMemcpy(
            resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, 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);
        for (int64_t i = 0; i < size; i++) {
            LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]);
        }
    }
    
    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 request 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;
    }
    
    int main()
    {
        // 1. (Boilerplate) Device/stream initialization. For details, 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 inputs and outputs as required by the API.
        std::vector<int64_t> xShape = {4, 2};
        std::vector<int64_t> yShape = {4, 2};
        std::vector<int64_t> scaleShape = {4, 1};
    
        void* xDeviceAddr = nullptr;
        void* yDeviceAddr = nullptr;
        void* scaleDeviceAddr = nullptr;
    
        aclTensor* x = nullptr;
        aclTensor* y = nullptr;
        aclTensor* scale = nullptr;
    
        std::vector<aclFloat16> xHostData = {1, 2, 3, 4, 5, 6, 7, 8};
        std::vector<int8_t> yHostData(8, 0);
        std::vector<float> scaleHostData = {0, 0, 0, 0};
    
        // Create the x aclTensor.
        ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create the y aclTensor.
        ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_INT8, &y);
        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);
    
        // 3. Call the CANN operator library API, and change it to the specific API name.
        uint64_t workspaceSize = 0;
        aclOpExecutor* executor;
    
        const char* roundMode = "rint";
    
        // Call the first-phase API of aclnnDynamicBlockQuantV2.
        ret = aclnnDynamicBlockQuantV2GetWorkspaceSize(
            x, 0, (char*)roundMode, aclDataType::ACL_INT8, 1, 128, 0, y, scale, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicBlockQuantV2GetWorkspaceSize failed. ERROR: %d\n", ret);
                  return ret);
    
        // Allocate device memory based on the 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 aclnnDynamicBlockQuantV2.
        ret = aclnnDynamicBlockQuantV2(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicBlockQuantV2 failed. ERROR: %d\n", ret); return ret);
    
        // 4. (Boilerplate) Synchronize and wait for task execution to end.
        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 on the device side to the host side, and modify it according to the specific API interface definition.
        PrintOutResult(yShape, &yDeviceAddr);
    
        // 6. Release aclTensor and aclScalar, and modify them according to the specific API interface definition.
        aclDestroyTensor(x);
        aclDestroyTensor(y);
        aclDestroyTensor(scale);
    
        // 7. Release device resources.
        aclrtFree(xDeviceAddr);
        aclrtFree(yDeviceAddr);
        aclrtFree(scaleDeviceAddr);
        if (workspaceSize > 0) {
            aclrtFree(workspaceAddr);
        }
        aclrtDestroyStream(stream);
        aclrtResetDevice(deviceId);
        aclFinalize();
    
        return 0;
    }
  • Ascend 950PR&950DT products:

    #include <iostream>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_dynamic_block_quant_v2.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;
    }
    
    void PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
      auto size = GetShapeSize(shape);
      std::vector<float> resultData(size, 0);
      auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, 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);
      for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("mean result[%ld] is: %f\n", i, resultData[i]);
      }
    }
    
    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;
    }
    
    int main() {
      // 1. (Boilerplate) Device/stream initialization. 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, which need to be custom-constructed according to the API.
      std::vector<int64_t> xShape = {4, 2};
      std::vector<int64_t> yShape = {4, 2};
      std::vector<int64_t> scaleShape = {4, 1};
    
      void* xDeviceAddr = nullptr;
      void* yDeviceAddr = nullptr;
      void* scaleDeviceAddr = nullptr;
    
      aclTensor* x = nullptr;
      aclTensor* y = nullptr;
      aclTensor* scale = nullptr;
    
      std::vector<float> xHostData = {1, 2, 3, 4, 5, 6, 7, 8};
      std::vector<float> yHostData(8, 0);
      std::vector<float> scaleHostData = {0, 0, 0, 0};
    
      // Create the x aclTensor.
      ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      // Create the y aclTensor.
      ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT8_E5M2, &y);
      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);
    
      // 3. Call the CANN operator library API. Change it to the specific API name.
      uint64_t workspaceSize = 0;
      aclOpExecutor* executor;
    
      const char* roundMode = "rint";
    
      // Call the first-phase API of aclnnDynamicBlockQuantV2.
      ret = aclnnDynamicBlockQuantV2GetWorkspaceSize(x, 0.1, (char *)roundMode, aclDataType::ACL_FLOAT8_E5M2, 1, 128, 0, y, scale, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicBlockQuantV2GetWorkspaceSize 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 aclnnDynamicBlockQuantV2.
      ret = aclnnDynamicBlockQuantV2(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicBlockQuantV2 failed. ERROR: %d\n", ret); return ret);
    
      // 4. (boilerplate) Synchronize and 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 in device memory to the host side. Modify it according to the specific API definition.
      PrintOutResult(yShape, &yDeviceAddr);
    
      // 6. Release the aclTensor and aclScalar. Modify it according to the specific API definition.
      aclDestroyTensor(x);
      aclDestroyTensor(y);
      aclDestroyTensor(scale);
    
      // 7. Release device resources.
      aclrtFree(xDeviceAddr);
      aclrtFree(yDeviceAddr);
      aclrtFree(scaleDeviceAddr);
      if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
      }
      aclrtDestroyStream(stream);
      aclrtResetDevice(deviceId);
      aclFinalize();
    
      return 0;
    }