aclnnFusedQuantMatmulWeightNz

Applicable Products

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

Function

  • Description: Fused quantized matrix multiplication and Gelu computation.

  • Formula:

    • x1Scale, bias INT32 (no offset in this scenario):

      qbmmout=(x1@x2+bias)∗x2Scale∗x1Scaleqbmmout = (x1@x2 + bias) * x2Scale * x1Scale
    • x1Scale, bias BFLOAT16/FLOAT16/FLOAT32 (this scenario has no offset):

      qbmmout=x1@x2∗x2scale∗x1Scale+biasqbmmout = x1@x2 * x2scale * x1Scale + bias
    • x1Scale without bias:

      qbmmout=x1@x2∗x2Scale∗x1Scaleqbmmout = x1@x2 * x2Scale * x1Scale
    • The OP type is defined by the fusedOpType input and supports the following:

      • gelu_tanh operation:

        out=gelu_tanh(qbmmout)out = gelu\_tanh(qbmmout)
      • gelu_erf operation:

        out=gelu_erf(qbmmout)out = gelu\_erf(qbmmout)

Function Prototype

Each operator uses a two-phase API. Call the "aclnnFusedQuantMatmulWeightNzGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process. Then call the "aclnnFusedQuantMatmulWeightNz" API to perform the computation.

aclnnStatus aclnnFusedQuantMatmulWeightNzGetWorkspaceSize(
  const aclTensor *x1,
  const aclTensor *x2,
  const aclTensor *x1Scale,
  const aclTensor *x2Scale,
  const aclTensor *yScaleOptional,
  const aclTensor *x1OffsetOptional,
  const aclTensor *x2OffsetOptional,
  const aclTensor *yOffsetOptional,
  const aclTensor *biasOptional,
  const aclTensor *x3Optional,
  const char      *fusedOpType,
  int64_t          groupSizeOptional,
  aclTensor       *out,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnFusedQuantMatmulWeightNz(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnFusedQuantMatmulWeightNzGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x1 Input The input x1 in the formula.
    • Only non-contiguous tensor is supported when the last m and k axes are transposed. Non-contiguous tensors are not supported along other axes.
    • The size of the last dimension cannot exceed 65535.
    INT4, INT8, INT32 ND 2-6 √
    x2 Input The input x2 in the formula.
    • Supports the AI processor affinity data layout.
    • The last dimension size cannot exceed 65535.
    INT4, INT8, INT32 NZ 2-6 √
    x1Scale Input Quantization parameter, input x1Scale in the formula. - FLOAT32 ND 1 -
    x2Scale Input Quantization parameter. Input x2Scale in the formula. - FLOAT32, BFLOAT16 ND 1 -
    yScaleOptional Input Quantization scale parameter of output y, used for static quantization. Reserved parameter, not supported in the current version. Need to pass in nullptr. - - - -
    x1OffsetOptional Input The input x1Offset in the formula. Reserved parameter, not supported in the current version, need to pass in nullptr. - - - -
    x2OffsetOptional Input The input x2Offset in the formula. Reserved parameter. Not supported in the current version. Need to pass in nullptr. - - - -
    yOffsetOptional Input Input yOffset in the formula. Reserved parameter. Not supported in the current version. Need to pass in nullptr. - - - -
    biasOptional Input Input bias in the formula. Pass nullptr when there is no bias. INT32, FLOAT32, BFLOAT16, FLOAT16 ND 1, 3 -
    x3Optional Input Input for the fused binary operation. Only fused unary operations are currently supported. Reserved parameter, not supported in the current version. Need to pass in nullptr. - - - -
    fusedOpType Input Input fusedOpType in the formula. Specifies the fusion mode supported by the QuantBatchMatmul operator. The value of the fusion mode must be "gelu_erf" or "gelu_tanh". STRING - - -
    groupSizeOptional Input Used to pass in the quantization group sizes along the m, n, and k dimensions. Reserved parameter, not supported in the current version. It is recommended to pass in 0. - - - -
    out Output Output out in the formula. - FLOAT16, BFLOAT16 ND 2-6 ✓
    workspaceSize Output Returns the workspace size that needs to be applied on the Device side. - - - - -
    executor Output Returns the op executor containing the operator computation flow. - - - - -
  • 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 x1, x2, x1Scale, x2Scale, or out passed in is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The shape of x1, x2, biasOptional, x1Scale, x2Scale, or out does not meet the verification conditions.
    The data type and data format of x1, x2, biasOptional, x1Scale, x2Scale, or out are not within the supported range.
    x1, x2, biasOptional, x1Scale, x2Scale, or out is an empty tensor.
    The passed-in fusedOpType is not one of "gelu_tanh" or "gelu_erf".
    The passed-in yScaleOptional, x1OffsetOptional, x2OffsetOptional, yOffsetOptional, x3Optional, or groupSizeOptional parameters are currently not supported.

aclnnFusedQuantMatmulWeightNz

  • Parameters:

    Parameter Input/Output Description
    workspace Input The workspace memory address applied by the Device side.
    workspaceSize Input The workspace size applied by the Device side, obtained by calling the first-phase API aclnnFusedQuantMatmulWeightNzGetWorkspaceSize.
    executor Input Op executor, containing the operator computation process.
    stream Input Stream for executing the task.
  • Return value

    aclnnStatus: return value, which is a status code. For details, see aclnn return code.

Constraints

  • Deterministic computation:

    • Atlas training products and Atlas inference products: aclnnFusedQuantMatmulWeightNz defaults to a deterministic implementation.
  • The input and output support the following data type combinations:

x1x2x1Scalex2Scalex2OffsetOptionalyScaleOptionalbiasOptionalyOffsetOptionalOut
INT8INT8FLOAT32FLOAT32/BFLOAT16nullnullnull/INT32/BFLOAT16/FLOAT32nullBFLOAT16
INT8INT8FLOAT32FLOAT32nullnullnull/INT32/FLOAT16/FLOAT32nullFLOAT16
INT4/INT32INT4/INT32FLOAT32FLOAT32/BFLOAT16nullnullnull/INT32/BFLOAT16/FLOAT32nullBFLOAT16
INT4/INT32INT4/INT32FLOAT32FLOAT32nullnullnull/INT32/FLOAT16/FLOAT32nullFLOAT16
  • The current API supports x1 pertoken quantization and x2 perchannel/pertensor quantization. The input dtype combination constraints of x1, x2, x1Scale, and x2Scale supported by different quantization modes are as follows:
    • The x1 data type supports INT8, INT32, and INT4.
      • When the data type is INT32 or INT4, it is an INT4 quantization scenario:
        • Currently, only ND input is supported.
        • Currently, only non-transposed input is supported.
        • The inner axis of x1 must be an even number.
      • When the data type is INT32, each INT32 data stores eight INT4 data values, with the corresponding dimension representation: (batch, m, k // 8). k must be a multiple of 8.
    • x2 supports INT8, INT32, and INT4 data types.
      • This API supports only the NZ format for x2, in which case k and n cannot be 1.
      • When the data type is INT32, each INT32 value stores 8 INT4 values.
      • Use the aclnnConvertWeightToINT4Pack API to convert the data format of x2 from INT32 (1 int32 stores 1 int4 in the 0-3 bits) to INT32 (1 int32 stores 8 int4) or INT4 (1 int4 represents 1 int4). For details, see aclnnConvertWeightToINT4Pack API.
      • For the AI processor-affine data layout format, the shape supports 4 to 8 dimensions.
        • When transposed, the dimensions are (batch, k1, n1, n0, k0), where batch is optional, k0 = 32, and n0 = 16. The k in the x1 shape and the k1 in the x2 shape must satisfy the following relationship: ceil(k / 32) = k1.
        • When not transposed, the dimensions are (batch, n1, k1, k0, n0), where batch is optional, k0 = 16, and n0 = 32. The k in the x1 shape and the k1 in the x2 shape must satisfy the following relationship: ceil(k / 16) = k1.
        • You can use the aclnnCalculateMatmulWeightSizeV2 and aclnnTransMatmulWeight APIs to convert the input format from ND to the AI processor-affine data layout format.
    • x1Scale constraints are as follows:
      • The shape supports 1D with a shape of (m,). The data type supports FLOAT32.
    • x2Scale constraints are as follows:
      • The shape supports 1D with a shape of (n,) or (1,), where n is consistent with n of x2. The data type supports FLOAT32 and BFLOAT16.
    • Constraints for biasOptional are as follows:
      • The shape supports 1D and 3D. In the INT4 quantization scenario, only 1D biasOptional is supported, with the shape (n). For 3D, the biasOptional shape is (batch, 1, n).
      • The data type supports int32, float32, bfloat16, or float16.
    • Constraints for out are as follows:
      • The shape supports 2D to 6D, (batch, m, n). The data type supports FLOAT16 and BFLOAT16.

Example

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

  • Atlas A3 products, Atlas A2 products:

x1 is INT8, x2 is INT8, x1Scale is FLOAT32, and x2Scale is FLOAT32.

#include <iostream>
#include <memory>
#include <vector>

#include "acl/acl.h"
#include "aclnnop/aclnn_fused_quant_matmul_weight_nz.h"
#include "aclnnop/aclnn_trans_matmul_weight.h"

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define CHECK_FREE_RET(cond, return_expr) \
    do {                                  \
        if (!(cond)) {                    \
            Finalize(deviceId, stream);   \
            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;
}

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

void Finalize(int32_t deviceId, aclrtStream stream)
{
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
}

template <typename T>
int CreateAclTensorX2(
    const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
    aclTensor** tensor)
{
    auto size = static_cast<uint64_t>(GetShapeSize(shape));

    const aclIntArray* mat2Size = aclCreateIntArray(shape.data(), shape.size());
    auto ret = aclnnCalculateMatmulWeightSizeV2(mat2Size, dataType, &size);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCalculateMatmulWeightSizeV2 failed. ERROR: %d\n", ret); return ret);
    size *= sizeof(T);

    // Call aclrtMalloc to allocate memory on the device side.
    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 the host-side data to the 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);

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

    std::vector<int64_t> storageShape;
    storageShape.push_back(GetShapeSize(shape));

    // Call aclCreateTensor to create an aclTensor
    *tensor = aclCreateTensor(
        shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, storageShape.data(),
        storageShape.size(), *deviceAddr);
    return 0;
}

int aclnnFusedQuantMatmulWeightNzTest(int32_t deviceId, 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. Custom construction is required based on the API.
    std::vector<int64_t> x1Shape = {5, 32};
    std::vector<int64_t> x2Shape = {32, 32};
    std::vector<int64_t> x1ScaleShape = {5};
    std::vector<int64_t> x2ScaleShape = {32};
    std::vector<int64_t> outShape = {5, 32};

    void* x1DeviceAddr = nullptr;
    void* x2DeviceAddr = nullptr;
    void* x1ScaleDeviceAddr = nullptr;
    void* x2ScaleDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* x1 = nullptr;
    aclTensor* x2 = nullptr;
    aclTensor* x1Scale = nullptr;
    aclTensor* x2Scale = nullptr;
    aclTensor* out = nullptr;
    std::vector<int8_t> x1HostData(5 * 32, 1);
    std::vector<int8_t> x2HostData(32 * 32, 1);
    std::vector<float> x1ScaleHostData(5, 1);
    std::vector<float> x2ScaleHostData(32, 1);
    std::vector<uint16_t> outHostData(5 * 32, 1); // It is actually float16 half precision.
    // Create the x1 aclTensor
    ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_INT8, &x1);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x1TensorPtr(x1, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> x1DeviceAddrPtr(x1DeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the x2 aclTensor in the AI processor affinity data layout format
    ret = CreateAclTensorX2(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_INT8, &x2);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x2HPTensorPtr(x2, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> x2HPDeviceAddrPtr(x2DeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the x1Scale aclTensor
    ret = CreateAclTensor(x1ScaleHostData, x1ScaleShape, &x1ScaleDeviceAddr, aclDataType::ACL_FLOAT, &x1Scale);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x1ScaleTensorPtr(x1Scale, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> x1ScaleDeviceAddrPtr(x1ScaleDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the x2Scale aclTensor
    ret = CreateAclTensor(x2ScaleHostData, x2ScaleShape, &x2ScaleDeviceAddr, aclDataType::ACL_FLOAT, &x2Scale);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x2ScaleTensorPtr(x2Scale, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> x2ScaleDeviceAddrPtr(x2ScaleDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the out aclTensor
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> outTensorPtr(out, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> outDeviceAddrPtr(outDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    int64_t groupSize = 0;
    const char fusedOpType[] = "gelu_tanh";

    // 3. Call the CANN operator library API. Replace it with the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    void* workspaceAddr = nullptr;

    // Call the aclnnTransMatmulWeight first-phase API.
    ret = aclnnTransMatmulWeightGetWorkspaceSize(x2, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeightGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);
    // Allocate device memory using the workspaceSize calculated by the first-phase API.
    std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtrTrans(nullptr, aclrtFree);
    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);
        workspaceAddrPtrTrans.reset(workspaceAddr);
    }
    // Call the aclnnTransMatmulWeight second-phase API.
    ret = aclnnTransMatmulWeight(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeight failed. ERROR: %d\n", ret); return ret);

    // Call the aclnnFusedQuantMatmulWeightNz first-phase API.
    workspaceSize = 0;
    ret = aclnnFusedQuantMatmulWeightNzGetWorkspaceSize(
        x1, x2, x1Scale, x2Scale, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, fusedOpType, groupSize, out,
        &workspaceSize, &executor);

    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedQuantMatmulWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);
    // Allocate device memory using the workspaceSize calculated by the first-phase API.

    std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtrNZ(nullptr, aclrtFree);
    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);
        workspaceAddrPtrNZ.reset(workspaceAddr);
    }
    // Call the aclnnFusedQuantMatmulWeightNz second-phase API.
    ret = aclnnFusedQuantMatmulWeightNz(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedQuantMatmulWeightNz failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Wait synchronously until the task execution is 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 the host side. Modify it according to the definition of the specific API.
    auto size = GetShapeSize(outShape);
    std::vector<uint16_t> resultData(
        size, 0); // In C, fp16 data cannot be printed directly. Read the data as uint16 and manually convert it to fp16 through binary representation.
    ret = aclrtMemcpy(
        resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, 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 ret);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("result[%ld] is: %u\n", i, resultData[i]);
    }
    return ACL_SUCCESS;
}

int main()
{
    // 1. (boilerplate) Initialize device/stream. For details, see the acl API manual.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = aclnnFusedQuantMatmulWeightNzTest(deviceId, stream);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedQuantMatmulWeightNzTest failed. ERROR: %d\n", ret); return ret);

    Finalize(deviceId, stream);
    return 0;
}