aclnnGroupedDynamicMxQuantV2
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: Based on the start value of the passed-in group index (
groupIndex), performs dynamic MX quantization with the target data typefloat4/float8on each group at the granularity of basic blocks.Formula:
- Use case 1: when
scaleAlgis 0:- The input
xis first grouped along dimension 0 according togroupIndex, and within each group, numbers are grouped by k = blocksize numbers. For a group of k numbers {{xi}i=1k}, the quantization scalemxscale_pre, {mxscale_pre, {Pi}i=1k}, corresponding to this group of numbers is calculated. The formula is shown in Formula (1) and (2) below.
- Each number in this group is divided by
mxscale_pre, and converted to the correspondingdst_typeaccording toround_mode, to obtain the quantized resulty. The calculation formula is formula (3) below.
The quantized are combined as output
yaccording to the positions of the corresponding .mxscale_preis grouped by the correspondinggroupIndex, the first dimension within each group is padded to an even number, and the result is combined as outputmxscale.emax: Exponent bits of the maximum normal number for the corresponding data type.
- The input
- Use case 1: when
| DataType | Emax | | :-----------: | :--: | | FLOAT4_E2M1 | 2 | | FLOAT4_E1M2 | 0 | | FLOAT8_E4M3FN | 8 | | FLOAT8_E5M2 | 15 |
Use case 2, when
scaleAlgis 1, only FP8 types are involved:Divide the long vector into blocks, each with a length of k. Compute a block scale factor for each block individually, and then map all elements within the block to the target low-precision type FP8 using the same . 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:
Map FP32 to the range representable by the target data type FP8, where is the maximum value representable by the target precision.
Convert the block scale factor to the representable scale value in FP8 format.
Extract the unbiased exponent and mantissa from the block floating-point scale factor .
To ensure no overflow during quantization, round up the exponent and keep it within the representable range of FP8:
Calculate the block scale factor:
Calculate the block conversion factor:
Apply to the final quantization step. For each element within a block, . The final quantized output is , where represents the block scale factor, i.e., , and represents the quantized data within the block.
Scenario 3, when
scaleAlgis 2, only the FP4 type is involved:- When
dstTypeMax = 0.0/6.0/7.0(FP4_E2M1)ordstTypeMax = 1.875(FP4_E1M2):- Group the input
xalong dimension 0 into groups of k = blocksize elements, and each group of k elements is dynamically quantized to , k = blocksize: - The quantized at the positions of the corresponding form the output
y, and the grouping along the corresponding dimensions forms the outputmxscale.
- Group the input
- When
dstTypeMax != 0.0/6.0/7.0(FP4_E2M1)ordstTypeMax != 1.875(FP4_E1M2):- The long vector is divided into blocks, each with a length of k. A block scale factor is computed separately for each block, and then all elements in the block are mapped to the target low-precision type using the same . If the last block has fewer than k elements, the missing values are treated as 0, and the block is processed as a complete one.
- Find the maximum absolute value in the block:
- Map FP32 to the range representable by the target data type, where is the maximum value representable by the target precision when
dst_type_maxis 0; is the value passed in throughdst_type_maxwhendst_type_maxis not 0. - Convert the block quantization scale factor to a scale value representable in the FP8 format.
- Extract the unbiased exponent and the mantissa from the floating-point quantization scale factor of the block.
- To ensure no overflow during quantization, round up the exponent and keep it within the representable range of FP8:
- Calculate the block scale factor:
- Calculate the block conversion factor:
- Apply to the final quantization step. For each element within a block, . The final quantized output is , where represents the block scale factor, i.e., , and represents the quantized data within the block.
- The quantized at the positions of the corresponding form the output
y, and the grouping along the corresponding dimensions forms the outputmxscale.
- When
Function Prototype
Each operator uses a two-phase API. You must call the "aclnnGroupedDynamicMxQuantV2GetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the computation process of the operator, and then call the "aclnnGroupedDynamicMxQuantV2" API to perform the computation.
aclnnStatus aclnnGroupedDynamicMxQuantV2GetWorkspaceSize(
const aclTensor *x,
const aclTensor *groupIndex,
const char *roundMode,
int64_t dstType,
int64_t blocksize,
int64_t scaleAlg,
double dstTypeMax,
const aclTensor *y,
const aclTensor *mxscale,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnGroupedDynamicMxQuantV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnGroupedDynamicMxQuantV2GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input Indicates the input tensor of the operator. The input x in the formula. Empty tensors are supported. FLOAT16, BFLOAT16 ND 2 √ groupIndex (aclTensor*) Input Start index of quantization grouping. - Empty tensors are not supported.
- Index values must be greater than or equal to 0 and non-decreasing, and the last value must be equal to the size of the first dimension of x.
INT32, INT64 ND 1 √ roundMode (char*) Input round_mode in the formula, which specifies the data conversion mode. - "rint"/"round"/"floor" modes are supported.
- For FLOAT8, only "rint" is supported; for FLOAT4, "rint"/"round"/"floor" are all supported.
STRING - - - dstType (int64_t) Input dst_type in the formula. Specifies the data type of y after conversion. Valid range: {35, 36, 40, 41}, corresponding to output y data types {35: FLOAT8_E5M2, 36: FLOAT8_E4M3FN, 40: FLOAT4_E2M1, 41: FLOAT4_E1M2} INT64 - - - blocksize (int64_t) Input blocksize in the formula, specifying the number of elements quantized each time. Currently, only 32 is supported. INT64 - - - scaleAlg (int64_t) Input Specifies the algorithm used for mxscale computation. - Currently, the supported values are 0, 1, and 2. Value 0 corresponds to use case 1, value 1 to use case 2, and value 2 to use case 3.
- When dstType is FLOAT4, the supported values are 0 and 2; when dstType is FLOAT8, the supported values are 0 and 1.
INT64 - - - dstTypeMax (double) Input Specifies the value of maxType, corresponding to Amax(Dtype) in the formula. - Currently, supported values are 0.0 and [1.75, 3.5) (FLOAT4_E1M2), and 0.0 and [6.0, 12.0] (FLOAT4_E2M1). This value can be set only for FP4.
- The value 0.0 indicates that Amax(Dtype) is the maximum value of the quantization result data type; the value [1.75, 3.5) or [6.0, 12.0] indicates that Amax(Dtype) is the passed-in value.
DOUBLE - - - y (aclTensor*) Output Represents the quantized output tensor. Corresponds to y in the formula. - Empty tensors are supported.
- The dimensions of shape are the same as those of x.
- Data types are FLOAT4_E2M1, FLOAT4_E1M2, FLOAT8_E4M3FN, and FLOAT8_E5M2, which must correspond to dstType.
FLOAT4_E2M1, FLOAT4_E1M2, FLOAT8_E4M3FN, FLOAT8_E5M2 ND 2 FLOAT8 supports non-contiguous tensors; FLOAT4 does not support non-contiguous tensors. mxscale (aclTensor*) Output Output mxscale composed of mxscale_pre in the formula. The quantization scale corresponding to each group. - Supports empty tensors.
- If the shape of x is [m,n] and the shape of groupIndex is [g], the shape of mxscale is [(m/(blocksize∗2)+g),n,2].
FLOAT8_E8M0 ND 3 × workspaceSize Output Returns the size of the workspace that needs to be allocated on the Device. - - - - - executor 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 If a passed-in parameter is a required input, output, or required attribute and is a null pointer, 161001 is returned. roundMode passed in is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of x, groupIndex, y, or mxscale is not within the supported range. The shapes of x, y, and mxscale do not meet the validation conditions. The dimensions of x, groupIndex, y, and mxscale are not within the supported range. roundMode, dstType, blocksize, scaleAlg, or dstTypeMax is not a currently supported value. Non-contiguous tensor is not supported when y is FLOAT4_E2M1 or FLOAT4_E1M2. Non-contiguous tensor is not supported for mxscale. ACLNN_ERR_PARAM_NULLPTR 361001 The current platform is not within the range of supported platforms.
aclnnGroupedDynamicMxQuantV2
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by calling the first-phase API aclnnGroupedDynamicMxQuantV2GetWorkspaceSize. executor Input Op executor that contains the operator computation process. stream Input Stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation:
- aclnnGroupedDynamicMxQuantV2 defaults to a deterministic implementation.
- The shape constraints on x, groupIndex, y, and mxscale are as follows:
- rank(mxscale) = rank(x) + 1.
- mxscale.shape[0] = x.shape[0] / (blocksize * 2) + g, where g is the number of groups.
- mxscale.shape[-1] = 2. Other dimensions are the same as those of input x.
- Output y has the same shape as x.
- If the data type of output y is FLOAT4_E2M1 or FLOAT4_E1M2, the length of the tail axis (dimension 1) of x must be an even number.
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 "acl/acl.h"
#include "aclnnop/aclnn_grouped_dynamic_mx_quant_v2.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 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 from 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;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
int aclnnGroupedDynamicMxQuantV2Test(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 inputs and outputs, customizing them based on the API.
std::vector<int64_t> xShape = {8, 1};
std::vector<int64_t> groupIndexShape = {2};
std::vector<int64_t> yOutShape = {8, 1};
std::vector<int64_t> mxscaleOutShape = {2, 1, 2};
void* xDeviceAddr = nullptr;
void* groupIndexDeviceAddr = nullptr;
void* yOutDeviceAddr = nullptr;
void* mxscaleOutDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* groupIndex = nullptr;
aclTensor* yOut = nullptr;
aclTensor* mxscaleOut = nullptr;
//Values corresponding to BF16 (0, 8, 64, 512)
std::vector<uint16_t> xHostData = {{0}, {16640}, {17024}, {17408}, {0}, {16640}, {17024}, {17408}};
std::vector<uint32_t> groupIndexHostData = {4, 8};
//Values corresponding to float8_e4m3 (0, 4, 32, 256)
std::vector<uint8_t> yOutHostData = {{0}, {72}, {96}, {120}, {0}, {72}, {96}, {120}};
//Value corresponding to float8_e8m0 (2)
std::vector<std::vector<uint8_t>> mxscaleOutHostData = {{{128, 0}}, {{128, 0}}};
const char* roundModeOptional = "rint";
int64_t dstType = 36;
int64_t blocksize = 32;
int64_t scaleAlg = 0;
double dstTypeMax = 0.0;
// Create the x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &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 groupIndex aclTensor.
ret = CreateAclTensor(groupIndexHostData, groupIndexShape, &groupIndexDeviceAddr, aclDataType::ACL_INT32, &groupIndex);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> groupIndexTensorPtr(groupIndex, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> groupIndexDeviceAddrPtr(groupIndexDeviceAddr, 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 mxscaleOut aclTensor.
ret = CreateAclTensor(mxscaleOutHostData, mxscaleOutShape, &mxscaleOutDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &mxscaleOut);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> mxscaleOutTensorPtr(mxscaleOut, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> mxscaleOutDeviceAddrPtr(mxscaleOutDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Call the CANN operator library API and change the API name as required.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnGroupedDynamicMxQuantV2.
ret = aclnnGroupedDynamicMxQuantV2GetWorkspaceSize(x, groupIndex, roundModeOptional, dstType, blocksize, scaleAlg,
dstTypeMax, yOut, mxscaleOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicMxQuantV2GetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the workspaceSize calculated 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 aclnnGroupedDynamicMxQuantV2.
ret = aclnnGroupedDynamicMxQuantV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicMxQuantV2 failed. ERROR: %d\n", ret); return ret);
//(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);
// Obtain the output values. Copy the results from device memory to host memory. Modify the code as required based on the definition of the specific API.
auto size = GetShapeSize(yOutShape);
std::vector<uint8_t> yOutData(size, 0); // In C, fp8 data cannot be printed directly. It needs to be read as uint8 and converted from binary to fp8 manually.
ret = aclrtMemcpy(yOutData.data(), yOutData.size() * sizeof(yOutData[0]), yOutDeviceAddr,
size * 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 < size; i++) {
LOG_PRINT("y[%ld] is: %d\n", i, yOutData[i]);
}
size = GetShapeSize(mxscaleOutShape);
std::vector<uint8_t> mxscaleOutData(size, 0); // fp8 data cannot be directly printed in C. Read it as uint8 and manually convert the binary value to fp8
ret = aclrtMemcpy(mxscaleOutData.data(), mxscaleOutData.size() * sizeof(mxscaleOutData[0]), mxscaleOutDeviceAddr,
size * sizeof(mxscaleOutData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy mxscaleOut from device to host failed. ERROR: %d\n", ret);
return ret);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("mxscaleOut[%ld] is: %d\n", i, mxscaleOutData[i]);
}
return ACL_SUCCESS;
}
int main()
{
// 1. (Boilerplate) Initialize device/stream. For details, see the acl API manual.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = aclnnGroupedDynamicMxQuantV2Test(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicMxQuantV2Test failed. ERROR: %d\n", ret);
return ret);
Finalize(deviceId, stream);
return 0;
}