aclnnSwigluMxQuantWithDualAxis
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: Fused operator that combines the SwiGLU activation function with dual-axis dynamic block quantization. It first computes the SwiGLU activation function on the input, and then dynamically quantizes the result block-wise along both the -1 axis and the -2 axis, outputting low-precision FP4/FP8 tensors and the corresponding scale factors.
Formula:
Stage 1: SwiGLU activation function
When
activateLeft=true:When
activateLeft=false:SwiGLU computation:
Stage 2: dual-axis dynamic block quantization
-1-axis quantization (column direction): The SwiGLU result is grouped along axis -1 in units of 32 numbers. Each group of 32 numbers is quantized to
-2-axis quantization (row direction): Groups the SwiGLU result along the -2 axis into groups of 32 numbers, and each group of 32 numbers is quantized into
obtained after -1-axis quantization forms the output y1Out according to the positions of the corresponding , and mxscale1 forms the output mxscale1Out according to the groups along the -1-axis dimension. obtained after -2-axis quantization forms the output y2Out according to the positions of the corresponding , and mxscale2 forms the output mxscale2Out according to the groups along the -2-axis dimension.
emax: The exponent of the maximum normal number of the corresponding data type.
| DataType | Emax | | :-----------: | :--: | | FLOAT4_E2M1 | 2 | | FLOAT4_E1M2 | 0 | | FLOAT8_E4M3FN | 8 | | FLOAT8_E5M2 | 15 |
Function Prototype
Each operator uses a two-phase API. Call the "aclnnSwigluMxQuantWithDualAxisGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor that contains the operator computation process. Then, call the "aclnnSwigluMxQuantWithDualAxis" API to execute the computation.
aclnnStatus aclnnSwigluMxQuantWithDualAxisGetWorkspaceSize(
const aclTensor *x,
const aclTensor *groupIndexOptional,
bool activateLeft,
char *roundModeOptional,
int64_t scaleAlg,
int64_t dstType,
double maxDtypeValue,
const aclTensor *y1Out,
const aclTensor *mxscale1Out,
const aclTensor *y2Out,
const aclTensor *mxscale2Out,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSwigluMxQuantWithDualAxis(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSwigluMxQuantWithDualAxisGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input Input tensor, x in the formula. - The shape is [M, 2N] and the last dimension must be an even number.
- If dstType is FLOAT4_E2M1/FLOAT4_E1M2, the last dimension must be divisible by 4.
- Empty tensors are not supported.
FLOAT16, BFLOAT16 ND 2 √ groupIndexOptional (aclTensor*) Input Group index, used to control group quantization boundaries. - The shape is [G]. Uses the cumsum mode to indicate the cumulative row count of each group.
- Passing an empty tensor is currently not supported.
INT64 ND 1 √ activateLeft (bool) Input SwiGLU activation side selection. - True indicates the left half is hidden and the right half is gate.
- False indicates the right half is hidden and the left half is gate.
- - - - roundModeOptional (char*) Input Indicates the mode of data conversion, corresponding to round_mode in the formula. - When dstType is 35/36, corresponding to output data types FLOAT8_E5M2/FLOAT8_E4M3FN of y1Out and y2Out, only {"rint"} is supported.
- When dstType is 40/41, corresponding to output data types FLOAT4_E2M1/FLOAT4_E1M2 of y1Out and y2Out, {"rint", "floor", "round"} are supported.
- If a null pointer is passed in, the "rint" mode is used.
STRING - - - scaleAlg (int64_t) Input Indicates the calculation method of mxscale1Out and mxscale2Out. - Value range: {1, 0}. 1 indicates the cuBLAS implementation, and 0 indicates the OCP implementation.
- When dstType is 40/41, only scaleAlg 0 is supported.
INT64 - - - dstType (int64_t) Input Indicates the types of y1Out and y2Out after the specified data conversion. - The input range is {35, 36, 40, 41}, which corresponds to the data types of output y1Out and y2Out: {35: FLOAT8_E5M2, 36: FLOAT8_E4M3FN, 40: FLOAT4_E2M1, 41: FLOAT4_E1M2}.
INT64 - - - maxDtypeValue (double) Input Reserved parameter. - Only 0 is supported for maxDtypeValue.
- - - - y1Out (aclTensor*) Output Indicates the corresponding result after the SwiGLU result is quantized along axis -1, corresponding to Pi in the corresponding formula. - The shape is [M, N], that is, half of the SwiGLU output.
FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, FLOAT4_E1M2 ND 2 √ mxscale1Out (aclTensor*) Output Indicates the quantization scale of each group along the -1 axis, which is mxscale1 in the corresponding formula. - The shape is [M, ceil(N/64), 2]. Even padding is required, and the pad value is 0.
FLOAT8_E8M0 ND 3 √ y2Out (aclTensor*) Output Indicates the corresponding result after quantizing the SwiGLU result along axis 2, that is, Pj in the corresponding formula. - The shape is [M, N].
FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, FLOAT4_E1M2 ND 2 √ mxscale2Out (aclTensor*) Output Indicates the quantization scale corresponding to each group on axis -2, which corresponds to mxscale2 in the formula. - When groupIndexOptional exists, the shape is [floor(M/64)+G, N, 2].
- When groupIndexOptional does not exist, the shape is [ceil(M/64), N, 2].
- Even padding is required, and the padding value is 0.
- The mxscale2Out output requires interleaving for every two rows of data.
FLOAT8_E8M0 ND 3 √ workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator calculation 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 x, y1Out, mxscale1Out, y2Out, or mxscale2Out is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x, roundModeOptional, dstType, scaleAlg, y1Out, mxscale1Out, y2Out, or mxscale2Out is not within the supported range. The shape of x, y1Out, y2Out, mxscale1Out, or mxscale2Out does not meet the validation conditions. roundModeOptional, dstType, or scaleAlg is not a currently supported value. The last dimension of x is not divisible by 2. ACLNN_ERR_RUNTIME_ERROR 361001 The current platform is not within the supported platform range.
aclnnSwigluMxQuantWithDualAxis
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device side. workspaceSize Input Workspace size allocated on the device side, obtained by calling the first-phase API aclnnSwigluMxQuantWithDualAxisGetWorkspaceSize. executor Input Executor for the op, containing the operator computation flow. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- x must be a 2D tensor, and the last dimension must be divisible by 2 (shape [M, 2N]).
- If dstType is FLOAT4_E2M1/FLOAT4_E1M2, the last dimension of x must be divisible by 4.
- FP8 output type (FLOAT8_E4M3FN) supports only the "rint" rounding mode.
- groupIndexOptional adopts the cumsum mode, where each value indicates the cumulative row count of the corresponding group. Each element of groupIndexOptional must be greater than 0, and the last element must be equal to M.
- Shape constraints for mxscale1Out and mxscale2Out:
- mxscale1Out.shape[-2] = (ceil(N/32) + 2 - 1) / 2.
- mxscale1Out.shape[-1] = 2.
- mxscale2Out.shape[-1] = 2.
- If groupIndexOptional is specified, mxscale2Out.shape[0] = floor(M/64) + G; otherwise, mxscale2Out.shape[0] = ceil(M/64).
- Other dimensions are the same as those of the SwiGLU output.
- Saturation mode is supported by default.
- Deterministic computation: aclnnSwigluMxQuantWithDualAxis 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 "acl/acl.h"
#include "aclnnop/aclnn_swiglu_mx_quant_with_dual_axis.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, 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 aclnnSwigluMxQuantWithDualAxisTest(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 as required by the API.
// Input x shape: [M, 2N] = [256, 1024]
std::vector<int64_t> xShape = {256, 1024};
// group_index shape: [G] = [1]. The cumsum mode is used, and the value 256 indicates that a group contains all 256 rows.
std::vector<int64_t> groupIndexShape = {1};
// SwiGLU output shape: [M, N] = [256, 512]
std::vector<int64_t> y1OutShape = {256, 512};
std::vector<int64_t> y2OutShape = {256, 512};
// mxscale1 shape: [M, ceil(N/32)/2 pad to even, 2] = [256, 8, 2]
std::vector<int64_t> mxscale1OutShape = {256, 8, 2};
// mxscale2 shape: [floor(M/64) + G, N, 2] = [4 + 1, 512, 2] = [5, 512, 2]
std::vector<int64_t> mxscale2OutShape = {5, 512, 2};
void* xDeviceAddr = nullptr;
void* groupIndexDeviceAddr = nullptr;
void* y1OutDeviceAddr = nullptr;
void* mxscale1OutDeviceAddr = nullptr;
void* y2OutDeviceAddr = nullptr;
void* mxscale2OutDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* groupIndex = nullptr;
aclTensor* y1Out = nullptr;
aclTensor* mxscale1Out = nullptr;
aclTensor* y2Out = nullptr;
aclTensor* mxscale2Out = nullptr;
// Initialize input data (BF16).
std::vector<uint16_t> xHostData(256 * 1024, 0);
for (int64_t i = 0; i < 256 * 1024; i++) {
xHostData[i] = static_cast<uint16_t>(i % 100);
}
// group_index data: cumsum mode. The value 256 indicates only one group, containing all rows.
std::vector<int64_t> groupIndexHostData = {256};
std::vector<uint8_t> y1OutHostData(256 * 512, 0);
std::vector<uint8_t> y2OutHostData(256 * 512, 0);
std::vector<uint8_t> mxscale1OutHostData(256 * 8 * 2, 0);
std::vector<uint8_t> mxscale2OutHostData(5 * 512 * 2, 0);
// Set the parameters.
bool activateLeft = true;
char* roundModeOptional = const_cast<char*>("rint");
int64_t dstType = 36; // FLOAT8_E4M3FN
int64_t scaleAlg = 1; // cuBLAS
double maxDtypeValue = 0.0;
// 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 groupIndex aclTensor.
ret = CreateAclTensor(groupIndexHostData, groupIndexShape, &groupIndexDeviceAddr, aclDataType::ACL_INT64, &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 y1Out aclTensor.
ret = CreateAclTensor(y1OutHostData, y1OutShape, &y1OutDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &y1Out);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> y1OutTensorPtr(y1Out, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> y1OutDeviceAddrPtr(y1OutDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create mxscale1Out aclTensor.
ret = CreateAclTensor(mxscale1OutHostData, mxscale1OutShape, &mxscale1OutDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &mxscale1Out);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> mxscale1OutTensorPtr(mxscale1Out, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> mxscale1OutDeviceAddrPtr(mxscale1OutDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create y2Out aclTensor.
ret = CreateAclTensor(y2OutHostData, y2OutShape, &y2OutDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &y2Out);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> y2OutTensorPtr(y2Out, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> y2OutDeviceAddrPtr(y2OutDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create mxscale2Out aclTensor.
ret = CreateAclTensor(mxscale2OutHostData, mxscale2OutShape, &mxscale2OutDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &mxscale2Out);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> mxscale2OutTensorPtr(mxscale2Out, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> mxscale2OutDeviceAddrPtr(mxscale2OutDeviceAddr, 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 aclnnSwigluMxQuantWithDualAxis (with groupIndex input).
ret = aclnnSwigluMxQuantWithDualAxisGetWorkspaceSize(x, groupIndex, activateLeft, roundModeOptional,
scaleAlg, dstType, maxDtypeValue, y1Out, mxscale1Out, y2Out, mxscale2Out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluMxQuantWithDualAxisGetWorkspaceSize 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 aclnnSwigluMxQuantWithDualAxis.
ret = aclnnSwigluMxQuantWithDualAxis(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluMxQuantWithDualAxis failed. ERROR: %d\n", ret); return ret);
// (boilerplate) Wait synchronously for the task to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// Obtain the output values and copy the results from the device side to the host side.
auto size1 = GetShapeSize(y1OutShape);
auto size2 = GetShapeSize(y2OutShape);
std::vector<uint8_t> y1OutData(size1, 0);
std::vector<uint8_t> y2OutData(size2, 0);
ret = aclrtMemcpy(y1OutData.data(), y1OutData.size() * sizeof(uint8_t), y1OutDeviceAddr,
size1 * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y1Out from device to host failed. ERROR: %d\n", ret);
return ret);
ret = aclrtMemcpy(y2OutData.data(), y2OutData.size() * sizeof(uint8_t), y2OutDeviceAddr,
size2 * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y2Out from device to host failed. ERROR: %d\n", ret);
return ret);
// Print part of the output results.
LOG_PRINT("y1Out first 10 elements:\n");
for (int64_t i = 0; i < 10 && i < size1; i++) {
LOG_PRINT("y1Out[%ld] = %d\n", i, y1OutData[i]);
}
LOG_PRINT("y2Out first 10 elements:\n");
for (int64_t i = 0; i < 10 && i < size2; i++) {
LOG_PRINT("y2Out[%ld] = %d\n", i, y2OutData[i]);
}
return ACL_SUCCESS;
}
int main()
{
// 1. (boilerplate) Initialize the device/stream. For details, see the acl API manual.
// Set deviceId based on your actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = aclnnSwigluMxQuantWithDualAxisTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluMxQuantWithDualAxisTest failed. ERROR: %d\n", ret); return ret);
Finalize(deviceId, stream);
return 0;
}