aclnnSwigluGroupQuantV2
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
aclnnSwigluGroupQuantV2 is the V2 API of aclnnSwigluGroupQuant,
corresponding to the standalone quantization mode quantMode=5 (mx_quant_v2). It adds the following to the MX quantization in V1:
- Adds the
alphaandbiasattributes to support the ClippedSwiGLU activation variant ; - The data type of
weightOptionalis expanded from FLOAT32 to FLOAT16, BFLOAT16, FLOAT32; - The quantization scale uses CuBALS (
scale_alg=1, no amax lower limit) and shares the same MX kernel as the first path of the dual-axis operatorswiglu_group_quant_with_dual_axis, so the first-path quantization values are consistent between training (dual-axis) and inference (single-axisquantMode=5).
Relationship with V1:
quantMode=5is an independent mode and is not derived from any parameter combination of V1. V1quantMode=0/1/2/3usesaclnnSwigluGroupQuant; onlyquantMode=5uses this API. Whenalpha=1.0,bias=0.0, and weight is FLOAT32 (or not passed), the activation of this API is the same as that of V1quantMode=1, but the quantization scale encoding is different (see "Quantization Computation").
Formula
Basic Computation Process
Step 1: Input splitting
Step 2: Clamping (optional)
Step 3: Variant SwiGLU activation
Step 4: Weight weighting (optional)
Step 5: MX FP8 quantization (CuBALS)
group_indexandscaleare not supported whenquantMode=5. Therefore, no group truncation or static quantization is performed; The inputxmust be 2D, and allTrows participate in the computation.
Step 1: Input Splitting
The input tensor is split into two parts along the last dimension ():
Step 2: Clamp Processing (Optional)
When clampLimit > 0, the input is clamped:
where is clampLimit. Clamping is disabled when clampLimit = -1.0.
Purpose of Clamp:
- (gating branch) is clamped to the positive range to prevent sigmoid gradient vanishing
- (linear branch) is clamped to the symmetric range to prevent numeric overflow
Step 3: Variant SwiGLU activation
Activation function (element-wise computation), variant form with alpha and bias:
Where:
- is
alpha - is
bias - is the Sigmoid function
When and , it degrades to the standard SwiGLU:
Complete computation step breakdown:
yOrigin Output:
When outputOrigin is set to True, yOrigin outputs the SwiGLU result
(pre-weighted, but already including the effects of clamp, alpha, and bias), which can be directly used for backward computation of grad_weight.
Step 4: Weight Weighting (Optional)
When weight is provided, the SwiGLU output is weighted:
where is the weight value of the -th token. It can be passed in as FLOAT16, BFLOAT16, or FLOAT32, and is processed at FP32 precision during computation.
MoE use case: The weight comes from the softmax output of the expert router and indicates the weight of the token for the current expert.
Step 5: MX FP8 quantization (CuBALS)
MX Quantization Principle: Uses the combination of E8M0 Scale + FP8 Data.
Grouping: Every 32 elements form a group, and elements fewer than 32 are padded with 0 for computation:
Amax computation (no lower limit for CuBALS):
$$ a_i = \max_{j=0}^{31} || $$Raw Scale Computation:
where has the following values:
- FP8 E4M3FN:
- FP8 E5M2:
Exponent ceiling (CuBALS): Extract the unbiased exponent and mantissa from , and round up the exponent to prevent quantization overflow:
E8M0 Scale encoding: is stored in FLOAT8_E8M0 as an unbiased exponent:
All-zero block handling: When , (no amax lower limit, consistent with the dual-axis operator).
Quantization computation:
Where cast_fp8_rint indicates the type conversion from FP32 to FP8, using the RINT (round to nearest) mode.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnSwigluGroupQuantV2GetWorkspaceSize" API to obtain the workspace size required for the computation and the executor containing the operator computation flow, and then call the "aclnnSwigluGroupQuantV2" API to perform the computation.
aclnnStatus aclnnSwigluGroupQuantV2GetWorkspaceSize(
const aclTensor *x,
const aclTensor *weightOptional,
const aclTensor *groupIndexOptional,
const aclTensor *scaleOptional,
int64_t dstType,
int64_t quantMode,
int64_t blockSize,
bool roundScale,
double clampLimit,
double dstTypeMax,
bool outputOrigin,
double alpha,
double bias,
const aclTensor *yOut,
const aclTensor *yScaleOut,
const aclTensor *yOriginOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSwigluGroupQuantV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSwigluGroupQuantV2GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-Contiguous Tensor x (aclTensor*) Input SwiGLU input. - Must be 2D, shape [T, D].
- D must be greater than or equal to 64 and divisible by 64.
- Empty tensors are not supported (T must be greater than 0).
- Data types are FLOAT16 and BFLOAT16.
FLOAT16, BFLOAT16 ND 2 × weightOptional (aclTensor*) Input (optional) MOE weight tensor, used for the weighted computation of the SwiGLU output. - Optional parameter.
- If not empty, the data type must be FLOAT16, BFLOAT16, or FLOAT32, and the number of elements must be equal to T.
- FLOAT16 and BFLOAT16 are new capabilities in V2.
FLOAT16, BFLOAT16, FLOAT32 ND 1-8 × groupIndexOptional (aclTensor*) Input (optional) Group index. - Not supported when quantMode=5. You must pass nullptr.
INT64 ND 1 × scaleOptional (aclTensor*) Input (optional) Static quantization invScale. - Not supported for quantMode=5. You must pass nullptr.
FLOAT32 ND 1 × dstType (int64_t) Input Target quantization type. - Supported values are 35 and 36, indicating FLOAT8_E5M2 and FLOAT8_E4M3FN respectively.
- FP4 types (FLOAT4_E2M1/FLOAT4_E1M2) are not supported.
- - - - quantMode (int64_t) Input Quantization mode. - Supported values: 0, 1, 2, 3, 5.
- - - - blockSize (int64_t) Input Quantization block size. - 0 indicates that the default block size of the current quantization mode is used.
- When quantMode is 5, 0 or 32 is supported.
- - - - roundScale (bool) Input Specifies whether to round scale to a power of 2. - When quantMode is 5, roundScale must be true.
- - - - clampLimit (double) Input Clamp threshold before SwiGLU computation. - -1.0 indicates that clamp is disabled.
- When clamp is enabled, clampLimit must be greater than 0.
- - - - dstTypeMax (double) Input Maximum finite value of the target quantization type. - This parameter does not take effect when quantMode is 5.
- - - - outputOrigin (bool) Input Specifies whether to output the pre-weighted SwiGLU result of weight. - true indicates that yOrigin is output. If false, the yOrigin output is invalid.
- - - - alpha (double) Input New in V2. Scaling factor for the Sigmoid input in the SwiGLU activation. - Must be a finite positive number (alpha > 0).
- - - - bias (double) Input New in V2. Bias of the linear branch in the SwiGLU activation. - Must be a finite number.
- - - - yOut(aclTensor*) Output Quantization output. - shape is [T, D/2].
- The data type must be the same as dstType.
FLOAT8_E5M2, FLOAT8_E4M3FN ND 2 × yScaleOut (aclTensor*) Output Quantization scale output. - The shape is [T, ceil(ceil((D/2)/32)/2), 2]. Every 2 scales are stored in pairs in the last dimension.
- The data type is FLOAT8_E8M0.
- Unused padding positions are filled with 0.
FLOAT8_E8M0 ND 3 × yOriginOut (aclTensor*) Output Pre-weighted SwiGLU result. - Shape is [T, D/2].
- Data type must be the same as that of x.
- Null pointers are not supported.
- If outputOrigin is false, no content is written, but the shape is still [T, D/2].
FLOAT16, BFLOAT16 ND 2 × workspaceSize (uint64_t*) Output Returns the size of the workspace to be requested on the Device. - - - - - executor (aclOpExecutor**) 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 x, yOut, yScaleOut, yOriginOut, workspaceSize, or executor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The input or output data type is not within the supported range. The input or output shape does not meet constraints (for example, x is not a 2D tensor, or D is not aligned to 64). dstType, quantMode, blockSize, roundScale, or clampLimit is not a currently supported value. alpha is not a finite positive number, or bias is not a finite number. weightOptional does not meet optional input constraints, or groupIndexOptional/scaleOptional is illegally passed in. ACLNN_ERR_INNER_TILING_ERROR 561002 The shape information of multiple input tensors does not match, or an input attribute is out of the value range (see Parameters for details).
aclnnSwigluGroupQuantV2
Parameters:
Parameter Input/Output Description workspace Input Memory address of the workspace allocated on the device. workspaceSize Input Size of the workspace allocated on the device, obtained by calling the first-phase API aclnnSwigluGroupQuantV2GetWorkspaceSize. executor Input Executor of the op, containing the computation flow of the operator. stream Input Specifies the stream for executing the task. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation: aclnnSwigluGroupQuantV2 defaults to a deterministic implementation.
- Quantization mode: Supports
quantMode=0/1/2/3/5;dstTypesupports 35 (FLOAT8_E5M2) and 36 (FLOAT8_E4M3FN). - Input shape:
xmust be a 2D tensor of[T, D], withT > 0,D >= 64, andD % 64 == 0. - blockSize supports 0 or 32; roundScale must be true.
- Not supported:
groupIndexOptional(group truncation) andscaleOptional(static quantization); both must be set tonullptr. - weightOptional supports FLOAT16, BFLOAT16, and FLOAT32; the number of elements is
T. yOriginOutsemantics: the output is the pre-weighted SwiGLU activation result (including the effects of clamp, alpha, and bias), which is independent of the value ofweightand can be directly used to computegrad_weightin backward propagation.- Scale algorithm: CuBALS is fixed (
scale_alg=1), with no lower limit on amax; the scale of an all-zero block is encoded as 0. This algorithm reuses the same kernel as the first path of the dual-axis operatorswiglu_group_quant_with_dual_axis, ensuring that the first-path quantization values are identical between training and inference. - Differences from V1:
quantMode=5is supported only by this API; foraclnnSwigluGroupQuant,quantMode=1retains the original scale encoding (amax lower limit of ); the two APIs may produce different quantization scales for the same input (all-zero blocks and blocks with extremely small amax).
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <cstdint>
#include <cstring>
#include <iostream>
#include <limits>
#include <memory>
#include <stdexcept>
#include <vector>
#include "acl/acl.h"
#include "aclnn/acl_meta.h"
#include "aclnnop/aclnn_swiglu_group_quant_v2.h"
namespace SwigluExample {
inline int64_t Numel(const std::vector<int64_t>& shape)
{
int64_t size = 1;
for (int64_t dim : shape) {
if (dim <= 0 || size > std::numeric_limits<int64_t>::max() / dim) {
throw std::invalid_argument("tensor shape must be positive and fit int64");
}
size *= dim;
}
return size;
}
inline bool CheckHardwareSupport(const char* operatorName)
{
const char* socName = aclrtGetSocName();
if (socName == nullptr) {
std::cout << "Warning: cannot get SOC name, skip hardware check" << std::endl;
return true;
}
std::cout << "Current SOC: " << socName << std::endl;
if (strstr(socName, "Ascend950") != nullptr || strstr(socName, "ascend950") != nullptr) {
return true;
}
std::cout << "Warning: " << operatorName << " only supports Ascend950, current SOC '" << socName
<< "' is not supported. Skip test." << std::endl;
return false;
}
class Session {
public:
explicit Session(int& status) : status_(status) {}
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
~Session()
{
if (pending_) {
Record(aclrtSynchronizeStream(stream_), "aclrtSynchronizeStream");
}
if (executor_ != nullptr) {
Record(aclDestroyAclOpExecutor(executor_), "aclDestroyAclOpExecutor");
}
if (workspace_ != nullptr) {
Record(aclrtFree(workspace_), "aclrtFree(workspace)");
}
for (auto& tensor : tensors_) {
if (tensor->descriptor != nullptr) {
Record(aclDestroyTensor(tensor->descriptor), "aclDestroyTensor");
}
if (tensor->device != nullptr) {
Record(aclrtFree(tensor->device), "aclrtFree(tensor)");
}
}
if (stream_ != nullptr) {
Record(aclrtDestroyStream(stream_), "aclrtDestroyStream");
}
if (deviceSet_) {
Record(aclrtResetDevice(deviceId_), "aclrtResetDevice");
}
if (initialized_) {
Record(aclFinalize(), "aclFinalize");
}
}
void Check(int result, const char* operation)
{
if (result != ACL_SUCCESS) {
Record(result, operation);
throw std::runtime_error(operation);
}
}
void Init(int32_t deviceId)
{
deviceId_ = deviceId;
Check(aclInit(nullptr), "aclInit");
initialized_ = true;
Check(aclrtSetDevice(deviceId_), "aclrtSetDevice");
deviceSet_ = true;
Check(aclrtCreateStream(&stream_), "aclrtCreateStream");
}
template <typename T>
aclTensor* CreateTensor(const std::vector<T>& host, const std::vector<int64_t>& shape, aclDataType dtype)
{
const int64_t elements = Numel(shape);
if (static_cast<uint64_t>(elements) != host.size() ||
host.size() > std::numeric_limits<size_t>::max() / sizeof(T) || aclDataTypeSize(dtype) != sizeof(T)) {
throw std::invalid_argument("tensor shape, storage or dtype size mismatch");
}
const size_t bytes = host.size() * sizeof(T);
std::vector<int64_t> strides(shape.size(), 1);
for (size_t i = shape.size(); i > 1; --i) {
strides[i - 2] = strides[i - 1] * shape[i - 1];
}
tensors_.push_back(std::make_unique<TensorResource>());
auto& tensor = *tensors_.back();
Check(aclrtMalloc(&tensor.device, bytes, ACL_MEM_MALLOC_HUGE_FIRST), "aclrtMalloc(tensor)");
Check(aclrtMemcpy(tensor.device, bytes, host.data(), bytes, ACL_MEMCPY_HOST_TO_DEVICE), "aclrtMemcpy");
tensor.descriptor = aclCreateTensor(shape.data(), shape.size(), dtype, strides.data(), 0, ACL_FORMAT_ND,
shape.data(), shape.size(), tensor.device);
Check(tensor.descriptor == nullptr ? ACL_ERROR_INVALID_PARAM : ACL_SUCCESS, "aclCreateTensor");
return tensor.descriptor;
}
aclOpExecutor** ExecutorAddress() { return &executor_; }
aclOpExecutor* PrepareExecutor()
{
Check(aclSetAclOpExecutorRepeatable(executor_), "aclSetAclOpExecutorRepeatable");
return executor_;
}
void* AllocateWorkspace(uint64_t bytes)
{
if (bytes > 0) {
Check(aclrtMalloc(&workspace_, bytes, ACL_MEM_MALLOC_HUGE_FIRST), "aclrtMalloc(workspace)");
}
return workspace_;
}
aclrtStream StreamForLaunch()
{
pending_ = true;
return stream_;
}
void Synchronize()
{
Check(aclrtSynchronizeStream(stream_), "aclrtSynchronizeStream");
pending_ = false;
}
private:
struct TensorResource {
void* device = nullptr;
aclTensor* descriptor = nullptr;
};
void Record(int result, const char* operation)
{
if (result != ACL_SUCCESS) {
std::cerr << operation << " failed: " << result << std::endl;
if (status_ == ACL_SUCCESS) {
status_ = result;
}
}
}
int& status_;
int32_t deviceId_ = 0;
bool initialized_ = false;
bool deviceSet_ = false;
bool pending_ = false;
aclrtStream stream_ = nullptr;
aclOpExecutor* executor_ = nullptr;
void* workspace_ = nullptr;
std::vector<std::unique_ptr<TensorResource>> tensors_;
};
} // namespace SwigluExample
using SwigluExample::CheckHardwareSupport;
using SwigluExample::Numel;
int main()
{
int status = ACL_SUCCESS;
{
SwigluExample::Session session(status);
try {
session.Init(0);
if (!CheckHardwareSupport("SwigluGroupQuantV2")) {
std::cout << "\n=== Test SKIPPED (hardware not supported) ===" << std::endl;
return ACL_SUCCESS;
}
const std::vector<int64_t> xShape{64, 128};
const std::vector<int64_t> yShape{64, 64};
const std::vector<int64_t> scaleShape{64, 1, 2};
std::vector<uint16_t> xHost(Numel(xShape), 0x3C00); // FP16 1.0
std::vector<uint8_t> yHost(Numel(yShape), 0);
std::vector<uint8_t> scaleHost(Numel(scaleShape), 0);
std::vector<uint16_t> originHost(Numel(yShape), 0);
aclTensor* x = session.CreateTensor(xHost, xShape, ACL_FLOAT16);
aclTensor* y = session.CreateTensor(yHost, yShape, ACL_FLOAT8_E4M3FN);
aclTensor* scale = session.CreateTensor(scaleHost, scaleShape, ACL_FLOAT8_E8M0);
aclTensor* origin = session.CreateTensor(originHost, yShape, ACL_FLOAT16);
uint64_t workspaceSize = 0;
auto ret = aclnnSwigluGroupQuantV2GetWorkspaceSize(x, nullptr, nullptr, nullptr, ACL_FLOAT8_E4M3FN, 5, 32,
true, 7.0, 15.0, true, 1.702, 1.0, y, scale, origin,
&workspaceSize, session.ExecutorAddress());
session.Check(ret, "aclnnSwigluGroupQuantV2");
aclOpExecutor* executor = session.PrepareExecutor();
void* workspace = session.AllocateWorkspace(workspaceSize);
ret = aclnnSwigluGroupQuantV2(workspace, workspaceSize, executor, session.StreamForLaunch());
session.Check(ret, "aclnnSwigluGroupQuantV2");
session.Synchronize();
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
if (status == ACL_SUCCESS) {
status = ACL_ERROR_INVALID_PARAM;
}
}
}
if (status != ACL_SUCCESS) {
return 1;
}
std::cout << "aclnnSwigluGroupQuantV2 example succeeded" << std::endl;
return 0;
}