aclnnClippedSwigluGrad
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description: The backward operator of aclnnClippedSwiglu. It computes the gradient of input x,
gradXOut.Calculation Process:
- Step 1: Axis merging and splitting (merge the axes of x and split it into x0 and x1)
- Step 2: GroupIndex processing (optional) → Compute the number of valid rows
- Step 3: Recompute the forward intermediate quantities
- Step 4: Clamp backward propagation mask computation
- Step 5: SwiGLU backward gradient computation
- Step 6: Concatenate gradients for output
- Step 7: GroupIndex zeroing (optional)
Formula for axis merging and splitting:
Merge the axes of x based on the input parameter
dim. The dimensions after merging are [pre, cut, after], where the cut axis is the axis to be split, and pre and after can be 1. Since the elements along the after axis are stored contiguously and the computation is element-wise, merge the cut axis with the after axis to obtain x with dimensions [pre, cut]. The dimensions ofgradYafter merging are [pre, cut/2].Split x based on the
interleavedparameter:When
interleavedis true, it represents odd-even splitting:When
interleavedis false, it indicates front-back split:Where is the pre-dimension index, and is the half-width index after splitting.
GroupIndex processing formula (when
groupIndexis provided):Where: is the number of elements in groupIndex, and all subsequent steps process only the first rows of data. When
groupIndexis not provided, .Formula for recomputing forward intermediate quantities:
Where: represents with only the upper bound clamped, represents with both bounds clamped, is the sigmoid activation value, is the
alphaparameter, and is thelimitparameter.Clamp backward propagation mask formula:
Where is the indicator function, which is 1 if the condition is met and 0 otherwise.
SwiGLU backward gradient calculation formula:
Where: is the gradient of , is the gradient of , and is
gradY.Gradient concatenation output formula:
When
interleavedis true:When
interleavedis false:where is
gradXOut.GroupIndex zeroing formula (when
groupIndexis provided):Finally, reshape the output tensor
gradXOutso that the number of its dimensions is the same as that ofxbefore axis merging, and the size of each dimension is the same as that ofx.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnClippedSwigluGradGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call the "aclnnClippedSwigluGrad" API to perform the computation.
aclnnStatus aclnnClippedSwigluGradGetWorkspaceSize(
const aclTensor *gradY,
const aclTensor *x,
const aclTensor *groupIndexOptional,
int64_t dim,
double alpha,
double limit,
double bias,
bool interleaved,
const aclTensor *gradXOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnClippedSwigluGrad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnClippedSwigluGradGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor gradY (aclTensor*) Input Input gradY in the formula, representing the gradient of the forward output y. The dimensions must be greater than 0, and the size on the dimension specified by the input dim must be half of that of x. Other dimensions must be consistent with x. The data type must be consistent with x and gradXOut. Does not support empty Tensor, and the input does not support containing ±inf or nan. FLOAT, FLOAT16, BFLOAT16 ND 1-8 × x (aclTensor*) Input Input x in the formula, which is the input of the forward operator. Used to recompute the forward intermediate values. The dimension must be greater than 0 and must be an even number in the dimension corresponding to input parameter dim. Does not support empty tensors. The input does not support containing ±inf or nan. FLOAT, FLOAT16, BFLOAT16 ND 1-8 × groupIndexOptional (aclTensor*) Input The input groupIndex in the formula, representing the grouping case. Empty pointers are supported. If the pointer is not empty, the tensor must be 1-dimensional and elements must be greater than or equal to 0. The i-th element represents the number of x batches to be processed by the i-th group, and the sum of elements must be less than or equal to the product of all dimensions before the dim dimension prior to axis merging. Does not support empty tensors. The input does not support containing ±inf or nan. INT64 ND 1 × dim (int64_t) Input Input dim in the formula, representing the dimension index for merging and splitting x. Value range: [-x.dim(), x.dim()-1]. - - - - alpha (double) Input Input alpha in the formula, which represents a variant of the parameter used by SwiGlu. It is recommended to be 1.702. - - - - limit (double) Input Input limit in the formula, representing the threshold value used by the SwiGlu variant. Must be greater than 0, recommended to be 7.0. - - - - bias (double) Input Input bias in the formula, representing the bias parameter used by the SwiGlu variant. Recommended to be 1.0. - - - - interleaved (bool) Input Input interleaved in the formula, indicating whether to split x in an odd-even manner. Setting it to true represents odd-even split of x, and setting it to false represents front-back split of x. - - - - gradXOut (aclTensor*) Output Output gradXOut in the formula. Does not support empty pointer. The shape must be consistent with x. Does not support empty tensor. FLOAT, FLOAT16, BFLOAT16 ND 1-8 × workspaceSize (uint64_t*) Output Returns the size of the workspace to be applied 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 Return 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 parameters gradY/x/gradXOut are nullptr. ACLNN_ERR_PARAM_INVALID 161002 The data type of an input or output is not within the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The shape information of multiple input tensors is inconsistent, or an input attribute is not in the value range (see Parameters for details).
aclnnClippedSwigluGrad
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied on the Device side. workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnClippedSwigluGradGetWorkspaceSize. executor Input Op executor, which contains the operator computation flow. stream Input Stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation: aclnnClippedSwigluGrad defaults to a deterministic implementation.
Example
The following 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_clipped_swiglu_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;
}
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);
// x shape [2, 32], grad_y shape [2, 16], grad_x shape [2, 32]
std::vector<int64_t> xShape = {2, 32};
std::vector<int64_t> gradYShape = {2, 16};
std::vector<int64_t> gradXOutShape = {2, 32};
void* xDeviceAddr = nullptr;
void* gradYDeviceAddr = nullptr;
void* gradXOutDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* gradY = nullptr;
aclTensor* gradXOut = nullptr;
std::vector<float> xHostData(64, 1.0f);
std::vector<float> gradYHostData(32, 1.0f);
std::vector<float> gradXOutHostData(64, 0.0f);
int dim = -1;
float alpha = 1.702;
float limit = 7.0;
float bias = 1.0;
bool interleaved = true;
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradYHostData, gradYShape, &gradYDeviceAddr, aclDataType::ACL_FLOAT, &gradY);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradXOutHostData, gradXOutShape, &gradXOutDeviceAddr, aclDataType::ACL_FLOAT, &gradXOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
ret = aclnnClippedSwigluGradGetWorkspaceSize(gradY, x, nullptr, dim, alpha, limit, bias, interleaved, gradXOut,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwigluGradGetWorkspaceSize 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 = aclnnClippedSwigluGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwigluGrad 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 size = GetShapeSize(gradXOutShape);
std::vector<float> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), gradXOutDeviceAddr,
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: %f\n", i, resultData[i]);
}
aclDestroyTensor(x);
aclDestroyTensor(gradY);
aclDestroyTensor(gradXOut);
aclrtFree(xDeviceAddr);
aclrtFree(gradYDeviceAddr);
aclrtFree(gradXOutDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}