aclnnDynamicQuantV4

📄 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: Performs dynamic quantization on the input tensor. In the MOE scenario, smoothScalesOptional differs for each expert and is distinguished by the input groupIndexOptional. Supports symmetric/asymmetric quantization. Supports pertoken/pertensor/perchannel quantization modes. Compared with aclnnDynamicQuantV3, the optional input parameter dstTypeMax is added to specify the range of quantization results.

  • Formula:

    • Symmetric quantization:
      • If smoothScalesOptional is not provided:scaleOut=max⁡t(abs(x))/DTYPEMAXscaleOut=\max_{t}(abs(x))/DTYPE_{MAX} yOut=round(x/scaleOut)yOut=round(x/scaleOut)
      • If smoothScalesOptional is provided:input=x⋅smoothScalesOptionalinput = x\cdot smoothScalesOptional scaleOut=max⁡t(abs(input))/DTYPEMAXscaleOut=\max_{t}(abs(input))/DTYPE_{MAX} yOut=round(input/scaleOut)yOut=round(input/scaleOut)
    • Asymmetric quantization:
      • If smoothScalesOptional is not provided:scaleOut=(max⁡t(x)−min⁡t(x))/(DTYPEMAX−DTYPEMIN)scaleOut=(\max_{t}(x) - \min_{t}(x))/(DTYPE_{MAX} - DTYPE_{MIN}) offset=DTYPEMAX−max⁡t(x)/scaleOutoffset=DTYPE_{MAX}-\max_{t}(x)/scaleOut yOut=round(x/scaleOut+offset)yOut=round(x/scaleOut+offset)
      • If smoothScalesOptional is provided:input=x⋅smoothScalesOptionalinput = x\cdot smoothScalesOptional scaleOut=(max⁡t(input)−min⁡t(input))/(DTYPEMAX−DTYPEMIN)scaleOut=(\max_{t}(input) - \min_{t}(input))/(DTYPE_{MAX} - DTYPE_{MIN}) offset=DTYPEMAX−max⁡t(input)/scaleOutoffset=DTYPE_{MAX}-\max_{t}(input)/scaleOut yOut=round(input/scaleOut+offset)yOut=round(input/scaleOut+offset) where max⁡t\max_{t}/min⁡t\min_{t} indicates the mode of computing the maximum/minimum value: if quantMode is "pertoken", t=rowt=row, indicating that the maximum/minimum value is computed for each token; if quantMode is "pertensor", t=allt=all, indicating that the maximum/minimum value of the entire tensor is computed; if quantMode is "perchannel", t=colt=col, indicating that the maximum/minimum value is computed for each channel. DTYPEMAXDTYPE_{MAX} is the maximum value of the output data type, and DTYPEMINDTYPE_{MIN} is the minimum value of the output data type. In the HiFloat8 scenario, custom input of DTYPEMAXDTYPE_{MAX} (DTYPEMINDTYPE_{MIN}) is supported.

Function Prototype

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

aclnnStatus aclnnDynamicQuantV4GetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *smoothScalesOptional,
  const aclTensor *groupIndexOptional,
  int64_t          dstType,
  bool             isSymmetrical,
  const char      *quantMode,
  float            dstTypeMax,
  const aclTensor *yOut,
  const aclTensor *scaleOut,
  const aclTensor *offsetOut,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnDynamicQuantV4(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnDynamicQuantV4GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    x(aclTensor*) Input Tensor of the operator input. Corresponds to x in the formula.
      If the data type of the corresponding yOut is INT4, the size of the last dimension of x must be divisible by 2.
    FLOAT16, BFLOAT16 ND 2-8 √
    smoothScalesOptional (aclTensor*) Input smoothScales of the operator input. Corresponds to smoothScalesOptional in the formula description.
    • In pertoken/pertensor scenarios, when groupIndexOptional is not input, the shape dimension is the last dimension of x.
    • When groupIndexOptional is input, the shape has two dimensions. The size of the first dimension corresponds to the number of experts and cannot exceed 1024. The size of the second dimension equals the size of the last dimension of x.
    • In the perchannel scenario, the shape size is the size of the second-to-last dimension of x.
    Consistent with x. ND 1, 2 √
    groupIndexOptional (aclTensor*) Input The groupIndex of the operator input. It corresponds to groupIndexOptional in the formula description.
    • The shape supports only one dimension, and its size equals the first dimension of smoothScalesOptional.
    • If groupIndexOptional is not nullptr, smoothScalesOptional must not be nullptr.
    INT32 ND 1 √
    dstType (int64_t) Input Specifies the data type of yOut after data conversion, corresponding to DType in the formula.
    • The input range is {2, 3, 29, 34, 35, 36}, respectively corresponding to the output data types of yOut {2:INT8, 3:INT32, 29:INT4, 34:HIFLOAT8, 35:FLOAT8_E5M2, 36:FLOAT8_E4M3FN}.
    • INT32 actually consists of 8 concatenated INT4 values.
    - - - -
    isSymmetrical (bool) Input Specifies whether to perform symmetric quantization. - - - - -
    quantMode (char*) Input Specifies the quantization mode.
    • Currently, "pertoken", "pertensor", and "perchannel" are supported.
    • If quantMode is set to "pertensor" or "perchannel", groupIndexOptional must be nullptr.
    - - - -
    dstTypeMax (float) Input Specifies the range of quantization results.
      Currently supported values: 0-32768. This parameter takes effect only when dstType is 34 (hifloat8).
    - - - -
    yOut (aclTensor*) Output Quantized output tensor. Its type is specified by dstType. It is yOut in the corresponding formula.
    • If the data type is INT4, the size of the last dimension must be divisible by 2.
    • If the data type is INT32, the last dimension is 1/8 of the last dimension of x.
    • For other data types, the shape is the same as that of x.
    INT4, INT8, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8, INT32 ND 2-8 √
    scaleOut (aclTensor*) Output The scale used for quantization. It corresponds to scaleOut in the corresponding formula.
    • When quantMode is pertoken, the shape is the shape of x with the last dimension removed.
    • When quantMode is pertensor, the shape is (1,).
    • When quantMode is perchannel, the shape is the shape of x with the second-to-last dimension removed.
    FLOAT32 ND 1-7 √
    offsetOut (aclTensor*) Output Offset used for asymmetric quantization. Corresponds to offsetOut in the corresponding formula.
      Supported only when isSymmetrical is false. If isSymmetrical is true, pass nullptr for offsetOut.
    FLOAT32 ND 1-7 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied for on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains 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 input x or output parameter is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, dimensions, etc. of the parameter are not within the supported range.
    ACLNN_ERR_INNER_CREATE_EXECUTOR 561001 Failed to create aclOpExecutor internally.

aclnnDynamicQuantV4

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Workspace size allocated on the device, obtained by the first-phase API aclnnDynamicQuantV4GetWorkspaceSize.
    executor Input Op executor, containing the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation:

    • aclnnDynamicQuantV4 defaults to a deterministic implementation.
  • If the data type of yOut is INT4, the last dimension of x and yOut must be divisible by 2. Non-contiguous tensors are not supported.

  • When the data type of yOut is INT32, the last dimension of x must be divisible by 8.

  • When groupIndexOptional is used, the number of experts must not exceed the product of all dimensions of x after removing the last dimension. The values of groupIndexOptional must form a non-decreasing array of values not less than zero, and the last value must be equal to the product of all dimensions of x after removing the last dimension. If this condition is not met, the result is meaningless.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_dynamic_quant_v4.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 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 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 device/stream. For details, see the acl API reference.
  // 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.
  int rowNum = 4;
  int rowLen = 2;
  int groupNum = 2;
  std::vector<int64_t> xShape = {4, 2};
  std::vector<int64_t> smoothShape = {groupNum, rowLen};
  std::vector<int64_t> groupShape = {groupNum};
  std::vector<int64_t> yShape = {4, 2};
  std::vector<int64_t> scaleShape = {4};
  std::vector<int64_t> offsetShape = {4};

  void* xDeviceAddr = nullptr;
  void* smoothDeviceAddr = nullptr;
  void* groupDeviceAddr = nullptr;
  void* yDeviceAddr = nullptr;
  void* scaleDeviceAddr = nullptr;
  void* offsetDeviceAddr = nullptr;

  aclTensor* x = nullptr;
  aclTensor* smooth = nullptr;
  aclTensor* group = nullptr;
  aclTensor* y = nullptr;
  aclTensor* scale = nullptr;
  aclTensor* offset = nullptr;

  std::vector<aclFloat16> xHostData;
  std::vector<aclFloat16> smoothHostData;
  std::vector<int32_t> groupHostData = {2, rowNum};
  std::vector<int8_t> yHostData;
  std::vector<float> scaleHostData;
  std::vector<float> offsetHostData;
  for (int i = 0; i < rowNum; ++i) {
    for (int j = 0; j < rowLen; ++j) {
      float value1 = i * rowLen + j;
      xHostData.push_back(aclFloatToFloat16(value1));
      yHostData.push_back(0);
    }
    scaleHostData.push_back(0);
    offsetHostData.push_back(0);
  }

  for (int m = 0; m < groupNum; ++m) {
    for (int n = 0; n < rowLen; ++n) {
      float value2 = m * rowLen + n;
      smoothHostData.push_back(aclFloatToFloat16(value2));
    }
  }

  // Create the x aclTensor.
  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the smooth aclTensor.
  ret = CreateAclTensor(smoothHostData, smoothShape, &smoothDeviceAddr, aclDataType::ACL_FLOAT16, &smooth);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the group aclTensor.
  ret = CreateAclTensor(groupHostData, groupShape, &groupDeviceAddr, aclDataType::ACL_INT32, &group);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create y aclTensor.
  ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_INT8, &y);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create scale aclTensor.
  ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create offset aclTensor.
  ret = CreateAclTensor(offsetHostData, offsetShape, &offsetDeviceAddr, aclDataType::ACL_FLOAT, &offset);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API. Replace it with the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  const char* quantMode = "pertoken";
  float dstTypeMax = 0.0;

  // Call the first-phase API of aclnnDynamicQuantV4.
  ret = aclnnDynamicQuantV4GetWorkspaceSize(x, smooth, group, 2, false, quantMode, dstTypeMax, y, scale, offset, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicQuantV4GetWorkspaceSize 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 aclnnDynamicQuantV4.
  ret = aclnnDynamicQuantV4(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicQuantV4 failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) Wait for the task execution to complete synchronously.
  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 modify it based on the specific API definition.
  PrintOutResult(yShape, &yDeviceAddr);

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

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

  return 0;
}