aclnnSwigluMxQuant
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: Adds the DynamicMxQuant operation after the Swish gated linear unit activation function to implement the SwigluMxQuant computation of x.
Formula when swigluMode is 0:
where Ai denotes the first half of xi, and Bi denotes the second half of xi.
Formula when swigluMode is 1:
where x_glu denotes the even-indexed part of xi, and x_linear denotes the odd-indexed part of xi.
Formula when swigluMode is 2:
Where x_glu and x_linear are obtained by splitting xi into the first half and the second half along the activateDim axis (non-interleaved splitting). When activateLeft is true, x_glu is the first half; otherwise, it is the second half. In this mode, axis must be -1.
Formula when swigluMode is 3:
where x_glu and x_linear are obtained by splitting xi along the activateDim axis into the first half and the second half (non-interleaved chunking). In this mode, the gluAlpha and gluBias parameters are ignored (sigmoid uses a fixed alpha=1 and no bias is added), and axis must be -1.
Use case 1: when scaleAlg is 0, the DynamicMxQuant computation logic:
- The input x is grouped along the axis dimension into groups of k = blocksize = 32 numbers. A group of k numbers is dynamically quantized into , k = blocksize
The quantized are combined into the output yOut according to the positions of the corresponding , and mxscale is combined into the output mxscaleOut according to the corresponding groupings along the 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 |
- Use case 2: when scaleAlg is 1 (only FP8 types are involved), the DynamicMxQuant computation logic:
- 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 representable range of the target data type FP8, where is the maximum value that the target precision can represent.
- 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:
- The final step applied to quantization: for each element in a block, . The final quantized output is , where denotes the scale factor of the block, which is here, and denotes the quantized data in the block.
Function Prototype
Each operator uses a two-phase API. Call "aclnnSwigluMxQuantGetWorkspaceSize" first to obtain the workspace size required for computation and the executor containing the operator computation process. Then call "aclnnSwigluMxQuant" to perform the computation.
aclnnStatus aclnnSwigluMxQuantGetWorkspaceSize(
const aclTensor *x,
const aclTensor *groupIndexOptional,
int64_t activateDim,
bool activateLeft,
int64_t swigluMode,
double clampLimit,
double gluAlpha,
double gluBias,
int64_t groupMode,
int64_t axis,
int64_t dstType,
char *roundModeOptional,
int64_t scaleAlg,
double maxDtypeValue,
const aclTensor *yOut,
const aclTensor *mxscaleOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSwigluMxQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSwigluMxQuantGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input Input data to be processed, which is x in the formula. - The shape is [X1,X2,...Xn,2H], with 2 to 7 dimensions.
- The dimension of input x corresponding to activateDim must be a multiple of 2.
- Empty tensors are not supported.
FLOAT16, BFLOAT16 ND 2-7 √ groupIndexOptional (aclTensor*) Input group_index required for MoE grouping. - Supports a 1D tensor with shape [groupNum]. groupNum must be greater than or equal to 1 and less than or equal to 256.
- Each value in data must be an integer greater than or equal to 0, and the sum of all values must be less than or equal to the total number of rows of x to be quantized.
- Optional parameter. A null pointer can be passed.
- Empty tensors are not supported (shape[0]=0 is rejected, which is different from not passing this parameter).
- If this input exists and either activateDim or axis is not the trailing axis, the shape of input x must be 2D.
INT32, INT64 ND 1 √ activateDim (int64_t) Input Indicates the axis specified for splitting in the swish computation. - The value range of activateDim is [-1, -2, xDim - 2, xDim - 1] (where xDim is the dimension of input x).
- If activateDim is not the last axis, swigluMode must be 0.
- - - - activateLeft (bool) Input Indicates whether swiglu activation is performed on the left half of the input. - If the value is false, activation is performed on the right half of the input. If swigluMode is 1, activation is performed on the parts of x at even indices (this parameter does not take effect).
- - - - swigluMode (int64_t) Input Specifies the computation mode of swiglu. - Value range: [0, 3].
- 0: the traditional swiglu computation method.
- 1: a swiglu variant that uses the odd-even chunking method and supports clampLimit, activation coefficients, and bias.
- 2: a swiglu variant that uses the front-back halving method. It performs clamp first, then sigmoid(alpha) activation, and supports bias. This mode requires axis=-1.
- 3: a swiglu variant that uses the front-back halving method. It performs sigmoid activation first (alpha is fixed to 1) and then clamp. Bias is not supported. This mode requires axis=-1.
- - - - clampLimit (double) Input Indicates the threshold value used by the swiglu variant. - This parameter is an optional parameter.
- Used to clamp the input. The value must be greater than 0 and less than infinity to prevent excessively large values from affecting the stability of the swiglu computation.
- - - - gluAlpha (double) Input Indicates the scaling parameter used by the swiglu variant. - Optional parameter.
- Used to adjust the scaling of the linear part in the glu activation function.
- - - - gluBias (double) Input Specifies the bias parameter used by the swiglu variant. - Optional parameter.
- Used to add an offset to the linear computation in swiglu.
- - - - groupMode (int64_t) Input Represents the mode corresponding to groupIndexOptional. - Value range: [0, 1].
- 0: count mode.
- 1: cumsum mode.
- - - - axis (int64_t) Input Specifies the axis on which DynamicMxQuant quantization is performed. - Value range: [-1, -2, xDim - 2, xDim - 1] (where xDim refers to the dimension of input x).
- - - - dstType (int64_t) Input Specifies the data type of output y. - The value range of dstType is [35, 36, 40, 41], corresponding to FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, and FLOAT4_E1M2 respectively.
- - - - roundModeOptional(char*) Input Specifies the rounding mode for output y. - The value range is ["rint", "round", "floor"].
- When the data type of output y is FLOAT8_E5M2 or FLOAT8_E4M3FN, only the "rint" mode is supported.
- A null pointer is supported. If a null pointer is passed in, "rint" is used.
- - - - scaleAlg (int64_t) Input Specifies the calculation method of mxscaleOut, corresponding to scaleAlg in the formula. - The value range of scaleAlg is [0, 1, 2]. 0 indicates scenario 1, and 1 indicates scenario 2.
- When dstType is FLOAT4_E2M1 or FLOAT4_E1M2, only the value 0 is supported.
- Currently, only the values 0 and 1 are supported.
- - - - maxDtypeValue (double) Input Specifies the maximum value of the target data type in the DynamicMxQuant process. - Value range of maxDtypeValue: no less than 0. This is a reserved parameter and does not take effect in the current version.
- - - - yOut (aclTensor*) Output Represents the quantized result of input x, corresponding to Pi and di in the formula. - If activateDim corresponds to the tail axis of x, the shape is [X1,X2,...Xn,H].
- If activateDim does not correspond to the tail axis of x, the shape is [X1,X2,...,XactivateDim / 2,...,2H].
- If the data type of yOut is FLOAT4_E2M1 or FLOAT4_E1M2, the last dimension of yOut must be a multiple of 2.
- Empty tensors are not supported.
FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, FLOAT4_E1M2 ND 2-7 √ mxscaleOut (aclTensor*) Output Represents the quantization scale of each group, corresponding to mxscale and Sb in the formula. - The shape on the axis is obtained by dividing the corresponding axis value of yOut by blocksize=32 and rounding up, and then padding to an even number. The padding value is 0.
- If axis is not the tail axis and groupIndexOptional is present, the shape on the axis is the corresponding axis value of yOut divided by 64 plus groupNum.
- If axis is not the tail axis, the mxscaleOut output requires interleaving for every two rows of data.
- Empty tensors are not supported.
FLOAT8_E8M0 ND 3-8 √ workspaceSize (uint64_t*) Output Returns the size of the workspace 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 x, yOut, or mxscaleOut is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not in the supported range. The dimension of the input or output is not in the supported range. activateDim is not in the specified value range. swigluMode is not in the specified value range. clampLimit is not in the specified value range. axis is not in the specified value range. dstType is not in the specified value range. roundModeOptional is not in the specified value range. scaleAlg is not within the specified value range. When swigluMode is 2 or 3, axis is not -1.
aclnnSwigluMxQuant
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device side. workspaceSize Input Size of the workspace allocated on the Device side, obtained by calling the first-phase API aclnnSwigluMxQuantGetWorkspaceSize. 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:
- aclnnSwigluMxQuant defaults to a deterministic implementation.
The dimension of input x corresponding to activateDim must be a multiple of 2, and the number of dimensions of x must be greater than 1.
If activateDim is not the last axis, swigluMode must be 0.
If swigluMode is 2 or 3, axis must be -1 (only last-axis quantization is supported).
When the data type of output yOut is FLOAT4_E2M1 or FLOAT4_E1M2, the last dimension of yOut must be a multiple of 2.
If the data type of output yOut is FLOAT4_E2M1 or FLOAT4_E1M2, scaleAlg must be 0.
Each element of groupIndexOptional must be an integer greater than or equal to 0, and the sum of all elements must not exceed the total number of rows of x to be quantized (that is, the product of the remaining axes of input x excluding the last axis).
The caller allocates memory for the outputs yOut/mxscaleOut based on the shape derived by the API. The operator writes the complete quantization result back to the output tensor. The output parts beyond the range covered by the sum of all elements in groupIndexOptional are not cleared and contain garbage data.
The memory spaces of the input and output cannot overlap. In-place modification is not supported.
The operator does not modify any input data during execution.
If activateDim is not the last axis, or axis is not the last axis, and groupIndexOptional is provided, input x must be 2-dimensional.
If the data type of output yOut is FLOAT8_E4M3FN or FLOAT8_E5M2, roundModeOptional must be rint.
Empty tensors are not supported: if any dimension in the shape of x, groupIndexOptional, yOut, or mxscaleOut is 0 (the number of elements is 0), API verification fails and ACLNN_ERR_PARAM_INVALID is returned.
x must be a 2-7 dimensional tensor. rank=0 scalar tensors are not supported.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_swiglu_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) {
// 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 data from the host 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;
}
int main() {
// 1. (Boilerplate) Initialize the device/stream. For details, see the acl API manual
// Fill in 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 inputs and outputs based on the API.
std::vector<int64_t> xShape = {2, 64};
std::vector<int64_t> groupIndexShape = {1};
std::vector<int64_t> outShape = {2, 32};
std::vector<int64_t> scaleOutShape = {2, 1, 2};
void* xDeviceAddr = nullptr;
void* groupIndexDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
void* scaleOutDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* groupIndex = nullptr;
aclTensor* out = nullptr;
aclTensor* scaleOut = nullptr;
std::vector<uint16_t> xHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63};
std::vector<uint8_t> outHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
std::vector<uint8_t> scaleOutHostData = {0, 0, 0, 0};
bool activateLeft = true;
int64_t dstType = 36;
int64_t activateDim = -1;
int64_t swigluMode = 1;
float clampLimit = 7.0;
float gluAlpha = 1.0;
float gluBias = 1.702;
int64_t groupMode = 0;
int64_t axis = -1;
int64_t scaleAlg = 0;
float maxDtypeValue = 0.0;
// Create x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create scaleOut aclTensor.
ret = CreateAclTensor(scaleOutHostData, scaleOutShape, &scaleOutDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &scaleOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Change it to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnSwigluMxQuant.
ret = aclnnSwigluMxQuantGetWorkspaceSize(x, nullptr, activateDim, activateLeft, swigluMode, clampLimit, gluAlpha, gluBias,groupMode, axis, dstType, "rint", scaleAlg, maxDtypeValue, out, scaleOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluMxQuantGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize computed 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 aclnnSwigluMxQuant.
ret = aclnnSwigluMxQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluMxQuant 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 values, copy the result from device memory to host memory, and modify the code based on the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<uint8_t> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]);
}
// 6. Release aclTensor and aclScalar, and modify the code based on the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(out);
aclDestroyTensor(scaleOut);
// 7. Release device resources, and modify the code based on the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(outDeviceAddr);
aclrtFree(scaleOutDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}