aclnnGroupedDynamicBlockQuantV2

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

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). Compared with the aclnnGroupedDynamicBlockQuant API, this API allows setting the maximum value of the target data type using dstTypeMax when the target data type is HIFLOAT8.

  • Formula:

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

Function Prototype

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

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

aclnnGroupedDynamicBlockQuantV2GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Denotes the operator input tensor. It is input in the corresponding formula. - FLOAT16, BFLOAT16 ND 2-3, in the form of [M, N] and [B, M, N] √
    groupList (aclTensor*) Input Denotes the offset of each group along the M axis (cumsum mode). Represents the start index of quantization groups. The values must be greater than or equal to 0 and non-decreasing, and the last number must be equal to the size of dimension -2 of x. INT32 ND 1 √
    minScale (double) Input Represents the minimum scale value used in calculating scaleOut. Corresponds to min_scale in the corresponding formula. The value must be greater than or equal to 0. DOUBLE - - -
    roundModeOptional (char*) Input Approximate mode for the final cast of high-bit data to the target data type.
    • When dstType is 35/36 and the data type of output yOut is FLOAT8_E5M2/FLOAT8_E4M3FN, only {"rint"} is supported.
    • When dstType is 34 and the data type of output yOut is HIFLOAT8, {"round", "hybrid"} are supported.
    • If a null pointer is passed in, 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 data types of output y: {34: HIFLOAT8, 35: FLOAT8_E5M2, 36: FLOAT8_E4M3FN}. INT64 - - -
    rowBlockSize (int64_t) Input Specifies the quantization granularity along the M axis. The currently supported values are 1/128/256/512. INT64 - - -
    colBlockSize (int64_t) Input Specifies the quantization granularity along the N axis. Supported values are 64/128/192/256. INT64 - - -
    groupListType (int64_t) Input Indicates the function type of group_list. Supported value: 0, corresponding to the cumsum mode. INT64 - - -
    dstTypeMax (double) Input Maximum value of the target data type.
    • Currently, only HIFLOAT8 is supported as the target data type, and the value range is [0.0, 32768.0]
    • 0.0 indicates that the original maximum value of the data type is used.
    DOUBLE - - -
    yOut (aclTensor*) Output Represents the output tensor after quantization. Corresponds to y in the corresponding formula. The dimensions of shape are the same as those of x. HIFLOAT8, FLOAT8_E4M3FN, FLOAT8_E5M2 ND 2-3 ×
    scaleOut (aclTensor*) Output Quantization scale corresponding to each group, which is the scale in the corresponding formula.
    • If the shape of input x is [M, N] and the shape of groupList is [g], the shape dimension of output scaleOut is [(M//rowBlockSize+g), ceil(N/colBlockSize)].
    • If the shape of input x is [B, M, N] and the shape of groupList is [g], the shape dimension of output scaleOut is [B, (M//rowBlockSize+g), ceil(N/colBlockSize)].
    FLOAT32 ND 2-3 ×
    workspaceSize Output Returns the size of the workspace to be requested on the device. - - - - -
    executor Output Returns the op executor containing the operator computation flow. - - - - -
  • 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 x, groupList, yOut, or scaleOut parameter is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The input or output data format or data type is out of the supported range.
    The shape of the input or output data is out of the supported range.

aclnnGroupedDynamicBlockQuantV2

  • Parameters:

    Parameter Input/Output Description
    workspace Input The workspace memory address requested on the Device side.
    workspaceSize Input The workspace size requested on the Device side, obtained by the first-phase API aclnnGroupedDynamicBlockQuantV2GetWorkspaceSize.
    executor Input Op executor containing the operator computation flow.
    stream Input Stream for executing the task.
  • Return Value

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

Constraints

  • Determinism note: aclnnGroupedDynamicBlockQuantV2 defaults to a deterministic implementation.
  • Supported use case note: Only the use case where both yOut and scaleOut are empty tensors is supported. Other empty tensor use cases are not supported.

Example

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

  #include <iostream>
  #include <vector>
  #include "acl/acl.h"
  #include "aclnnop/aclnn_grouped_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 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-side data 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 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;
  }

  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);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the inputs and outputs. Customize the construction 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 actual API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;

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

    // Call the aclnnGroupedDynamicBlockQuantV2 first-phase API
    ret = aclnnGroupedDynamicBlockQuantV2GetWorkspaceSize(x, groupList, minScale, (char *)roundMode, aclDataType::ACL_FLOAT8_E5M2, rowBlockSize, colBlockSize, groupListType, dstTypeMax, y, scale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicBlockQuantV2GetWorkspaceSize 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 aclnnGroupedDynamicBlockQuantV2 second-phase API
    ret = aclnnGroupedDynamicBlockQuantV2(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicBlockQuantV2 failed. ERROR: %d\n", ret);
              return ret);

    // 4. (Boilerplate) Wait synchronously 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. Modify according to 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 according to 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;
  }