aclnnSwigluGroupQuantGrad
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: The SwigluGroupQuantGrad operator implements the backward gradient computation of group quantization for the SwiGLU activation function. It computes the input gradient
grad_xand the weight gradientgrad_weight.Operator support scope: Supports the MoE use case (groupIndex passed in) and the non-MoE use case (groupIndex left empty). Supports the optional Clamp backward propagation mask and the optional Weight gradient computation.
Calculation Process:
- Step 0: GroupIndex processing (optional) → Compute trunc
- Step 1: Input splitting (split x into x0 and x1)
- Step 2: Clamp processing (optional)
- Step 3: SwiGLU backward propagation computation
- Step 4: Weight gradient computation (optional)
- Step 5: Gradient concatenation output
GroupIndex processing formula in the MoE use case:
where is the number of MoE expert groups, and all subsequent steps process only the first rows of data.
Input splitting formula:
Clamp processing formula (when clamp_limit > 0):
where is
clamp_limit.SiLU gradient formula:
where:
Input gradient computation formula:
where: if weight is provided, then ; if weight is not provided, then
Weight gradient computation formula (optional):
where: is the raw activation value output of the SwiGLU forward propagation, summed along the last dimension (H dimension).
Clamp backward propagation mask formula (when clamp_limit > 0):
where is the indicator function.
Gradient concatenation and GroupIndex processing formula:
Function Prototype
Each operator uses a two-phase API. First call the "aclnnSwigluGroupQuantGradGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclnnSwigluGroupQuantGrad" API to perform the computation.
aclnnStatus aclnnSwigluGroupQuantGradGetWorkspaceSize(
const aclTensor *gradY,
const aclTensor *x,
const aclTensor *weightOptional,
const aclTensor *yOriginOptional,
const aclTensor *groupIndexOptional,
double clampLimit,
const aclTensor *gradXOut,
const aclTensor *gradWeightOutOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSwigluGroupQuantGrad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSwigluGroupQuantGradGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor gradY (aclTensor*) Input Gradient output tensor, carrying the gradient from the downstream layer. - shape=[..., H], typically [T, H] or [B, S, H].
- T is the number of tokens, B is the batch size, S is the sequence length, and H is the hidden size.
BFLOAT16, FLOAT16, FLOAT ND 2-8 × x (aclTensor*) Input Input tensor for forward propagation. - shape=[..., 2H], commonly [T, 2H] or [B, S, 2H]. The last dimension must be an even number.
- The H in the last dimension corresponds to the H of gradY.
BFLOAT16, FLOAT16, FLOAT ND 2-8 × weightOptional (aclTensor*) Input (optional) MoE weight tensor. - When weight is not empty, the number of elements must equal the number of elements of x or gradY excluding the last dimension. Common shapes are [T] or [B, S].
- When weight is provided, yOrigin must also be provided to compute gradWeight.
FLOAT ND 1-8 × yOriginOptional (aclTensor*) Input (optional) Original activation value output of SwiGLU forward propagation. - shape=[..., H]. Common shapes are [T, H] or [B, S, H], which must be consistent with the shape of gradY.
- When weight is provided, yOrigin must also be provided to compute gradWeight.
BFLOAT16, FLOAT16, FLOAT ND 2-8 × groupIndexOptional (aclTensor*) Input (optional) GroupIndex tensor for dynamic kernel allocation. - shape=[G], dtype=INT64.
- G is the number of MoE expert groups.
- Each element in groupIndex is the number of group tokens in count mode.
INT64 ND 1 × clampLimit (float) Input Clamp threshold. - Value range: -1.0 or >0.0.
- clampLimit=-1.0 indicates that the Clamp backward propagation mask is disabled. If enabled, clampLimit must be >0.0.
FLOAT - - - gradXOut (aclTensor*) Output Input gradient tensor. - shape=[..., 2H]; common shapes are [T, 2H] or [B, S, 2H], the same as x.
- The data type is the same as that of gradY/x.
BFLOAT16, FLOAT16, FLOAT ND 2-8 × gradWeightOutOptional (aclTensor*) Output (optional) Weight gradient tensor. - Output when weight is provided; the shape is the same as that of the input weight.
- The data type is FLOAT.
FLOAT ND 1-8 × 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 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 Required parameter gradY/x/gradXOut is nullptr. ACLNN_ERR_INNER_TILING_ERROR 161002 The data type of the input or output is not in the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The shape information of multiple input tensors does not match, or input attributes are out of the value range (see Parameters).
aclnnSwigluGroupQuantGrad
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Size of the workspace allocated on the Device, obtained by the first-phase API aclnnSwigluGroupQuantGradGetWorkspaceSize. executor Input Op executor, which contains the operator computation flow. stream Input Stream for executing the task. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
Deterministic computation:
- aclnnSwigluGroupQuantGrad defaults to a deterministic implementation.
Input shape constraints:
- The last dimension of x must be an even number ().
- The last dimension of gradY is , corresponding to half of the last dimension of x.
- The shapes of the first n-1 dimensions of gradY and x must be the same.
Optional parameter constraints:
- If weight is provided, yOrigin must also be provided to compute gradWeight.
- The number of elements in weight must equal the product of the element counts of x or gradY excluding the last dimension.
- The shape of yOrigin must be the same as that of gradY.
Data type constraints:
- The data types of gradY, x, yOrigin, and gradX must be the same (FLOAT, FLOAT16, or BFLOAT16).
- weight and gradWeight must be of the FLOAT type.
- groupIndex must be of the INT64 type.
Clamp constraints:
- The value range of clampLimit is -1.0 or >0.0.
- clampLimit=-1.0 indicates that the Clamp backward propagation mask is disabled. When the mask is enabled, clampLimit must be >0.0.
Specification constraints:
Specification Item Specification Specification Description B 1~31 - S 0~128K - H 512, 768, 1024, 1536, 1792, 2048, 2560, 4096 -
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_group_quant_grad.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)
{
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);
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);
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);
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];
}
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
template <typename T>
int CreateAclTensorWithValue(const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
aclTensor** tensor, T value)
{
int64_t shapeSize = GetShapeSize(shape);
std::vector<T> hostData(shapeSize, value);
return CreateAclTensor(hostData, shape, deviceAddr, dataType, tensor);
}
int main()
{
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);
std::vector<int64_t> gradYShape = {512, 512};
std::vector<int64_t> xShape = {512, 1024};
std::vector<int64_t> weightShape = {512};
std::vector<int64_t> yOriginShape = {512, 512};
std::vector<int64_t> groupIndexShape = {256};
std::vector<int64_t> gradXShape = {512, 1024};
std::vector<int64_t> gradWeightShape = {512};
void* gradYDeviceAddr = nullptr;
void* xDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* yOriginDeviceAddr = nullptr;
void* groupIndexDeviceAddr = nullptr;
void* gradXDeviceAddr = nullptr;
void* gradWeightDeviceAddr = nullptr;
aclTensor* gradYTensor = nullptr;
aclTensor* xTensor = nullptr;
aclTensor* weightTensor = nullptr;
aclTensor* yOriginTensor = nullptr;
aclTensor* groupIndexTensor = nullptr;
aclTensor* gradXTensor = nullptr;
aclTensor* gradWeightTensor = nullptr;
int64_t gradYSize = GetShapeSize(gradYShape);
std::vector<float> gradYHostData(gradYSize, 1.0f);
for (int64_t i = 0; i < gradYSize; i++) {
gradYHostData[i] = static_cast<float>(i % 10) * 0.1f;
}
int64_t xSize = GetShapeSize(xShape);
std::vector<float> xHostData(xSize, 1.0f);
for (int64_t i = 0; i < xSize; i++) {
xHostData[i] = static_cast<float>((i % 20) - 10) * 0.5f;
}
int64_t weightSize = GetShapeSize(weightShape);
std::vector<float> weightHostData(weightSize, 1.0f);
for (int64_t i = 0; i < weightSize; i++) {
weightHostData[i] = static_cast<float>((i % 5) + 1) * 0.2f;
}
int64_t yOriginSize = GetShapeSize(yOriginShape);
std::vector<float> yOriginHostData(yOriginSize, 1.0f);
for (int64_t i = 0; i < yOriginSize; i++) {
yOriginHostData[i] = static_cast<float>((i % 8) + 1) * 0.3f;
}
int64_t groupIndexSize = GetShapeSize(groupIndexShape);
std::vector<int64_t> groupIndexHostData(groupIndexSize, 0);
int64_t groupStride = 512 / 256;
for (int64_t i = 0; i < groupIndexSize; i++) {
groupIndexHostData[i] = i * groupStride;
}
ret = CreateAclTensor(gradYHostData, gradYShape, &gradYDeviceAddr, aclDataType::ACL_FLOAT16, &gradYTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &xTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weightTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(yOriginHostData, yOriginShape, &yOriginDeviceAddr, aclDataType::ACL_FLOAT16, &yOriginTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(groupIndexHostData, groupIndexShape, &groupIndexDeviceAddr, aclDataType::ACL_INT64,
&groupIndexTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorWithValue<float>(gradXShape, &gradXDeviceAddr, aclDataType::ACL_FLOAT16, &gradXTensor, 0.0f);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorWithValue<float>(gradWeightShape, &gradWeightDeviceAddr, aclDataType::ACL_FLOAT,
&gradWeightTensor, 0.0f);
CHECK_RET(ret == ACL_SUCCESS, return ret);
float clampLimit = 1.0f;
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
ret = aclnnSwigluGroupQuantGradGetWorkspaceSize(gradYTensor, xTensor, weightTensor, yOriginTensor, groupIndexTensor,
clampLimit, gradXTensor, gradWeightTensor, &workspaceSize,
&executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluGroupQuantGradGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
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);
}
ret = aclnnSwigluGroupQuantGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluGroupQuantGrad failed. ERROR: %d\n", ret); return ret);
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
auto gradXResultSize = GetShapeSize(gradXShape);
std::vector<float> gradXResultData(gradXResultSize, 0);
ret = aclrtMemcpy(gradXResultData.data(), gradXResultData.size() * sizeof(float), gradXDeviceAddr,
gradXResultSize * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy gradX result from device to host failed. ERROR: %d\n", ret);
return ret);
LOG_PRINT("gradX output (first 10 elements):\n");
for (int64_t i = 0; i < 10 && i < gradXResultSize; i++) {
LOG_PRINT("gradX[%ld] = %f\n", i, gradXResultData[i]);
}
auto gradWeightResultSize = GetShapeSize(gradWeightShape);
std::vector<float> gradWeightResultData(gradWeightResultSize, 0);
ret = aclrtMemcpy(gradWeightResultData.data(), gradWeightResultData.size() * sizeof(float), gradWeightDeviceAddr,
gradWeightResultSize * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy gradWeight result from device to host failed. ERROR: %d\n", ret);
return ret);
LOG_PRINT("gradWeight output (first 10 elements):\n");
for (int64_t i = 0; i < 10 && i < gradWeightResultSize; i++) {
LOG_PRINT("gradWeight[%ld] = %f\n", i, gradWeightResultData[i]);
}
aclDestroyTensor(gradYTensor);
aclDestroyTensor(xTensor);
aclDestroyTensor(weightTensor);
aclDestroyTensor(yOriginTensor);
aclDestroyTensor(groupIndexTensor);
aclDestroyTensor(gradXTensor);
aclDestroyTensor(gradWeightTensor);
aclrtFree(gradYDeviceAddr);
aclrtFree(xDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(yOriginDeviceAddr);
aclrtFree(groupIndexDeviceAddr);
aclrtFree(gradXDeviceAddr);
aclrtFree(gradWeightDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}