aclnnSwigluGroupGrad
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 SwigluGroupGrad operator implements the backward propagation computation of the SwiGLU activation function. It is used to compute the input gradient
grad_xand the weight gradientgrad_weight.Formula:
Step 1: GroupIndex processing (optional) → Compute trunc:
where is the number of MoE expert groups,
grad_xretains only the valid gradients of the first rows;grad_weightdoes not apply this row mask.Step 2 Input splitting (split x into x0 and x1):
Step 3 Clamp processing (optional):
Where is
clamp_limit.Step 4 SwiGLU backward propagation computation:
Forward propagation review:
Sigmoid computation:
SiLU computation:
SiLU gradient:
Input gradient computation:
where is the processed gradient input: if weight is provided, then ; if weight is not provided, then .
Step 5 Weight gradient calculation (optional):
where is the SwiGLU forward output; when weight exists, this output has been multiplied by weight. Sum along the last dimension (H dimension). When
groupIndexis provided,grad_weightis still computed over the full rows, and the mask is not applied.Step 6 Clamp backward propagation (optional):
Step 7 Gradient concatenation and GroupIndex processing: $$\mathbf{grad}x[t, h] = \begin{cases} \mathbf{grad}{x_0}[t, h] & h \in [0, H) \ \mathbf{grad}_{x_1}[t, h-H] & h \in [H, 2H) \end{cases}$$
When
groupIndexis provided, only the gradients of the first rows are valid:Key feature: In MoE inference backward propagation, different experts may process different numbers of tokens. groupIndex allows dynamic adjustment of the processing range.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnSwigluGroupGradGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclnnSwigluGroupGrad" API to perform the computation.
aclnnStatus aclnnSwigluGroupGradGetWorkspaceSize(
const aclTensor *gradY,
const aclTensor *x,
const aclTensor *weightOptional,
const aclTensor *yOriginOptional,
const aclTensor *groupIndexOptional,
float clampLimit,
aclTensor *gradXOut,
aclTensor *gradWeightOutOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSwigluGroupGrad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSwigluGroupGradGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor gradY (aclTensor*) Input Gradient of the output tensor, from the downstream layer. - shape=[..., H], commonly [T, H] or [B, S, H].
- Empty tensors are supported. If a tensor is empty, the API returns directly.
BFLOAT16, FLOAT16, FLOAT ND 1-8 √ x (aclTensor*) Input Input tensor for forward propagation. - shape=[..., 2H]. Common shapes are [T, 2H] or [B, S, 2H]. The last dimension must be an even number.
- Empty tensors are supported. For empty tensors, the API returns directly.
BFLOAT16, FLOAT16, FLOAT ND 1-8 √ weightOptional (aclTensor*) Input (optional) MoE weight tensor. - The number of elements equals the number of elements in gradY excluding the last dimension.
- Must be provided together with yOriginOptional.
FLOAT ND 1-8 √ yOriginOptional (aclTensor*) Input (optional) Forward output of SwiGLU. If weight is present, this output has been multiplied by weight. - shape=[..., H]; common shapes are [T, H] or [B, S, H].
- Must be provided together with weightOptional.
- The number of elements in non-tail dimensions equals that of gradY.
BFLOAT16, FLOAT16, FLOAT ND 1-8 √ groupIndexOptional (aclTensor*) Input (optional) GroupIndex tensor for dynamic kernel allocation. - shape=[G], G > 0.
- Data type: INT64.
INT64 ND 1 ([G]) √ clampLimit (float) Input Clamp threshold. - The value range is -1.0 or >0.0.
- clampLimit=-1.0 indicates that the Clamp backward propagation mask is disabled. When enabled, clampLimit must be >0.0.
FLOAT - - - gradXOut (aclTensor*) Output Input gradient tensor. - shape=[..., 2H]. Common shapes are [T, 2H] or [B, S, 2H], consistent with x.
BFLOAT16, FLOAT16, FLOAT ND 1-8 √ gradWeightOutOptional (aclTensor*) Output (optional) Weight gradient tensor. - Output when both weightOptional and yOriginOptional are provided.
- The shape is consistent with weightOptional.
FLOAT ND Same as weightOptional. √ workspaceSize (uint64_t*) Output Returns the workspace size 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 Return Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The required parameters gradY, x, or gradXOut is nullptr. ACLNN_ERR_PARAM_INVALID 161002 clampLimit does not satisfy the condition of being -1.0 or greater than 0.0 (including NaN and 0.0). The last dimension of x is not twice the last dimension of gradY. The total number of elements in the non-tail axes of gradY is different from that of x. The parameter shape is invalid. The parameter data types do not match.
aclnnSwigluGroupGrad
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 aclnnSwigluGroupGradGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Stream that executes tasks. Return Value
aclnnStatus: Returned status code. For details, see aclnn return code.
Constraints
- Determinism: aclnnSwigluGroupGrad defaults to a deterministic implementation.
- H must be greater than 0.
- The last dimension of x must be an even number (2H). The last dimension of gradY is H, which is half of the last dimension of x.
- The trailing axes of gradY and x satisfy x.shape[-1] == 2 * gradY.shape[-1], and the total numbers of non-trailing axis elements are equal.
- weightOptional and yOriginOptional must be provided together or left empty together; the number of elements in weightOptional is equal to the number of non-trailing axis elements in gradY; the last dimension of yOriginOptional is the same as that of gradY, and the number of non-trailing axis elements is equal to that of gradY.
- When groupIndexOptional is non-empty, it must be a 1-D non-empty tensor.
- gradY, x, yOriginOptional, and gradXOut must have the same data type (FLOAT, FLOAT16, or BFLOAT16).
- weightOptional and gradWeightOutOptional must be of the FLOAT type.
- groupIndexOptional must be of the INT64 type.
- The value of clampLimit is -1.0 or greater than 0.0. A value of -1.0 indicates that the Clamp backward propagation mask is disabled. When the mask is enabled, clampLimit must be greater than 0.0.
Example
The sample code is for reference only. For details about the compilation and execution procedure, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_swiglu_group_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, aclFormat format)
{
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, format, shape.data(),
shape.size(), *deviceAddr);
return 0;
}
int main()
{
// 1. Initialize Device and Stream.
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. Create the input tensor.
int64_t T = 2;
int64_t H = 256;
int64_t twoH = 2 * H;
std::vector<int64_t> gradYShape = {T, H};
std::vector<int64_t> xShape = {T, twoH};
std::vector<int64_t> weightShape = {T, 1};
std::vector<int64_t> yOriginShape = {T, H};
void *gradYDeviceAddr = nullptr;
void *xDeviceAddr = nullptr;
void *weightDeviceAddr = nullptr;
void *yOriginDeviceAddr = nullptr;
aclTensor *gradY = nullptr;
aclTensor *x = nullptr;
aclTensor *weight = nullptr;
aclTensor *yOrigin = nullptr;
std::vector<uint16_t> hostGradY(GetShapeSize(gradYShape), 1);
std::vector<uint16_t> hostX(GetShapeSize(xShape), 1);
std::vector<float> hostWeight(GetShapeSize(weightShape), 1.0f);
std::vector<uint16_t> hostYOrigin(GetShapeSize(yOriginShape), 1);
ret = CreateAclTensor(hostGradY, gradYShape, &gradYDeviceAddr, aclDataType::ACL_BF16, &gradY,
aclFormat::ACL_FORMAT_ND);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(hostX, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x,
aclFormat::ACL_FORMAT_ND);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(hostWeight, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight,
aclFormat::ACL_FORMAT_ND);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(hostYOrigin, yOriginShape, &yOriginDeviceAddr, aclDataType::ACL_BF16, &yOrigin,
aclFormat::ACL_FORMAT_ND);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Create the output tensor.
std::vector<int64_t> gradXOutShape = {T, twoH};
std::vector<int64_t> gradWeightOutShape = {T, 1};
void *gradXOutDeviceAddr = nullptr;
void *gradWeightOutDeviceAddr = nullptr;
aclTensor *gradXOut = nullptr;
aclTensor *gradWeightOut = nullptr;
std::vector<uint16_t> hostGradXOut(GetShapeSize(gradXOutShape), 0);
std::vector<float> hostGradWeightOut(GetShapeSize(gradWeightOutShape), 0.0f);
ret = CreateAclTensor(hostGradXOut, gradXOutShape, &gradXOutDeviceAddr, aclDataType::ACL_BF16, &gradXOut,
aclFormat::ACL_FORMAT_ND);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(hostGradWeightOut, gradWeightOutShape, &gradWeightOutDeviceAddr,
aclDataType::ACL_FLOAT, &gradWeightOut, aclFormat::ACL_FORMAT_ND);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 4. Get the workspace size.
float clampLimit = -1.0f;
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
ret = aclnnSwigluGroupGradGetWorkspaceSize(gradY, x, weight, yOrigin, nullptr, clampLimit, gradXOut,
gradWeightOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluGroupGradGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// 5. Allocate the workspace and perform the computation.
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 = aclnnSwigluGroupGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluGroupGrad 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);
// 6. Release the resources.
aclDestroyTensor(gradY);
aclDestroyTensor(x);
aclDestroyTensor(weight);
aclDestroyTensor(yOrigin);
aclDestroyTensor(gradXOut);
aclDestroyTensor(gradWeightOut);
aclrtFree(gradYDeviceAddr);
aclrtFree(xDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(yOriginDeviceAddr);
aclrtFree(gradXOutDeviceAddr);
aclrtFree(gradWeightOutDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}