aclnnQuantGroupedMatmulDequant

Applicable Products

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

Function

  • Description: performs quantization, grouped matrix multiplication, and dequantization on the input x.
  • Formula: 1. If smoothScaleOptional is provided, then
    $$ x = x\cdot scale_{smooth} $$
    2.If xScaleOptional is not input, dynamic quantization is applied, and the quantization coefficient of x must be calculated.
    $$ scale_{x}=row\_max(abs(x))/max_{quantDataType} $$
    3.Quantization
    $$ x_{quantized}=round(x/scale_{x}) $$
    4.Grouped matrix multiplication + dequantization
    • 4.1 If the data type of $scale_{weight}$ is FLOAT32:
    $$ \begin{aligned} x^{*}_{quantized} &= x_{quantized}[group[i-1]:group[i]]\\ out^{*}_{quantized} &= out_{quantized}[group[i-1]:group[i]]\\ scale^{*}_{x} &= \begin{cases} scale_{x}[group[i-1]:group[i]] & pertoken \\ scale_{x} & pertensor \\ \end{cases} \\ out^{*}_{quantized} &= (x^{*}_{quantized}@weight_{quantized}[i] + bias) * scale_{weight}[i] * scale^{*}_{x} \end{aligned} $$
    • 4.2 If the data type of $scale_{weight}$ is INT64:
      $$ x^{*}_{quantized} = x_{quantized}[group[i-1]:group[i]] \\ out^{*}_{quantized} = out_{quantized}[group[i-1]:group[i]] \\ scale_{weight} = torch.tensor(np.frombuffer(scale_{weight}.numpy().astype(np.int32).\\tobytes(), dtype=np.float32)).reshape(scale_{weight}) \\ out^{*}_{quantized} = (x^{*}_{quantized}@weight_{quantized}[i] + bias) * scale_{weight}[i] $$
      Special note: In use case 4.2 described above, $scale_{weight}$ has already undergone matrix multiplication with $scale_{x}$ before being passed in. Therefore, the operator omits this step during internal computation, which requires pertensor static quantization. That is, $scale_{weight}$ must be processed as follows before input to obtain data of the INT64 type:
      $$ scale_{weight} = scale_{weight} * scale_{x} \\ scale_{weight} = torch.tensor(np.frombuffer(scale_{weight}.numpy().astype(np.float32). \\tobytes(), dtype=np.int32).astype(np.int64)).reshape(scale_{weight}) $$

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnQuantGroupedMatmulDequantGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size according to the workflow, and then call the "aclnnQuantGroupedMatmulDequant" API to perform the computation.

aclnnStatus aclnnQuantGroupedMatmulDequantGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *weight,
  const aclTensor *weightScale,
  const aclTensor *groupList,
  const aclTensor *biasOptional,
  const aclTensor *xScaleOptional,
  const aclTensor *xOffsetOptional,
  const aclTensor *smoothScaleOptional,
  char            *xQuantMode,
  bool             transposeWeight,
  const aclTensor *out,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnQuantGroupedMatmulDequant(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnQuantGroupedMatmulDequantGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x Input Indicates the left matrix of the input, a mandatory parameter, that is, x in the formula.
    • Empty tensors are not supported.
    • The shape supports 2 dimensions, and each dimension indicates: (m, k).
    FLOAT16 ND 2 √
    weight Input Indicates the right matrix of the input, a mandatory parameter, that is, weight_{quantized} in the formula. Empty tensors are not supported. INT8 FRACTAL_NZ, ND 3, 5 √
    weightScale Input Indicates the quantization coefficient of weight, which is a mandatory parameter and corresponds to scale_{weight} in the formula.
    • The shape is two-dimensional (g, n), where g and n are consistent with g and n of weight.
    • If the data type is INT64, the data type of xScaleOptional must be FLOAT16 and the value of xQuantMode must be pertensor.
    FLOAT32, INT64 ND 2 √
    groupList Input group in the formula. Indicates the prefix sum result of grouping input tensor x in MoE use cases. The shape is 1D [g]. - INT64 ND 1 √
    biasOptional Input Indicates the bias of the computation. Optional parameter. Corresponds to bias in the formula. Currently, only passing in a null pointer is supported. - - - -
    xScaleOptional Input Indicates the quantization scale of x, an optional parameter, which is scale_{x} in the formula.
    • When xQuantMode is pertensor, the shape is 1D (1,); when xQuantMode is pertoken, the shape is 1D (m,), where m is consistent with the m of input x. If it is empty, dynamic quantization is used.
    • When the data type is FLOAT16, the data type of weightScale must be INT64, and the value of xQuantMode must be pertensor.
    • Empty tensors are supported.
    FLOAT32, FLOAT16 ND 1 √
    xOffsetOptional Input Indicates the offset of x, an optional parameter. Currently, only a null pointer can be passed. - - - -
    smoothScaleOptional Input Indicates the smoothing coefficient of x, an optional parameter, corresponding to scale_{smooth} in the formula.
    • The shape is 1D (k,), where k is consistent with the k of x.
    • Empty tensors are supported.
    FLOAT16 ND 1 √
    xQuantMode Input Specifies the quantization mode of input x. Supported values are pertoken/pertensor. Only pertoken is supported for dynamic quantization. pertoken indicates that each token (row) has its own quantization parameters; pertensor indicates that the entire tensor uses the same quantization parameters. STRING - - -
    transposeWeight Input Indicates whether the input weight is transposed. Currently, only true is supported. BOOL - - -
    out Output Calculation result, mandatory parameter, corresponding to out in the formula. 2D shapes are supported, with dimensions (m, n), where m is consistent with the m of x, and n is consistent with the n of weight. FLOAT16 ND 2 ×
    workspaceSize Output Returns the workspace size to be allocated on the Device side. - - - - -
    executor Output Returns the op executor that contains the operator computation flow. - - - - -
    • In ND format, the shape of weight supports 3 dimensions.
      • When transposeWeight is true, the dimensions are: (g, n, k).
      • When transposeWeight is false, the dimensions are: (g, k, n).
    • In FRACTAL_NZ format, the weight shape supports 5 dimensions.
      • If transposeWeight is true, the dimensions are (g, k1, n1, n0, k0), where k0 = 32, n0 = 16, and k1 and k of x must meet the following relationship: ceilDiv(k, 32) = k1.
      • If transposeWeight is false, the dimensions are (g, n1, k1, k0, n0), where k0 = 16, n0 = 32, and k1 and k of x must meet the following relationship: ceilDiv(k, 16) = k1.
      • Use the aclnnCalculateMatmulWeightSizeV2 API and the aclnnTransMatmulWeight API to convert the input Format from ND to FRACTAL_NZ.
  • 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:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 If a required input, output, or required attribute is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002
  • If the input parameter is of type aclTensor and its data type is not within the supported range.
  • n or k in the shape of weight is not divisible by 16.
  • aclnnAdvanceStepGetWorkspaceSize failed 561002 If the input parameter is of type aclTensor and its shape does not match the preceding parameter description.

aclnnFatreluMul

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Workspace size allocated on the Device side, obtained through the first-phase API aclnnQuantGroupedMatmulDequantGetWorkspaceSize.
    executor Input Op executor, including the computation flow of the operator.
    stream Input Stream for executing tasks.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnQuantGroupedMatmulDequant defaults to a deterministic implementation.
  • n and k must both be integer multiples of 16.

  • If the data type of weightScale is INT64, the data type of xScaleOptional must be FLOAT16 and the value of xQuantMode must be pertensor; if the data type of xScaleOptional is FLOAT16, the data type of weightScale must be INT64 and the value of xQuantMode must be pertensor.

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_quant_grouped_matmul_dequant.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 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 data to 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 as required by the API.
  int G = 4;
  int M = 64;
  int K = 256;
  int N = 512;

  char quantMode[16] = "pertoken";
  bool transposeWeight = true;

  std::vector<int64_t> xShape = {M,K};
  std::vector<int64_t> weightShape = {G,N,K};
  std::vector<int64_t> weightScaleShape = {G,N};
  std::vector<int64_t> xScaleShape = {M};
  std::vector<int64_t> smoothScaleShape = {K};
  std::vector<int64_t> outShape = {M,N};
  std::vector<int64_t> groupListShape = {G};

  void* xDeviceAddr = nullptr;
  void* weightDeviceAddr = nullptr;
  void* weightScaleDeviceAddr = nullptr;
  void* groupListDeviceAddr = nullptr;
  void* xScaleDeviceAddr = nullptr;
  void* smoothScaleDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;

  aclTensor* x = nullptr;
  aclTensor* weight = nullptr;
  aclTensor* weightScale = nullptr;
  aclTensor* groupList = nullptr;
  aclTensor* bias = nullptr;
  aclTensor* xScale = nullptr;
  aclTensor* xOffset = nullptr;
  aclTensor* smoothScale = nullptr;
  aclTensor* out = nullptr;

  std::vector<uint16_t> xHostData(GetShapeSize(xShape));
  std::vector<uint8_t> weightHostData(GetShapeSize(weightShape));
  std::vector<float> weightScaleHostData(GetShapeSize(weightScaleShape));
  std::vector<int64_t> groupListHostData(GetShapeSize(groupListShape));
  groupListHostData[0] = 7;
  groupListHostData[1] = 32;
  groupListHostData[2] = 40;
  groupListHostData[3] = 64;
  std::vector<float> xScaleHostData(GetShapeSize(xScaleShape));
  std::vector<uint16_t> smoothScaleHostData(GetShapeSize(smoothScaleShape));
  std::vector<uint16_t> outHostData(GetShapeSize(outShape));

  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_INT8, &weight);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(weightScaleHostData, weightScaleShape, &weightScaleDeviceAddr, aclDataType::ACL_FLOAT, &weightScale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(groupListHostData, groupListShape, &groupListDeviceAddr, aclDataType::ACL_INT64, &groupList);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(xScaleHostData, xScaleShape, &xScaleDeviceAddr, aclDataType::ACL_FLOAT, &xScale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(smoothScaleHostData, smoothScaleShape, &smoothScaleDeviceAddr, aclDataType::ACL_FLOAT16, &smoothScale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API, and replace it with the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Call the first-phase API of aclnnQuantGroupedMatmulDequant.
  ret = aclnnQuantGroupedMatmulDequantGetWorkspaceSize(x, weight, weightScale, groupList,
                                                bias, xScale, xOffset, smoothScale,
                                                quantMode, transposeWeight, out,
                                                &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantGroupedMatmulDequantGetWorkspaceSize 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 aclnnQuantGroupedMatmulDequant.
  ret = aclnnQuantGroupedMatmulDequant(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantGroupedMatmulDequant failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Synchronize and wait for the task 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 on the Device side to the host side. Modify this part based on the specific API definition.
  PrintOutResult(outShape, &outDeviceAddr);

  // 6. Release aclTensor and aclScalar. Modify this part based on the specific API definition.
  aclDestroyTensor(x);
  aclDestroyTensor(weight);
  aclDestroyTensor(weightScale);
  aclDestroyTensor(groupList);
  aclDestroyTensor(xScale);
  aclDestroyTensor(smoothScale);
  aclDestroyTensor(out);

  // 7. Release device resources.
  aclrtFree(xDeviceAddr);
  aclrtFree(weightDeviceAddr);
  aclrtFree(weightScaleDeviceAddr);
  aclrtFree(groupListDeviceAddr);
  aclrtFree(xScaleDeviceAddr);
  aclrtFree(smoothScaleDeviceAddr);
  aclrtFree(outDeviceAddr);

  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}