aclnnQuantMatmulDequant

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, matmul, and dequantization on input x.

  • Formula: 1 If smoothScaleOptional is passed in,

    x=x⋅scalesmoothx = x\cdot scale_{smooth}

    2 If xScaleOptional is not passed in, dynamic quantization is used, and the quantization coefficient of x needs to be calculated.

    scalex=row_max(abs(x))/maxquantDataTypescale_{x}=row\_max(abs(x))/max_{quantDataType}

    3 Quantization

    xquantized=round(x/scalex)x_{quantized}=round(x/scale_{x})

    4 Matmul+Dequantization

    • 4.1 If the data type of the input scaleweightscale_{weight} is FLOAT32:

      out=(xquantized@weightquantized+bias)∗scaleweight∗scalexout = (x_{quantized}@weight_{quantized} + bias) * scale_{weight} * scale_{x}
    • 4.2 If the data type of the input scaleweightscale_{weight} is INT64:

      scaleweight=torch.tensor(np.frombuffer(scaleweight.numpy().astype(np.int32).tobytes(),dtype=np.float32))out=(xquantized@weightquantized+bias)∗scaleweightscale_{weight} = torch.tensor(np.frombuffer(scale_{weight}.numpy().astype(np.int32).tobytes(), dtype=np.float32)) \\ out = (x_{quantized}@weight_{quantized} + bias) * scale_{weight}

      Special note: If use case 4.2 above applies, scaleweightscale_{weight} has already been multiplied by scalexscale_{x} before being passed in. Therefore, the operator skips this step in internal computation, which requires the pertensor static quantization use case. That is, process scaleweightscale_{weight} as follows before passing it in to obtain INT64 data:

      scaleweight=scaleweight∗scalexscaleweight=torch.tensor(np.frombuffer(scaleweight.numpy().astype(np.float32).tobytes(),dtype=np.int32).astype(np.int64))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))

Function Prototype

Each operator uses a two-phase API. First, call the "aclnnQuantMatmulDequantGetWorkspaceSize" API to obtain input parameters and calculate the required workspace size based on the workflow. Then, call the "aclnnQuantMatmulDequant" API to perform the computation.

aclnnStatus aclnnQuantMatmulDequantGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *weight,
  const aclTensor *weightScale,
  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 aclnnQuantMatmulDequant(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnQuantMatmulDequantGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Indicates the input left matrix, x in the formula.
    • Supports a 2D shape, with each dimension denoting (m, k).
    • Empty tensors are not supported.
    FLOAT16 ND 2 √
    weight (aclTensor*) Input Indicates the input right matrix, weight_{quantized} in the formula. Empty tensors are not supported. INT8 FRACTAL_NZ, ND 2, 4 √
    weightScale (aclTensor*) Input Indicates the quantization scale of weight, scale_{weight} in the formula.
    • The shape is 1D (n,), where n is the same as that of weight.
    • Supports empty tensors.
    • If the data type is INT64, it is a mandatory requirement that the data type of xScaleOptional is FLOAT16 and the value of xQuantMode is pertensor.
    FLOAT32, INT64 ND 1 √
    biasOptional (aclTensor*) Optional input Indicates the offset of the computation, that is, bias in the formula. Currently, only a null pointer can be passed in. - - - -
    xScaleOptional (aclTensor*) Optional input Indicates the quantization scale of x, 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 the same as that of input x. If it is empty, dynamic quantization is used.
    • Supports empty tensors.
    • When the data type is FLOAT16, it is a mandatory requirement that the data type of weightScale is INT64 and the value of xQuantMode is pertensor.
    FLOAT32, FLOAT16 ND - √
    xOffsetOptional (aclTensor*) Optional input Indicates the offset of x. Currently, only a null pointer can be passed in. - - - -
    smoothScaleOptional (aclTensor*) Optional input Indicates the smoothing factor of x, scale_{smooth} in the formula.
    • shape is 1D (k,), where k is the same as the k of x.
    • Supports empty tensor.
    FLOAT16 ND 1 √
    xQuantMode (char*) Input Specifies the quantization mode of input x. Value options: pertoken/pertensor. Only pertoken is supported for dynamic quantization. pertoken indicates that each token (a row) has its own quantization parameters; pertensor indicates that the entire tensor uses the same quantization parameters. STRING - - -
    transposeWeight (bool) Input Indicates whether the input weight is transposed. Currently, only true is supported. BOOL - - -
    out (aclTensor*) Output Computation result, that is, out in the formula. Two-dimensional shape is supported. Each dimension: (m, n). m is the same as that of x, and n is the same as that of weight. FLOAT16 ND 2 √
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied by the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor that contains the operator computation process. - - - - -
    • For the weight parameter in ND format, the shape supports 2 dimensions.
      • When transposeWeight is true, the dimensions indicate: (n, k).
      • When transposeWeight is false, the dimensions indicate: (k, n).
    • For the weight parameter in FRACTAL_NZ format, the shape supports 4 dimensions.
      • When transposeWeight is true, the dimensions indicate: (k1, n1, n0, k0), where k0 = 32, n0 = 16, and k1 must meet the following relationship with k of x: ceilDiv(k, 32) = k1.
      • When transposeWeight is false, each dimension indicates: (n1, k1, k0, n0), where k0 = 16, n0 = 32, and k1 and k of x must satisfy 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 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 If a passed-in parameter is a required input, output, or required attribute and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002
    • If a passed-in parameter is of the aclTensor type and its data type is not within the supported range.
    • n or k in the shape of weight is not divisible by 16.
    ACLNN_ERR_INNER_TILING_ERROR 561002 If a passed-in parameter is of the aclTensor type and its shape does not match the preceding parameter description.

aclnnQuantMatmulDequant

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied by the Device side.
    workspaceSize Input Workspace size applied by the Device side, obtained by the first-phase API aclnnQuantMatmulDequantGetWorkspaceSize.
    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

  • Determinism description:

    • Atlas training products, Atlas inference products: aclnnQuantMatmulDequant 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

Sample code is as follows, 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_quant_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, 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 memory on the device.
  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 data on the host to memory on the device.
  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 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) Device/stream initialization. For details, see the acl API manual.
  // 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 input and output. Customize the construction based on the API.
  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 = {N,K};
  std::vector<int64_t> weightScaleShape = {N};
  std::vector<int64_t> xScaleShape = {M};
  std::vector<int64_t> smoothScaleShape = {K};
  std::vector<int64_t> outShape = {M,N};

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

  aclTensor* x = nullptr;
  aclTensor* weight = nullptr;
  aclTensor* weightScale = 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<uint16_t> weightScaleHostData(GetShapeSize(weightScaleShape));
  std::vector<uint16_t> 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(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. Replace it with the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Call the first-phase API of aclnnQuantMatmulDequant.
  ret = aclnnQuantMatmulDequantGetWorkspaceSize(x, weight, weightScale,
                                                bias, xScale, xOffset, smoothScale,
                                                quantMode, transposeWeight, out,
                                                &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulDequantGetWorkspaceSize 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 second-phase API aclnnQuantMatmulDequant.
  ret = aclnnQuantMatmulDequant(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulDequant 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 values and copy the results from device memory to the host side. Modify the code based on the specific API definition.
  PrintOutResult(outShape, &outDeviceAddr);

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

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

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

  return 0;
}