aclnnMxToBlockMxQuant

📄 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: Converts the FLOAT4 tensor quantized by calling aclnnDynamicMxQuantV2 together with the FLOAT8_E8M0 scaling factors to the FLOAT8 block quantization format, and outputs the quantization scales along the -1 and -2 axes.

  • Formula:

    scalefp8=max(mxscalefp4_block)/MAX_OFFSEToffset=mxscalefp4_block/scalefp8xfp8=xfp4×offset\begin{aligned} scale_{fp8} &= max(mxscale_{fp4\_block}) / MAX\_OFFSET \\ offset &= mxscale_{fp4\_block} / scale_{fp8} \\ x_{fp8} &= x_{fp4} \times offset \end{aligned}
    • where mxscalefp4_blockmxscale_{fp4\_block} is the FP8_E8M0 scale factor provided by the input mxscale; MAX_OFFSETMAX\_OFFSET is the maximum offset between the input and output data types; xfp4x_{fp4} is the quantized FLOAT4 tensor; xfp8x_{fp8} is the converted FLOAT8 tensor.

    • MAX_OFFSET reference table:

      InputOutputMAX_OFFSET
      FP4_E2M1FP8_E5M213
      FP4_E1M2FP8_E5M215
      FP4_E2M1FP8_E4M3FN6
      FP4_E1M2FP8_E4M3FN8

Function Prototype

Each operator uses a two-phase API. Call aclnnMxToBlockMxQuantGetWorkspaceSize first to obtain the workspace size required for the computation and the executor containing the operator computation flow, and then call aclnnMxToBlockMxQuant to execute the computation.

aclnnStatus aclnnMxToBlockMxQuantGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *mxscale,
  int64_t          dstType,
  const aclTensor *y,
  const aclTensor *scale1,
  const aclTensor *scale2,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnMxToBlockMxQuant(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnMxToBlockMxQuantGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Represents the quantized input tensor of the operator. Corresponds to x_fp4 in the formula.
    • Does not support null Tensor.
    FLOAT4_E2M1, FLOAT4_E1M2 ND 2-3 ×
    mxscale (aclTensor*) Input Quantization scale obtained by calling DynamicMxQuant. Corresponds to mxscale_fp4_block in the formula.
    • Does not support null tensors.
    • The shape must meet the constraints described in the formula.
    FLOAT8_E8M0 ND 3-4 ×
    dstType (int64_t) Input Specifies the data type of output y. The input range is {35, 36}, corresponding to the data types of output y: {35: FLOAT8_E5M2, 36: FLOAT8_E4M3FN}. INT64 - - -
    y (aclTensor*) Output Quantization output tensor. Corresponds to x_fp8 in the corresponding formula.
    • Does not support null tensors.
    • The shape dimensions must remain consistent with x.
    • The data type must correspond to dstType.
    FLOAT8_E5M2, FLOAT8_E4M3FN ND 2-3 ×
    scale1 (aclTensor*) Output Represents the quantization scale corresponding to each group along the -1 axis.
    • Null tensors are not supported.
    • The shape must meet the formula in Constraints.
    FLOAT8_E8M0 ND 3-4 ×
    scale2 (aclTensor*) Output Quantization scale corresponding to each group on axis -2. The output requires interleaving of every two rows of data.
    • Does not support null tensors.
    • shape must meet the formula described in Constraints.
    FLOAT8_E8M0 ND 3-4 ×
    workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - -
    executor Output Returns the op executor, which contains the operator computation process. - - - - -
  • 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 parameter is a required input or output and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of x, mxscale, y, scale1, and scale2 are not in the supported range.
    The shapes of x, mxscale, y, scale1, and scale2 do not meet the validation conditions.
    The dimensions of x, mxscale, y, scale1, and scale2 are not in the supported range.
    dstType is not among the currently supported values.
    The data type of y does not match the correspondence with dstType.
    ACLNN_ERR_RUNTIME_ERROR 361001 The current platform is not among the supported platforms.

aclnnMxToBlockMxQuant

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested by the Device side.
    workspaceSize Input Workspace size requested by the Device side, obtained by the first-phase API aclnnMxToBlockMxQuantGetWorkspaceSize.
    executor Input Op executor that includes the operator computation process.
    stream Input Stream where tasks are executed.
  • Return value

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

Constraints

  • Deterministic computation:
    • aclnnMxToBlockMxQuant defaults to a deterministic implementation.
  • x supports only 2D or 3D input. The -2 axis must be a multiple of 64, and the -1 axis must be a multiple of 2. Non-contiguous tensors and empty tensors are not supported.
  • The shape constraints of x, mxscale, scale1, and scale2 are described as follows:
    • rank(mxscale) = rank(x) + 1.
    • mxscale.shape[-2] = (Ceil(x.shape[-1] / 32) + 2 - 1) / 2.
    • mxscale.shape[-1] = 2.
    • Other dimensions are consistent with input x.
  • The shape constraints of output scale1 are described as follows:
    • rank(scale1) = rank(x) + 1.
    • scale1.shape[-2] = (Ceil(x.shape[-1] / 32) + 2 - 1) / 2.
    • scale1.shape[-1] = 2.
    • Other dimensions are consistent with input x.
  • The shape constraints of output scale2 are as follows:
    • rank(scale2) = rank(x) + 1.
    • scale2.shape[-3] = ((Ceil(x.shape[-2] / 32) + 2 - 1) / 2) * 2 / 2.
    • scale2.shape[-2] = x.shape[-1].
    • scale2.shape[-1] = 2.
    • Other dimensions are consistent with input x.
  • dstType supports only {35, 36}, corresponding to {FLOAT8_E5M2, FLOAT8_E4M3FN}.

Example

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

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

#include "acl/acl.h"
#include "aclnnop/aclnn_mx_to_block_mx_quant.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 code 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 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 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;
}

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

int aclnnMxToBlockMxQuantTest(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. The construction needs to be customized based on the API.
    std::vector<int64_t> xShape = {64, 2};
    std::vector<int64_t> scaleShape = {64, 1, 2};
    std::vector<int64_t> yOutShape = {64, 2};
    std::vector<int64_t> scale1Shape = {64, 1, 2};
    std::vector<int64_t> scale2Shape = {1, 2, 2};

    void* xDeviceAddr = nullptr;
    void* scaleDeviceAddr = nullptr;
    void* yOutDeviceAddr = nullptr;
    void* scale1DeviceAddr = nullptr;
    void* scale2DeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* mxscale = nullptr;
    aclTensor* yOut = nullptr;
    aclTensor* scale1Out = nullptr;
    aclTensor* scale2Out = nullptr;

    std::vector<uint8_t> xHostData(128, 0x12);
    std::vector<uint8_t> scaleHostData(128, 128);
    std::vector<uint8_t> yOutHostData(128, 0);
    std::vector<uint8_t> scale1HostData(128, 0);
    std::vector<uint8_t> scale2HostData(4, 0);
    int64_t dstType = 36;

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

    // Create the scale aclTensor.
    ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &mxscale);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> scaleTensorPtr(mxscale, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> scaleDeviceAddrPtr(scaleDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the yOut aclTensor.
    ret = CreateAclTensor(yOutHostData, yOutShape, &yOutDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &yOut);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yOutTensorPtr(yOut, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> yOutDeviceAddrPtr(yOutDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the scale1Out aclTensor.
    ret = CreateAclTensor(scale1HostData, scale1Shape, &scale1DeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &scale1Out);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> scale1TensorPtr(scale1Out, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> scale1DeviceAddrPtr(scale1DeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the scale2Out aclTensor.
    ret = CreateAclTensor(scale2HostData, scale2Shape, &scale2DeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &scale2Out);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> scale2TensorPtr(scale2Out, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> scale2DeviceAddrPtr(scale2DeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Call the CANN operator library API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;

    // Call the first-phase API of aclnnMxToBlockMxQuant.
    ret = aclnnMxToBlockMxQuantGetWorkspaceSize(x, mxscale, dstType, yOut, scale1Out, scale2Out,
                                                &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS,
              LOG_PRINT("aclnnMxToBlockMxQuantGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);

    // Allocate device memory based on the workspaceSize computed by the first-phase API.
    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);
    }

    // Call the second-phase API of aclnnMxToBlockMxQuant.
    ret = aclnnMxToBlockMxQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMxToBlockMxQuant failed. ERROR: %d\n", ret); return ret);

    // Wait for the task execution to complete synchronously.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    // Obtain the value of output y, and copy the result from device-side memory to the host side.
    auto ySize = GetShapeSize(yOutShape);
    std::vector<uint8_t> yOutData(ySize, 0);
    ret = aclrtMemcpy(yOutData.data(), yOutData.size() * sizeof(yOutData[0]), yOutDeviceAddr,
                      ySize * sizeof(yOutData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy yOut from device to host failed. ERROR: %d\n", ret);
              return ret);
    for (int64_t i = 0; i < ySize; i++) {
        LOG_PRINT("y[%ld] is: %u\n", i, yOutData[i]);
    }

    return ACL_SUCCESS;
}

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 = aclnnMxToBlockMxQuantTest(deviceId, stream);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMxToBlockMxQuantTest failed. ERROR: %d\n", ret); return ret);

    Finalize(deviceId, stream);
    return 0;
}