aclnnSituMxQuant

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: Fuses the Situ activation function and dynamic MX (Microscaling) quantization into a single operator. It applies Situ activation to the input data x, applies MX quantization to the activated result, and outputs the quantized result and scale.

  • Formula:

  1. Situ Activation
situA=β×tanh⁡(gate/β)×sigmoid(gate)situA = \beta \times \tanh(gate / \beta) \times sigmoid(gate)

When linear_beta > 0:

up=linear_beta×tanh⁡(up/linear_beta)up = linear\_beta \times \tanh(up / linear\_beta) situOut=situA×upsituOut = situA \times up
When activate_left is true, gate takes the first half of x and up takes the second half; when activate_left is false, gate takes the second half of x and up takes the first half.
  1. MX quantization (OCP algorithm)
shared_exp=floor(log2(max(∣situOuti∣)))−emaxshared\_exp = floor(log2(max(|situOut_i|))) - emax y_scale=2shared_exp(E8M0)y\_scale = 2^{shared\_exp} (E8M0) y=cast_to_fp8(situOut/y_scale)y = cast\_to\_fp8(situOut / y\_scale)

Function Prototype

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

aclnnStatus aclnnSituMxQuantGetWorkspaceSize(
    const aclTensor*  x,
    double            beta,
    double            linearBeta,
    bool              activateLeft,
    int64_t           axis,
    int64_t           dstType,
    char*             roundModeOptional,
    const aclTensor*  yOut,
    const aclTensor*  yScaleOut,
    uint64_t*         workspaceSize,
    aclOpExecutor**   executor)
aclnnStatus aclnnSituMxQuant(
    void*            workspace,
    uint64_t         workspaceSize,
    aclOpExecutor*   executor,
    aclrtStream      stream)

aclnnSituMxQuantGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input The input x in the formula.
    • Empty tensors are not supported.
    • Supports 1-8 dimensions.
    • The last dimension must be a multiple of 2.
    FLOAT16, BFLOAT16 ND 1-8 √
    beta (double) Input The beta parameter for Situ activation. Must be greater than 0. Default: 1.0. - - - -
    linearBeta (double) Input linearBeta parameter of Situ activation. Not enabled when the value is ≤ 0. Default: 0.0. - - - -
    activateLeft (bool) Input Whether to apply Situ activation to the left half of the input. If the value is false, activation is applied to the right half of the input. Defaults to false. - - - -
    axis (int64_t) Input Quantization axis. Currently, only -1 is supported. Defaults to -1. - - - -
    dstType (int64_t) Input Output data type of y. The value ranges from {35, 36}, corresponding to {35: FLOAT8_E5M2, 36: FLOAT8_E4M3FN} respectively. Defaults to 36. - - - -
    roundModeOptional (char*) Input Quantization rounding mode. Supports {"rint", "round", "floor"}. FP8 output supports only "rint". Defaults to "rint". - - - -
    yOut(aclTensor*) Output Quantized output, which is y in the formula.
    • Empty tensors are not supported.
    • The shape is x.shape[:-1]+[H], where H=x.shape[-1]/2.
    FLOAT8_E4M3FN, FLOAT8_E5M2 ND 1-8 √
    yScaleOut (aclTensor*) Output MX quantization scale (E8M0 format).
    • Empty tensors are not supported.
    • The shape is x.shape[:-1]+[ceil(H/64), 2], where H=x.shape[-1]/2.
    FLOAT8_E8M0 ND 2-9 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing 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 The input x, yOut, or yScaleOut is a null pointer.
ACLNN_ERR_PARAM_INVALID 161002 x, yOut, or yScaleOut is an empty tensor.
The data type of x is out of the supported range.
axis is not -1.
dstType is out of the supported range.
roundModeOptional is not within the supported range.
The last dimension of x is not a multiple of 2.
beta is not greater than 0.
The data type of yOut does not match dstType, or the data type of yScaleOut is not FLOAT8_E8M0.
The shape of yOut or yScaleOut is inconsistent with the inferred result.
The data format of x, yOut, or yScaleOut is not ND.
ACLNN_ERR_RUNTIME_ERROR 361001 The current platform is not within the supported platform range.

aclnnSituMxQuant

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Size of the workspace allocated on the Device, obtained by calling the first-phase API aclnnSituMxQuantGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation:

    • aclnnSituMxQuant defaults to a deterministic implementation.
  • The last dimension of x must be a multiple of 2.

  • The number of dimensions of x must be greater than or equal to 1.

  • axis currently supports only -1 (quantization along the last axis).

  • dstType supports 36 (FLOAT8_E4M3FN) or 35 (FLOAT8_E5M2).

  • roundModeOptional must be "rint".

  • The data type of yOut must match dstType, and the data type of yScaleOut must be FLOAT8_E8M0.

  • The shapes of yOut and yScaleOut must be consistent with the deduction results (see Parameters).

  • The shape constraints of yScaleOut are as follows:

    • H = x.shape[-1] / 2
    • scaleNum = ceil(H / 64)
    • yScaleOut.shape = x.shape[:-1] + [scaleNum, 2]

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 <cstring>

#include "acl/acl.h"
#include "aclnnop/aclnn_situ_mx_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 shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

int Init(int32_t deviceId, aclrtStream* stream)
{
    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);
    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);
    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);
    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];
    }
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0,
                              aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(), *deviceAddr);
    return 0;
}

uint16_t FloatToBf16Bits(float val)
{
    uint32_t bits;
    std::memcpy(&bits, &val, sizeof(bits));
    uint32_t lsb = (bits >> 16) & 1;
    bits += 0x7FFF + lsb;
    return static_cast<uint16_t>(bits >> 16);
}

int main()
{
    // 1. (boilerplate) Initialize device/stream. 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);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the inputs and outputs as required by the API.
    std::vector<int64_t> xShape = {4, 128};
    std::vector<int64_t> yShape = {4, 64};
    std::vector<int64_t> yScaleShape = {4, 1, 2};

    // Generate BF16 input data.
    std::vector<uint16_t> xHostData(GetShapeSize(xShape));
    for (int64_t i = 0; i < GetShapeSize(xShape); i++) {
        float val = ((i * 17 + 3) % 200 - 100) / 50.0f;
        xHostData[i] = FloatToBf16Bits(val);
    }
    std::vector<uint8_t> yHostData(GetShapeSize(yShape), 0);
    std::vector<uint8_t> yScaleHostData(GetShapeSize(yScaleShape), 0);

    void* xDeviceAddr = nullptr;
    void* yDeviceAddr = nullptr;
    void* yScaleDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* y = nullptr;
    aclTensor* yScale = nullptr;

    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &y);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(yScaleHostData, yScaleShape, &yScaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &yScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    double beta = 1.0;
    double linearBeta = 0.0;
    bool activateLeft = false;
    int64_t axis = -1;
    int64_t dstType = 36;

    // 3. Call the CANN operator library API. Replace the name with the actual API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnSituMxQuant.
    ret = aclnnSituMxQuantGetWorkspaceSize(x, beta, linearBeta, activateLeft, axis, dstType,
                                           const_cast<char*>("rint"),
                                           y, yScale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSituMxQuantGetWorkspaceSize 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 aclnnSituMxQuant.
    ret = aclnnSituMxQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSituMxQuant failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Synchronously 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, copy the result on the device memory to the host memory, and modify it according to the definition of the specific API.
    auto yResultSize = GetShapeSize(yShape);
    std::vector<uint8_t> yResult(yResultSize, 0);
    ret = aclrtMemcpy(yResult.data(), yResult.size(), yDeviceAddr,
                      yResultSize, ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy yResult from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < yResultSize; i++) {
        LOG_PRINT("y[%ld] is: %d\n", i, yResult[i]);
    }

    // 6. Release aclTensor and aclScalar, and modify it according to the definition of the specific API.
    aclDestroyTensor(x);
    aclDestroyTensor(y);
    aclDestroyTensor(yScale);

    // 7. Release device resources, and modify it according to the definition of the specific API.
    aclrtFree(xDeviceAddr);
    aclrtFree(yDeviceAddr);
    aclrtFree(yScaleDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}