aclnnGroupedQuantMax

📄 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

  • Description: Quantizes input x into groups based on the input scale and computes amax, the maximum absolute value of input x for each group.

  • Formula:

    group_listgroup\_list splits xx along dim-0 into num_groups groups, and group_list[g]group\_list[g] is the cumulative size of the first g+1g+1 groups along dim-0 (monotonically increasing, group_list[−1]=x.shape[0]group\_list[-1]=x.shape[0]). For each group (g = 0, 1, ..., num_groups - 1):

    x_g=x[group_list[g−1]:group_list[g],...]x\_g = x[group\_list[g-1] : group\_list[g], ...] y=Cast(x_g×scale[g],dst_type,round_mode)y = \text{Cast}(x\_g \times scale[g], \text{dst\_type}, \text{round\_mode}) amax[g]=max⁡(∣x_g∣)amax[g] = \max(|x\_g|)

    where xx indicates the input tensor, x_gx\_g indicates the g-th group of data in the input tensor, and the lower bound is 0 when g=0; scalescale indicates the quantization scale factor, amax[g]amax[g] is the maximum absolute value of the corresponding group of the input tensor, dst_type\text{dst\_type} specifies the output type, and round_mode\text{round\_mode} specifies the rounding mode.

Function Prototype

Each operator uses a two-phase API. First call the "aclnnGroupedQuantMaxGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation flow, and then call the "aclnnGroupedQuantMax" API to perform the computation.

aclnnStatus aclnnGroupedQuantMaxGetWorkspaceSize(
  const aclTensor  *x,
  const aclTensor  *scale,
  const aclTensor  *groupList,
  const char       *roundMode,
  int64_t           dstType,
  aclTensor        *y,
  aclTensor        *amax,
  uint64_t         *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnGroupedQuantMax(
  void           *workspace,
  uint64_t        workspaceSize,
  aclOpExecutor  *executor,
  aclrtStream     stream)

aclnnGroupedQuantMaxGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Input tensor to be quantized, corresponding to x in the formula.
    • Empty tensors are supported.
    FLOAT, FLOAT16, BFLOAT16 ND 2-8 √
    scale (aclTensor*) Input Quantization scale factor, corresponding to scale in the formula.
    • Empty tensors are not supported.
    • The shape is fixed to [num_groups].
    FLOAT ND 1 √
    groupList (aclTensor*) Input Indicates the offset of each group of the input x on axis 0 (cumsum mode), corresponding to group_list in the formula.
    • Empty tensors are not supported.
    • Indicates the start index of quantization groups. Each value must be greater than 0 and monotonically increasing, and the last value must be equal to the size of x on axis 0.
    • The shape is [num_groups], with num_groups ranging from 1-384.
    INT64 ND 1 √
    roundMode (char*) Input Specifies the round mode.
    • When dstType is 34, roundMode supports "round" and "hybrid".
    • When dstType is 35 or 36, roundMode supports "rint".
    STRING - - -
    dstType (int64_t) Input Specifies the quantization data type of the output. 34=HIFLOAT8, 35=FLOAT8_E5M2, 36=FLOAT8_E4M3.
    • Value range {34, 35, 36}
    INT64 - - -
    y (aclTensor*) Output Quantized output tensor, corresponding to y in the formula.
    • The data type is determined by dstType.
    • The shape is the same as x.
    HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3 ND 2-8 √
    amax (aclTensor*) Output Maximum absolute value of x, corresponding to amax in the formula.
    • The data type must be the same as that of x.
    • The shape is fixed to [num_groups].
    FLOAT, FLOAT16, BFLOAT16 ND 1 √
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be allocated on the device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing the operator computation process. - - - - -
  • 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 x, scale, groupList, y, or amax is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of x, scale, and groupList are not supported.
    The value of dstType is not in {34, 35, 36}.
    The value of roundMode is invalid.
    The shape dimension of x is not within 2-8, or the shapes of scale and amax are not [num_groups].

aclnnGroupedQuantMax

  • Parameters

    ParameterInput/OutputDescription
    workspaceInputWorkspace memory address allocated on the device.
    workspaceSizeInputSize of the workspace allocated on the device, obtained by calling the first-phase API aclnnGroupedQuantMaxGetWorkspaceSize.
    executorInputOp executor that contains the operator computation flow.
    streamInputStream for task execution.
  • Return Value

    aclnnStatus: Return value. For details, see aclnnReturnCode.

Constraints

  • Deterministic computation:
    • aclnnGroupedQuantMax 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 <memory>
#include <vector>
#include <cmath>
#include "acl/acl.h"
#include "aclnnop/aclnn_grouped_quant_max.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 for 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-side 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-side data to 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];
    }

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

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

    LOG_PRINT("Init acl success.\n");

    std::vector<int64_t> xShape = {4, 4};
    std::vector<int64_t> scaleShape = {1};
    std::vector<int64_t> groupListShape = {1};
    std::vector<int64_t> amaxShape = {1};

    // The x values can cover multiple cases.
    std::vector<float> xHostData = {1.0f, -2.0f, 3.0f, -4.0f,  5.0f,    -6.0f,  7.0f,    -8.0f,
                                    0.5f, -0.5f, 0.0f, 448.0f, -448.0f, 0.125f, -0.125f, 2.5f};

    // scale = 1.0
    std::vector<float> scaleHostData = {1.0f};

    // The output y is initialized to 0.
    std::vector<uint8_t> yHostData(GetShapeSize(xShape), 0);

    // amax is initialized to 0.
    std::vector<int64_t> groupListHostData = {4};
    std::vector<float> amaxHostData = {0.0f};

    void* xDeviceAddr = nullptr;
    void* scaleDeviceAddr = nullptr;
    void* groupListDeviceAddr = nullptr;
    void* yDeviceAddr = nullptr;
    void* amaxDeviceAddr = nullptr;
    aclTensor* xTensor = nullptr;
    aclTensor* scaleTensor = nullptr;
    aclTensor* groupListTensor = nullptr;
    aclTensor* yTensor = nullptr;
    aclTensor* amaxTensor = nullptr;

    // Create input x tensor
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &xTensor);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> xTensorPtr(xTensor, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> xDeviceAddrPtr(xDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create scale tensor (float, shape [1])
    ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scaleTensor);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> scaleTensorPtr(scaleTensor, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> scaleDeviceAddrPtr(scaleDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create groupList tensor (int64, shape [1])
    ret = CreateAclTensor(groupListHostData, groupListShape, &groupListDeviceAddr, aclDataType::ACL_INT64, &groupListTensor);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> groupListTensorPtr(groupListTensor, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> groupListDeviceAddrPtr(groupListDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create output y tensor (FLOAT8_E4M3FN, same shape as x)
    ret = CreateAclTensor(yHostData, xShape, &yDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &yTensor);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yTensorPtr(yTensor, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> yDeviceAddrPtr(yDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create output amax tensor (float, shape [1])
    ret = CreateAclTensor(amaxHostData, amaxShape, &amaxDeviceAddr, aclDataType::ACL_FLOAT, &amaxTensor);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> amaxTensorPtr(amaxTensor, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> amaxDeviceAddrPtr(amaxDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call grouped_quant_max API
    int64_t dstType = 36; // FLOAT8_E4M3FN
    char* roundMode = const_cast<char*>("rint");
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor = nullptr;

    // First stage: get workspace size
    ret = aclnnGroupedQuantMaxGetWorkspaceSize(
        xTensor, scaleTensor, groupListTensor, roundMode, dstType, yTensor, amaxTensor, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedQuantMaxGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    LOG_PRINT("aclnnGroupedQuantMaxGetWorkspaceSize success, workspaceSize: %lu\n", workspaceSize);

    // Allocate workspace
    void* workspaceAddr = nullptr;
    std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtr(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);
        workspaceAddrPtr.reset(workspaceAddr);
    }

    // Second stage: execute
    ret = aclnnGroupedQuantMax(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedQuantMax failed. ERROR: %d\n", ret); return ret);

    // 4. Synchronize stream
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
    LOG_PRINT("aclnnGroupedQuantMax execution success.\n");

    // 5. Get results
    // Copy y (FLOAT8_E4M3FN) back to host
    auto ySize = GetShapeSize(xShape);
    std::vector<uint8_t> yOutData(ySize, 0);
    ret = aclrtMemcpy(
        yOutData.data(), ySize * sizeof(uint8_t), yDeviceAddr, ySize * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y from device to host failed. ERROR: %d\n", ret); return ret);

    // Copy amax back to host
    std::vector<float> amaxOutData(1, 0);
    ret = aclrtMemcpy(amaxOutData.data(), sizeof(float), amaxDeviceAddr, sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy amax from device to host failed. ERROR: %d\n", ret); return ret);

    // Print results
    auto size = GetShapeSize(xShape);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("yOut[%ld] is: %d\n", i, yOutData[i]);
    }
    LOG_PRINT("amaxOut is: %f\n", amaxOutData[0]);

    return ACL_SUCCESS;
}

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

    Finalize(deviceId, stream);
    LOG_PRINT("All test cases passed!\n");
    return 0;
}