aclnnGroupedDynamicBlockQuant

📄 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 each group at the basic block granularity based on the starting values of the group indices (groupList), into (FP8/HiFP8), and outputs the quantization parameter scale (FP32).

  • Formula:

    input_max=block_reduce_max(abs(input))input\_max = block\_reduce\_max(abs(input)) scale=min(input_max/FP8_MAX(HiF8_MAX),1/min_scale)scale = min(input\_max/FP8\_MAX(HiF8\_MAX), 1/min\_scale) y=cast_to_[HiF8/FP8](input/scale)y = cast\_to\_[HiF8/FP8](input/scale)

Function Prototype

Each operator is divided into a two-phase API. You must first call the "aclnnGroupedDynamicBlockQuantGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnGroupedDynamicBlockQuant" API to perform the computation.

aclnnStatus aclnnGroupedDynamicBlockQuantGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *groupList,
  double           minScale,
  char            *roundModeOptional,
  int64_t          dstType,
  int64_t          rowBlockSize,
  int64_t          colBlockSize,
  int64_t          groupListType,
  const aclTensor *yOut,
  const aclTensor *scaleOut,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnGroupedDynamicBlockQuant(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnGroupedDynamicBlockQuantGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Represents the input tensor of the operator. Corresponds to input in the formula. Supports empty tensors. FLOAT16, BFLOAT16 ND 2-3, in the shapes of [M, N] and [B, M, N] √
    groupList (aclTensor*) Input Indicates the offset of each group on the M axis (cumsum mode). Indicates the start index of the quantization group. The value must be greater than or equal to 0, non-decreasing, and the last value must equal the size of the -2 axis of x. INT32 ND 1 √
    minScale (double) Input Specifies the minimum scale value involved in the scaleOut computation. Corresponds to min_scale in the formula. Requires this value to be greater than or equal to 0. DOUBLE - - -
    roundModeOptional (char*) Input Indicates the approximation mode for casting high-bit data to the target data type.
    • When dstType is 35/36, corresponding to the output yOut data type being FLOAT8_E5M2/FLOAT8_E4M3FN, only {"rint"} is supported.
    • When dstType is 34, corresponding to the output yOut data type being HIFLOAT8, {"round", "hybrid"} are supported.
    • When a null pointer is passed, the "rint" mode is used.
    STRING - - -
    dstType (int64_t) Input Indicates the data type of yOut after data conversion. The input range is {34, 35, 36}, corresponding to the output y data types {34: HIFLOAT8, 35: FLOAT8_E5M2, 36: FLOAT8_E4M3FN} respectively. INT64 - - -
    rowBlockSize (int64_t) Input Indicates the quantization granularity on the specified M axis. Currently supports values of 1, 128, 256, and 512. INT64 - - -
    colBlockSize (int64_t) Input Specifies the quantization granularity on the N-axis. Currently supports values 64, 128, 192, and 256. INT64 - - -
    groupListType (int64_t) Input Indicates the function type of group_list. Currently supports the value 0, which corresponds to the cumsum mode. INT64 - - -
    yOut (aclTensor*) Output Represents the quantized output tensor. Corresponds to y in the formula.
    • Supports empty tensors.
    • The shape dimensions remain consistent with x.
    HIFLOAT8, FLOAT8_E4M3FN, FLOAT8_E5M2 ND 2-3 √
    scaleOut (aclTensor*) Output Represents the quantization scale corresponding to each group, corresponding to scale in the formula.
    • Supports empty tensors.
    • If the shape of input x is [M, N] and the shape of groupList is [g], the shape of output scaleOut is [(M//rowBlockSize+g), (N/colBlockSize)].
    • If the shape of input x is [B, M, N] and the shape of groupList is [g], the shape of output scaleOut is [B, (M//rowBlockSize+g), (N/colBlockSize)].
    FLOAT32 ND 2-3 √
    workspaceSize Output Returns the workspace size to be applied for on the Device side. - - - - -
    executor Output Returns the operator executor, which contains the operator computation flow. - - - - -
  • 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 x, groupList, yOut, or scaleOut parameter passed in is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The input or output data format or data type is not within the supported range.
    The shape of the input or output data is not within the supported range.

aclnnGroupedDynamicBlockQuant

  • 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 through the first-phase API aclnnGroupedDynamicBlockQuantGetWorkspaceSize.
    executor Input Operator executor that 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: aclnnGroupedDynamicBlockQuant 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_grouped_dynamic_block_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 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 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 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);

    // 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 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.
    // Fill in the 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. Custom construction is required based on the API.
    std::vector<int64_t> xShape = {4, 2};
    std::vector<int64_t> groupListShape = {1};
    std::vector<int64_t> yShape = {4, 2};
    std::vector<int64_t> scaleShape = {5, 1};

    void* xDeviceAddr = nullptr;
    void* groupListDeviceAddr = nullptr;
    void* yDeviceAddr = nullptr;
    void* scaleDeviceAddr = nullptr;

    aclTensor* x = nullptr;
    aclTensor* groupList = nullptr;
    aclTensor* y = nullptr;
    aclTensor* scale = nullptr;

    std::vector<aclFloat16> xHostData = {1, 2, 3, 4, 5, 6, 7, 8};
    std::vector<int32_t> groupListHostData = {1};
    std::vector<uint8_t> yHostData(8, 0);
    std::vector<float> scaleHostData = {0, 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 groupList aclTensor.
    ret = CreateAclTensor(groupListHostData, groupListShape, &groupListDeviceAddr, aclDataType::ACL_INT32, &groupList);
    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. Replace with the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;

    const char* roundMode = "rint";
    float minScale = 0.0;
    int64_t rowBlockSize = 1;
    int64_t colBlockSize = 128;
    int64_t groupListType = 0;

    // Call the first-phase API of aclnnGroupedDynamicBlockQuant.
    ret = aclnnGroupedDynamicBlockQuantGetWorkspaceSize(x, groupList, minScale, (char *)roundMode, aclDataType::ACL_FLOAT8_E5M2, rowBlockSize, colBlockSize, groupListType, y, scale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicBlockQuantGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);

    // Apply for 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 aclnnGroupedDynamicBlockQuant.
    ret = aclnnGroupedDynamicBlockQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicBlockQuant failed. ERROR: %d\n", ret);
              return ret);

    // 4. (Boilerplate) Synchronously 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.
    LOG_PRINT("yOut is: \n");
    PrintOutResult(yShape, &yDeviceAddr);
    LOG_PRINT("scaleOut is: \n");
    PrintOutResult(scaleShape, &scaleDeviceAddr);

    // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(groupList);
    aclDestroyTensor(y);
    aclDestroyTensor(scale);

    // 7. Release device resources.
    aclrtFree(xDeviceAddr);
    aclrtFree(groupListDeviceAddr);
    aclrtFree(yDeviceAddr);
    aclrtFree(scaleDeviceAddr);
    if (workspaceSize > 0) {
      aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
  }