aclnnFlatQuantV2

📄 View Source Code

Applicable Products

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

Function

  • Differences from V1:

    • The V2 version adds the dstTypeMax parameter to control the maximum value of the target data type in pergroup quantization mode (corresponding to the float4_e2m1 output type).
    • The V1 version does not support customizing the maximum value of the target data type and defaults to the maximum value representable by the target precision.
  • User selection suggestions:

    • To customize the maximum value of the target data type (value range: 6.0-12.0) for float4_e2m1 quantization, choose the V2 version.
    • If you only need to use the default maximum value of the target precision or the INT4/INT32 quantized output types, both the V1 and V2 versions can be used.
    • For use cases that require finer control over the quantization range to optimize model performance or accuracy, the V2 version is recommended.
  • Description: This fused operator performs two small matrix multiplications on the input matrix x in sequence, that is, right multiplication by the input matrix kroneckerP2 and left multiplication by the input matrix kroneckerP1, and then quantizes the matrix multiplication result. Currently, 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:

    • When dstTypeMax = 0.0:

      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
    • When dstTypeMax = 6.0/7.0:

      • The input x is grouped along the axis dimension in groups of k = blocksize elements, and each group of k numbers {{Vi}i=1k}\{\{V_i\}_{i=1}^{k}\} is dynamically quantized to {mxscale1,{Pi}i=1k}\{mxscale1, \{P_i\}_{i=1}^{k}\}, k = blocksize:

        shared_exp={ceil(log2(maxi(∣Vi∣)))−emax, iftheprecedingone/twohighbitsofthemantissa are 1, and the mantissa is not all 0floor(log2(maxi(∣Vi∣)))−emax, otherwiseshared\_exp = \begin{cases} ceil(log_2(max_i(|V_i|))) - emax, & \text{ if} the preceding one/two high bits of the mantissa \text{ are 1, and the mantissa is not all 0} \\ floor(log_2(max_i(|V_i|))) - emax, & \text{ otherwise} \end{cases} \\ Pi=cast_to_dst_type(Vi/mxscale,round_mode), i from 1 to blocksizeP_i = cast\_to\_dst\_type(V_i/mxscale, round\_mode), \space i\space from\space 1\space to\space blocksize\\
      • ​The quantized PiP_{i} are combined into the output yOut according to the positions of the corresponding ViV_{i}, and mxscale is combined into the output mxscaleOut according to the corresponding groupings along the axis dimension.

    • When dstTypeMax != 0.0/6.0/7.0:

      • Divide the long vector into blocks, each with a length of k. Compute a block scale factor Sfp32bS_{fp32}^b for each block individually, and then map all elements within the block to the target low-precision type FP8 using the same Sfp32bS_{fp32}^b. If the last block has fewer than k elements, treat the missing values as 0 and process it as a complete block.

      • Find the maximum absolute value of the elements in the block:

        Amax(Dfp32b)=max({∣di∣}i=1k)Amax(D_{fp32}^b)=max(\{|d_{i}|\}_{i=1}^{k})
      • Map FP32 to the range representable by the target data type FP8. When dst_max_value=0, Amax(DType)Amax(DType) is the maximum value representable by the target precision; when dst_max_value!=0, Amax(DType)Amax(DType) is the value passed in for dst_max_value.

        Sfp32b=Amax(Dfp32b)Amax(DType)S_{fp32}^b = \frac{Amax(D_{fp32}^b)}{Amax(DType)}
      • Convert the block quantization scale factor Sfp32bS_{fp32}^b to a scale value Sue8m0bS_{ue8m0}^b representable in the FP8 format.

      • Extract the unbiased exponent EintbE_{int}^b and the mantissa MfixpbM_{fixp}^b from the floating-point quantization scale factor Sfp32bS_{fp32}^b of the block.

      • To ensure no overflow during quantization, round up the exponent and keep it within the representable range of FP8:

        Eintb={Eintb+1, ifSfp32b is a normal number, andEintb<254 andMfixpb>0Eintb, otherwiseE_{int}^b = \begin{cases} E_{int}^b + 1, & \text{ if} S_{fp32}^b \text{ is a normal number, and} E_{int}^b < 254 \text{ and} M_{fixp}^b > 0 \\ E_{int}^b, & \text{ otherwise} \end{cases}
      • Calculate the block scale factor: Sue8m0b=2EintbS_{ue8m0}^b=2^{E_{int}^b}

      • Calculate the block conversion factor: Rfp32b=1fp32(Sue8m0b)R_{fp32}^b=\frac{1}{fp32(S_{ue8m0}^b)}

      • Apply to the final quantization step. For each element within a block, di=DType(dfp32i⋅Rfp32n)d^i = DType(d_{fp32}^i \cdot R_{fp32}^n). The final quantized output is (Sb,[di]i=1k)\left(S^b, [d^i]_{i=1}^k\right), where SbS^b represents the block scale factor, i.e., Sue8m0bS_{ue8m0}^b, and [di]i=1k[d^i]_{i=1}^k represents the quantized data within the block.

      • ​The quantized PiP_{i} are combined into the output yOut according to the positions of the corresponding ViV_{i}, and mxscale is combined into the output mxscaleOut according to the corresponding groupings along the axis dimension.

Function Prototype

Each operator uses a two-phase API. First, call aclnnFlatQuantV2GetWorkspaceSize to obtain the workspace size required for the calculation and the executor that includes the calculation flow of the operator. Then, call aclnnFlatQuantV2 to execute the calculation.

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

aclnnFlatQuantV2GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Raw input data, corresponding to `x` in the corresponding formula.
    • The operator does not support null tensors.
    • The shape is [M, N1, N2], where M is no greater than 262144, and N1 and N2 are no 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 Calculation matrix 1 of the input, corresponding to `kroneckerP1` in the corresponding formula.
    • Does not support null tensors.
    • The shape is [N1, N1], where N1 is consistent with the N1 dimension in x.
    • The data type is consistent with the data type of input parameter x.
    FLOAT16, BFLOAT16 ND 2 √
    kroneckerP2 (aclTensor*) Input Calculation matrix 2 of the input, corresponding to `kroneckerP2` in the formula.
    • Does not support null tensors.
    • The shape is [N2, N2], where N2 is consistent with the N2 dimension in x. The shape [0,0] is supported only in the perGroup scenario, indicating that the operator does not use the right matrix for calculation and only performs multiplication of the left matrix.
    • The data type is consistent with the data type of input parameter x.
    FLOAT16, BFLOAT16 ND 2 √
    clipRatio (double) Input Controls the clipping ratio in quantization, corresponding to `clipRatio` in the formula.
    • The input data range is (0, 1].
    - - - -
    dstTypeMax (double) Input Indicates the value of maxType, corresponding to Amax(DType) in the formula.
    • Supported values are 0.0 and 6.0-12.0. A value of 0.0 indicates that this parameter is not used; a value of 6.0-12.0 indicates the maximum value of the target data type. This value can be set only when the data type is FLOAT4_E2M1.
    DOUBLE ND - -
    out (aclTensor*) Output Output tensor, corresponding to out in the formula.
    • Does not support null Tensor.
    • If the data type is INT32, the last dimension of shape is 1/8 of the last dimension of the input parameter x, and the other dimensions are consistent with x.
    • If the data type is INT4, shape is consistent with the input parameter x.
    • If the data type is FLOAT4_E2M1, shape is [M,N1*N2].
    INT4, INT32, FLOAT4_E2M1 ND 3 or 2 √
    quantScale (aclTensor*) Output Quantization scale of the output, corresponding to quantScale in the formula.
    • Does not support null tensors.
    • When the quantized output type is INT4 or INT32, the shape is [M], where M is consistent with the M dimension in x, and the data type is FLOAT32.
    • When 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 needs to be requested by the user on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which includes the calculation process of the operator. - - - - -
  • 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 The required inputs (x, kroneckerP1, kroneckerP2) and required outputs (out, quantScale) in the input parameters are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x, kroneckerP1, kroneckerP2, out, or quantScale is not within the supported range.
    The data type of kroneckerP1 or kroneckerP2 is 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 the first or second dimension is inconsistent with the second dimension of x.
    In the perToken scenario, the dimension of kroneckerP2 is not 2, or the first or second dimension is inconsistent with the third dimension of x.
    In the INT4 or INT32 scenario, the dimension of quantScale is not 1, or the first dimension is inconsistent with the first dimension of x.
    In the FLOAT4_E2M1 scenario, the dimension of quantScale is not 3, or the 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 trailing axis of x is not an even number, or the shape of x is inconsistent with that of out.
    If the data type of out is INT32, the last dimension of the shape of x is not 8 times the size 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.

aclnnFlatQuantV2

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested by the Device.
    workspaceSize Input Workspace size requested by the Device, obtained by the first-phase API aclnnFlatQuantV2GetWorkspaceSize.
    executor Input Op executor, includes the calculation process of the operator.
    stream Input Specifies the stream for task execution.
  • Return Value

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

Constraints

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

Example

The following sample code is 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_flat_quant_v2.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 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 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);

    // 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) Device/stream initialization. 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);
    // Handle the check as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the input and output. Customize the construction based on the API.
    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;
    double dstTypeMax = 0.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 aclTensor x.
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the aclTensor kroneckerP1.
    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. Replace it with the actual API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnFlatQuantV2.
    ret = aclnnFlatQuantV2GetWorkspaceSize(
        x, kroneckerP1, kroneckerP2, clipRatio, dstTypeMax, out, quantScale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlatQuantV2GetWorkspaceSize 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 aclnnFlatQuantV2.
    ret = aclnnFlatQuantV2(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlatQuantV2 failed. ERROR: %d\n", ret); return ret);
    // 4. (boilerplate) Synchronously wait for the task execution to finish.
    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 according to the actual API definition.
    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 according to the actual API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(kroneckerP1);
    aclDestroyTensor(kroneckerP2);
    aclDestroyTensor(out);
    aclDestroyTensor(quantScale);

    // 7. Release device resources. Modify it according to 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;
}