aclnnFlatQuant

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: 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: This fused operator performs two small matrix multiplications on the input matrix x at a time, that is, right-multiplying the input matrix by kroneckerP2 and left-multiplying it by kroneckerP1, and then quantizes the matrix multiplication result. Currently, the pertoken and pergroup quantization modes are supported, corresponding to the INT4 and FLOAT4_E2M1 quantized output types respectively.

  • Matrix multiplication formula:

    1. Input x is right-multiplied by kroneckerP2:

      x′=x@kroneckerP2x' = x @ kroneckerP2
    2. Left-multiply x' by kroneckerP1:

      x′′=kroneckerP1@x′x'' = kroneckerP1@x'
  • Quantization calculation mode:

    pertoken quantization mode:

    1. Compute the maximum absolute value along dimension 0 of x'' and divide it by (7 / clipRatio) to calculate the quantization scale for quantization to the INT4 format:

      quantScale=[max(abs(x′′[0,:,:])),max(abs(x′′[1,:,:])),...,max(abs(x′′[M−1,:,:]))]/(7/clipRatio)quantScale = [max(abs(x''[0,:,:])),max(abs(x''[1,:,:])),...,max(abs(x''[M-1,:,:]))]/(7 / clipRatio)
    2. Calculate the output out:

      out=x′′/quantScaleout = x'' / quantScale

    pergroup quantization mode

    1. After matrix multiplication, x'' has a shape of [M,N1,N2]. To calculate mx_quantize in the pergroup quantization mode, reshape it to [M,N1*N2], denoted as x2.

    2. Group x2 along the second dimension by groupsize. Each group contains elements e0,e1...e31. Calculate emax.

      emax=max(e0,e1....e31)emax = max(e0,e1....e31)
    3. Calculate reduceMaxValue and sharedExp.

      reduceMaxValue=log2(reduceMax(x2),groupSize=32)reduceMaxValue = log2(reduceMax(x2),groupSize=32) sharedExp[M,N1∗N2/32]=reduceMaxValue−emaxsharedExp[M,N1*N2/32] = reduceMaxValue -emax
    4. Calculate quantScale.

      quantScale[M,N1∗N2/32]=2sharedExp[M,N1∗N2/32]quantScale[M,N1*N2/32] = 2 ^ {sharedExp[M,N1*N2/32]}
    5. One quantScale is shared per groupsize. Calculate out.

      out=x2/quantScaleout = x2 / quantScale

Function Prototype

Each operator uses a two-phase API. First call the aclnnFlatQuantGetWorkspaceSize API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the aclnnFlatQuant API to perform the computation.

aclnnStatus aclnnFlatQuantGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *kroneckerP1,
  const aclTensor *kroneckerP2,
  double           clipRatio,
  aclTensor       *out,
  aclTensor       *quantScale,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnFlatQuant(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnFlatQuantGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    x (aclTensor*) Input Raw input data, corresponding to `x` in the formula.
    • Empty tensors are not supported.
    • The shape is [M, N1, N2], where M is not greater than 262144 and N1 and N2 are not greater than 256.
    • If the data type of out is INT32, N2 must be a multiple of 8.
    • If the data type of out is INT4, N2 must be an even number.
    • If the data type of out is FLOAT4_E2M1, N2 must be an even number.
    FLOAT16, BFLOAT16 ND 3 √
    kroneckerP1 (aclTensor*) Input Input calculation matrix 1, corresponding to `kroneckerP1` in the formula.
    • Empty tensors are not supported.
    • The shape is [N1, N1], where N1 is the same as the N1 dimension of x.
    • The data type is the same as the data type of input x.
    FLOAT16, BFLOAT16 ND 2 √
    kroneckerP2 (aclTensor*) Input Calculation matrix 2 for input, corresponding to `kroneckerP2` in the formula.
    • Empty tensors are not supported.
    • The shape is [N2, N2], where N2 is the same as the N2 dimension of x. The shape [0,0] is supported only in the perGroup scenario, indicating that the operator does not use the right matrix for computation and only performs left matrix multiplication.
    • The data type is the same as the data type of input x.
    FLOAT16, BFLOAT16 ND 2 √
    clipRatio (double) Input Controls the quantization clipping ratio. Corresponds to `clipRatio` in the corresponding formula.
    • The input data range is (0, 1].
    - - - -
    out(aclTensor*) Output Output tensor, which is out in the corresponding formula.
    • Empty tensors are not supported.
    • If the data type is INT32, the last dimension of the shape is 1/8 of the last dimension of input x, and the other dimensions are the same as those of x.
    • If the data type is INT4, the shape is the same as that of input x.
    • If the data type is FLOAT4_E2M1, the shape is [M,N1*N2].
    INT4, INT32, FLOAT4_E2M1 ND 3 or 2 √
    quantScale(aclTensor*) Output Quantization factor in the output. It is quantScale in the corresponding formula.
    • Empty tensors are not supported.
    • If the quantized output type is INT4 or INT32, the shape is [M], where M is the same as the M dimension of x, and the data type is FLOAT32.
    • If the quantized output type is FLOAT4_E2M1, the shape is [M,ceildiv(N1*N2,64),2], and the data type is FLOAT8_E8M0.
    FLOAT32, FLOAT8_E8M0 ND 1 or 3 √
    workspaceSize (uint64_t*) Output Returns the workspace size that the user needs to allocate on the Device. - - - - -
    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 A required input (x, kroneckerP1, or kroneckerP2) or required output (out or quantScale) in the parameters is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x, kroneckerP1, kroneckerP2, out, or quantScale is not supported.
    The data types of kroneckerP1 and kroneckerP2 are inconsistent with that of x.
    The dimension of x is not 3.
    The first dimension of x is out of the range [1, 262144], or the second dimension is out of [1, 256], or the third dimension is out of [1, 256].
    The dimension of kroneckerP1 is not 2, or its first and second dimensions are inconsistent with the second dimension of x.
    In the perToken scenario, the dimension of kroneckerP2 is not 2, or its first and second dimensions are inconsistent with the third dimension of x.
    In the INT4 or INT32 scenario, the dimension of quantScale is not 1, or its first dimension is inconsistent with the first dimension of x.
    In the FLOAT4_E2M1 scenario, the dimension of quantScale is not 3, or its first dimension is inconsistent with the first dimension of x.
    The value of clipRatio is out of the range (0, 1].
    If the data type of out is INT4, the size of the last dimension of the shape of x is not even, or the shape of x is inconsistent with that of out.
    If the data type of out is INT32, the size of the last dimension of the shape of x is not 8 times that of the last dimension of the shape of out, or the sizes of the non-last dimensions of the shapes of x and out are inconsistent.

aclnnFlatQuant

  • 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 aclnnFlatQuantGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnFlatQuant defaults to a deterministic implementation.

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_flat_quant.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 shape_size = 1;
    for (auto i : shape) {
        shape_size *= i;
    }
    return shape_size;
}

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

    // 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 the device/stream. 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);
    // Handle the check as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the inputs and outputs based on the API definitions.
    std::vector<int64_t> xShape = {16, 16, 16};
    std::vector<int64_t> kroneckerP1Shape = {16, 16};
    std::vector<int64_t> kroneckerP2Shape = {16, 16};
    std::vector<int64_t> outShape = {16, 16, 2};
    std::vector<int64_t> quantScaleShape = {16};
    void* xDeviceAddr = nullptr;
    void* kroneckerP1DeviceAddr = nullptr;
    void* kroneckerP2DeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    void* quantScaleDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* kroneckerP1 = nullptr;
    aclTensor* kroneckerP2 = nullptr;
    aclTensor* out = nullptr;
    aclTensor* quantScale = nullptr;
    double clipRatio = 1.0;
    std::vector<aclFloat16> xHostData(16 * 16 * 16, aclFloatToFloat16(1));
    std::vector<aclFloat16> kroneckerP1HostData(16 * 16, aclFloatToFloat16(1));
    std::vector<aclFloat16> kroneckerP2HostData(16 * 16, aclFloatToFloat16(1));
    std::vector<int32_t> outHostData(16 * 16 * 2, 1);
    std::vector<float> quantScaleHostData(16, 0);
    // Create the x aclTensor.
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the kroneckerP1 aclTensor.
    ret = CreateAclTensor(
        kroneckerP1HostData, kroneckerP1Shape, &kroneckerP1DeviceAddr, aclDataType::ACL_FLOAT16, &kroneckerP1);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the kroneckerP2 aclTensor.
    ret = CreateAclTensor(
        kroneckerP2HostData, kroneckerP2Shape, &kroneckerP2DeviceAddr, aclDataType::ACL_FLOAT16, &kroneckerP2);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the out aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_INT32, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the quantScale aclTensor.
    ret = CreateAclTensor(
        quantScaleHostData, quantScaleShape, &quantScaleDeviceAddr, aclDataType::ACL_FLOAT, &quantScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // 3. Call the CANN operator library API. Change it to the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnFlatQuant.
    ret = aclnnFlatQuantGetWorkspaceSize(
        x, kroneckerP1, kroneckerP2, clipRatio, out, quantScale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlatQuantGetWorkspaceSize 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 aclnnFlatQuant.
    ret = aclnnFlatQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlatQuant failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Synchronize and wait 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 value and copy the result from device memory to host memory. Modify it based on the definition of the specific API.
    auto size = GetShapeSize(outShape);
    std::vector<int32_t> resultData(size, 0);
    ret = aclrtMemcpy(
        resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(int32_t),
        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: %d\n", i, resultData[i]);
    }

    auto quantScaleSize = GetShapeSize(quantScaleShape);
    std::vector<float> quantScaleResultData(quantScaleSize, 0);
    ret = aclrtMemcpy(
        quantScaleResultData.data(), quantScaleResultData.size() * sizeof(quantScaleResultData[0]),
        quantScaleDeviceAddr, quantScaleSize * sizeof(float), 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 < quantScaleSize; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, quantScaleResultData[i]);
    }

    // 6. Release the aclTensor. Modify it based on the definition of the specific API.
    aclDestroyTensor(x);
    aclDestroyTensor(kroneckerP1);
    aclDestroyTensor(kroneckerP2);
    aclDestroyTensor(out);
    aclDestroyTensor(quantScale);

    // 7. Release device resources. Modify the code based on the specific API definition.
    aclrtFree(xDeviceAddr);
    aclrtFree(kroneckerP1DeviceAddr);
    aclrtFree(kroneckerP2DeviceAddr);
    aclrtFree(outDeviceAddr);
    aclrtFree(quantScaleDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}