aclnnGroupedDynamicMxQuant
Applicable Products
| Product | Supported |
|---|---|
| √ | |
| × | |
| × | |
| × | |
| × | |
| × |
Function
Description: Performs grouped float8 dynamic quantization on the input data based on the start values of the group indices.
Formula:
- First, group the input x along dimension 0 by groupIndex. Within each group, further divide the data into sub-groups of k = blocksize elements. For each sub-group of k elements , compute the corresponding quantization scale mxscale_pre, yielding . The formula is given by (1) and (2) below.
- Divide each of these k numbers by mxscale, convert to the corresponding dst_type according to round_mode, and obtain the quantization result y. The formula is shown in (3).
The quantized forms the output y according to the positions of the corresponding . mxscale_pre is grouped by the corresponding groupIndex, and the first dimension within each group is padded to an even number to form the output mxscale.
emax: The exponent of the maximum normal number of the corresponding data type.
DataType emax FLOAT8_E4M3FN 8 FLOAT8_E5M2 15
Function Prototype
Each operator is divided into a two-phase API. You must first call the "aclnnGroupedDynamicMxQuantGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation flow, and then call the "aclnnGroupedDynamicMxQuant" API to perform the computation.
aclnnStatus aclnnGroupedDynamicMxQuantGetWorkspaceSize(
const aclTensor *x,
const aclTensor *groupIndex,
const char *roundMode,
int64_t dstType,
int64_t blocksize,
const aclTensor *y,
const aclTensor *mxscale,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnGroupedDynamicMxQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnGroupedDynamicMxQuantGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor x (aclTensor*) Input Represents the input tensor of the operator. Corresponds to input x in the formula. Supports empty tensors. FLOAT16, BFLOAT16 ND 2 √ groupIndex (aclTensor*) Input Start index of the quantization group. - Empty tensors are not supported.
- The indices must be greater than or equal to 0, non-decreasing, and the last value must equal the size of the first dimension of x.
INT32 ND 1 √ roundMode (char*) Input The round_mode in the formula, which specifies the data conversion mode. Only the "rint" mode is supported. - - - - dstType (int64_t) Input dst_type in the formula specifies the type of y after data conversion. The input range is {35, 36}, corresponding to the output y data type being {35: FLOAT8_E5M2, 36: FLOAT8_E4M3FN}. - - - - blocksize (int64_t) Input Specifies the number of elements quantized at a time in the formula. Currently, only the value 32 is supported. - - - - y (aclTensor*) Output Represents the quantized output tensor, corresponding to y in the formula. - Supports empty tensors.
- The dimensions of shape are consistent with x.
- The data type supports FLOAT8_E4M3FN and FLOAT8_E5M2, and must correspond to dstType.
FLOAT8_E4M3FN, FLOAT8_E5M2 ND 2 √ mxscale (aclTensor*) Output The output mxscale composed of mxscale_pre in the formula, representing the quantization scale for each group. - Supports empty tensors.
- Assume the shape of x is [m,n] and the shape of groupedIndex is [g], then the shape of mxscale is [(m/(blocksize∗2)+g),n,2].
FLOAT8_E8M0 ND 3 √ workspaceSize Output Returns the workspace size to be allocated on the Device side. - - - - - executor Output Returns the operator executor, which contains the operator computation flow. - - - - - Return value
aclnnStatus: return code. For details, see aclnn Return Code.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The input parameter is a required input, output, or required attribute, and is a null pointer, 161001 is returned. The input roundMode is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of x, groupIndex, y, and mxscale are not within the supported range. The shapes of x, y, and mxscale do not meet the validation conditions. approximate, quantMode, roundMode, and dstType are not within the supported range. The dimensions of x, groupIndex, y, and mxscale are not within the supported range. roundMode, dstType, and blocksize do not match the currently supported values. mxscale does not support non-contiguous tensors. ACLNN_ERR_RUNTIME_ERROR 361001 The current platform is not within the supported platform range.
aclnnGroupedDynamicMxQuant
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied for on the Device side. workspaceSize Input Workspace size applied for on the Device side, obtained from the first-phase API aclnnGroupedDynamicMxQuantGetWorkspaceSize. executor Input Operator executor, which contains the operator computation flow. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return code. For details, see aclnn Return Code.
Constraints
Deterministic computation:
- aclnnGroupedDynamicMxQuant defaults to a deterministic implementation.
Example
The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.
#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_grouped_dynamic_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: initialize resources.
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);
// Copy data from the host side to the device memory using aclrtMemcpy.
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);
// Compute the strides of a 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];
}
// Create an aclTensor using the aclCreateTensor API.
*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 aclnnGroupedDynamicMxQuantTest(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 input and output. Customize the construction based on the API requirements.
std::vector<int64_t> xShape = {8, 1};
std::vector<int64_t> groupedIndexShape = {2};
std::vector<int64_t> yOutShape = {8, 1};
std::vector<int64_t> mxscaleOutShape = {2, 1, 2};
void* xDeviceAddr = nullptr;
void* groupedIndexDeviceAddr = nullptr;
void* yOutDeviceAddr = nullptr;
void* mxscaleOutDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* groupedIndex = nullptr;
aclTensor* yOut = nullptr;
aclTensor* mxscaleOut = nullptr;
//Corresponding BF16 values (0, 8, 64, 512).
std::vector<uint16_t> xHostData = {{0}, {16640}, {17024}, {17408}, {0}, {16640}, {17024}, {17408}};
std::vector<uint32_t> groupedIndexHostData = {4,8};
//Values corresponding to float8_e4m3 (0, 4, 32, 256).
std::vector<uint8_t> yOutHostData = {{0}, {72}, {96}, {120}, {0}, {72}, {96}, {120}};
//Values 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;
// Create 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 groudedIndex aclTensor.
ret = CreateAclTensor(groupedIndexHostData, groupedIndexShape, &groupedIndexDeviceAddr, aclDataType::ACL_INT32, &groupedIndex);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> groupedIndexTensorPtr(groupedIndex, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> groupedIndexDeviceAddrPtr(groupedIndexDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create 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. Replace with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnGroupedDynamicMxQuant.
ret = aclnnGroupedDynamicMxQuantGetWorkspaceSize(x, groupedIndex, roundModeOptional, dstType, blocksize, yOut, mxscaleOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicMxQuantGetWorkspaceSize 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 aclnnGroupedDynamicMxQuant.
ret = aclnnGroupedDynamicMxQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicMxQuant failed. ERROR: %d\n", ret); return ret);
//(Boilerplate) Synchronously wait for task execution to finish.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// Obtain the output value and copy the result from the device side memory to the host side. Modify this based on the specific API definition.
auto size = GetShapeSize(yOutShape);
std::vector<uint8_t> yOutData(
size, 0); // In C, fp4 data cannot be printed directly. Read it as uint8 and manually convert it to fp4 via binary.
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); // In C, fp8 data cannot be printed directly. Read it as uint8 and manually convert it to fp8 via binary.
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 the device/stream. Refer to the acl API manual.
// Fill in the deviceId based on your actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = aclnnGroupedDynamicMxQuantTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedDynamicMxQuantTest failed. ERROR: %d\n", ret); return ret);
Finalize(deviceId, stream);
return 0;
}