aclnnQuantGroupedMatmulDequantWeightNZ

📄 View Source Code

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 input x. This API is a weightNZ-specialized version of aclnnQuantGroupedMatmulDequant.
  • 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 "aclnnQuantGroupedMatmulDequantWeightNZGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the process, and then call the "aclnnQuantGroupedMatmulDequantWeightNZ" API to execute the computation.

aclnnStatus aclnnQuantGroupedMatmulDequantWeightNZGetWorkspaceSize(
  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,
  aclTensor *out,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnQuantGroupedMatmulDequantWeightNZ(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnQuantGroupedMatmulDequantWeightNZGetWorkspaceSize

  • 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, and x in the formula.
    • Empty tensors are not supported.
    • The shape supports 2 dimensions, where each dimension indicates: (m, k).
    FLOAT16 ND 2 √
    weight Input Indicates the right matrix of the input, a mandatory parameter, and weight_{quantized} in the formula. Empty tensors are not supported. Note that this API ignores the data format of weight and forcibly treats it as the FRACTAL_NZ format. INT8 FRACTAL_NZ 5 -
    weightScale Input Indicates the quantization scale of weight, a mandatory parameter, which is scale_{weight} in the formula.
    • The shape is 2D (g, n), where g and n are consistent with those of weight.
    • When 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 The group in the formula. Indicates the prefix sum result of grouping input tensor x in MoE use cases. The shape is 1-D [g]. - INT64 ND 1 √
    biasOptional Input Indicates the offset for the computation. It is an optional parameter and corresponds to the bias in the formula. Currently, only a null pointer can be passed in. - - - -
    xScaleOptional Input Indicates the quantization scale of x. Optional parameter, 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. Optional parameter. Currently, only an empty pointer can be passed in. - - - -
    smoothScaleOptional Input Indicates the smoothing coefficient of x, an optional parameter, which is scale_{smooth} in the formula.
    • The shape is 1D (k,), where k is consistent with that of x.
    • Supports empty tensors.
    FLOAT16 ND 1 √
    xQuantMode Input Specifies the quantization mode of input x. Supported values are pertoken/pertensor. For dynamic quantization, only pertoken is supported. pertoken indicates that each token (a row) has its own quantization parameters; pertensor indicates that the entire tensor uses unified 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. shape supports 2 dimensions, each dimension indicates: (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 size of the workspace to be requested on the Device side. - - - - -
    executor Output Returns the op executor, which contains the operator computation flow. - - - - -
    • 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.
  • 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 the passed parameter is a mandatory input, output, or mandatory attribute and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002
  • The input parameter is of type aclTensor and its data type is not in the supported range.
  • The storageShape of weight is not 5-dimensional.
  • aclnnAdvanceStepGetWorkspaceSize failed 561002 The input parameter is of type aclTensor and its shape is inconsistent with the preceding parameter description.

aclnnQuantGroupedMatmulDequantWeightNZ

  • Parameters

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

    aclnnStatus: return status code. For details, see aclnn return codes.

Constraints

  • Deterministic computation:

    • aclnnQuantGroupedMatmulDequantWeightNZ 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_weight_nz.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) {
  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, aclFormat formatType, aclTensor** tensor) {
  auto size = GetShapeSize(shape) * sizeof(T);
  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);
  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);

  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];
  }

  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, formatType,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

int main() {
  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);

  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, K / 32, N / 16, 16, 32};
  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, aclFormat::ACL_FORMAT_ND, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_INT8, aclFormat::ACL_FORMAT_FRACTAL_NZ, &weight);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(weightScaleHostData, weightScaleShape, &weightScaleDeviceAddr, aclDataType::ACL_FLOAT, aclFormat::ACL_FORMAT_ND, &weightScale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(groupListHostData, groupListShape, &groupListDeviceAddr, aclDataType::ACL_INT64, aclFormat::ACL_FORMAT_ND, &groupList);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(xScaleHostData, xScaleShape, &xScaleDeviceAddr, aclDataType::ACL_FLOAT, aclFormat::ACL_FORMAT_ND, &xScale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(smoothScaleHostData, smoothScaleShape, &smoothScaleDeviceAddr, aclDataType::ACL_FLOAT16, aclFormat::ACL_FORMAT_ND, &smoothScale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, aclFormat::ACL_FORMAT_ND, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  ret = aclnnQuantGroupedMatmulDequantWeightNZGetWorkspaceSize(x, weight, weightScale, groupList,
                                                bias, xScale, xOffset, smoothScale,
                                                quantMode, transposeWeight, out,
                                                &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantGroupedMatmulDequantWeightNZGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

  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);
  }

  ret = aclnnQuantGroupedMatmulDequantWeightNZ(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantGroupedMatmulDequantWeightNZ failed. ERROR: %d\n", ret); return ret);

  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

  PrintOutResult(outShape, &outDeviceAddr);

  aclDestroyTensor(x);
  aclDestroyTensor(weight);
  aclDestroyTensor(weightScale);
  aclDestroyTensor(groupList);
  aclDestroyTensor(xScale);
  aclDestroyTensor(smoothScale);
  aclDestroyTensor(out);

  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;
}