aclnnClippedSwigluV2
Applicable Products
Ascend 950PR&950DT products : Not 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: Clipped Swish gated linear unit activation function, which performs SwiGlu computation on x. Compared with aclnnClippedSwiglu, this API adds an input parameter: clamp_mode, to support use cases where some new models require the clamp operation to be performed after the silu activation.
Formula:
For a given input tensor x with dimensions [a,b,c,d,e,f,g...], aclnnClippedSwigluV2 performs the following computation:
Concatenate the axes of x based on the input parameter dim. After concatenation, the dimensions become [pre, cut, after]. The cut axis is the axis that needs to be split into two tensors after concatenation. The split method can be front-back split or odd-even split. pre and after can be 1. For example, when dim is 3, the dimensions of x after concatenation are [abc, d, efg*…]. In addition, since the elements of the after axis are stored contiguously and the computation is element-wise, the cut axis and the after axis are merged, resulting in x with dimensions [pre, cut].
Filters the pre axis of x based on the input parameter group_index. The formula is as follows:
where sum represents the sum of all elements in group_index. This step is skipped when group_index is not provided.
Split x according to the input parameter interleaved. The formula is as follows:
When interleaved is true, an odd-even split is performed:
When interleaved is false, a front-back split is performed:
Perform variant SwiGlu computation based on the input parameters alpha, limit, bias, and clamp_mode. The formula is as follows:
When clampMode is 0, the clamp operation is performed before silu:
When clampMode is 1, the clamp operation is performed after silu:
Reshape the output tensor y to have the same number of dimensions as x before concatenation, with the size on the dim axis being half of that of x, and other dimensions identical to x.
Function Prototype
Each operator uses a two-phase API. First call "aclnnClippedSwigluV2GetWorkspaceSize" to obtain the workspace size required for the calculation and the executor that includes the calculation process of the operator. Then call "aclnnClippedSwigluV2" to execute the calculation.
aclnnStatus aclnnClippedSwigluV2GetWorkspaceSize(
const aclTensor *x,
const aclTensor *groupIndexOptional,
int64_t dim,
double alpha,
double limit,
double bias,
bool interleaved,
int64_t clampMode,
const aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnClippedSwigluV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnClippedSwigluV2
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input Input x in the formula. - Does not support null pointers. The dimension must be greater than 0, and the shape must be even along the dimension corresponding to the input parameter dim.
- Supports empty tensors.
FLOAT, FLOAT16, BFLOAT16 ND 1-8 √ groupIndexOptional (aclTensor*) Input Input group_index in the formula, indicating grouping. - Supports null pointers.
- If not a null pointer, it must be 1-dimensional, and its elements must be greater than or equal to 0. The i-th element indicates the number of batches of x to be processed by the i-th group.
- The number of supported groups depends on the UB space size.
- Does not support null tensors.
INT64 ND 1 √ dim (int64_t) Input Input dim in the formula, which represents the dimension index for merging and splitting x. Value range: [-x.dim(), x.dim()-1] - - - - alpha (double) Input The input alpha in the formula, representing the parameter used by the SwiGlu variant. Recommended to be 1.702. - - - - limit (double) Input The input limit in the formula. It represents the threshold value used by variant SwiGlu. It must be greater than 0 and is recommended to be 7.0. - - - - bias (double) Input The input bias in the formula represents the bias parameter used by variant SwiGlu. Recommended to be 1.0. - - - - interleaved (bool) Input The input interleaved in the formula indicates whether x is split in odd-even mode. If set to true, x is split by odd and even positions; if set to false, x is split into front and back halves. - - - - clampMode (int64_t) Input Input clampMode in the formula, indicating the execution order of the clamp and silu operations. If set to 1, the clamp operation on A is moved to after the silu activation; that is, clamp is applied to the result of silu(A). If set to 0, the clamp operation on A is performed before the silu activation. - - - - out (aclTensor*) Output The output y in the formula. - Does not support null pointer. The shape is half of x on the dimension corresponding to input dim, and the same as x on other dimensions.
- Supports empty tensor.
FLOAT, FLOAT16, BFLOAT16 ND 1-8 × workspaceSize (uint64_t*) Output Returns the workspace size to be applied by the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which includes the calculation process of the operator. - - - - - 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 or out is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is out of the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The shape of the input or output is out of the supported range. The data type or shape size of groupIndexOptional is out of the supported range. dim is out of the dimension range supported by input x. limit is less than or equal to 0. clampMode is neither 0 nor 1.
aclnnClippedSwigluV2
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied by the Device side. workspaceSize Input Workspace size applied by the Device side, obtained by the first-phase API aclnnClippedSwigluV2GetWorkspaceSize. executor Input Op executor, which includes the calculation flow of the operator. stream Input Specifies the stream for executing tasks. Return value:
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation: aclnnClippedSwigluV2 defaults to a deterministic implementation. Non-deterministic implementation is not currently supported; even if deterministic computation is configured, the configuration does not take effect.
- The portion of output out beyond the sum of all elements in groupIndexOptional is not cleared, and the memory of this portion contains garbage data.
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_clipped_swiglu_v2.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: acl 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 memory on the device.
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 host-side data 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 the aclCreateTensor API 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 documentation.
// Set 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 the inputs and outputs according to the API definition.
std::vector<int64_t> xShape = {2, 32};
std::vector<int64_t> groupIndexShape = {1};
std::vector<int64_t> outShape = {2, 16};
void* xDeviceAddr = nullptr;
void* groupIndexDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* groupIndex = nullptr;
aclTensor* out = nullptr;
std::vector<float> 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};
std::vector<int64_t> groupIndexData = {1};
std::vector<float> 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};
int dim = -1;
float alpha = 1.0;
float limit = 7.0;
float bias = 1.702;
bool interleaved = true;
int64_t clampMode = 1;
// Create the x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the groupIndex aclTensor.
ret = CreateAclTensor(groupIndexData, groupIndexShape, &groupIndexDeviceAddr, aclDataType::ACL_INT64, &groupIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the actual API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the aclnnClippedSwigluV2 first-phase API.
ret = aclnnClippedSwigluV2GetWorkspaceSize(x, groupIndex, dim, alpha, limit, bias, interleaved, clampMode, out,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwigluV2GetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the workspaceSize calculated 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 aclnnClippedSwigluV2 second-phase API.
ret = aclnnClippedSwigluV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwigluV2 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 value and copy the result from device memory to host memory. Modify according to the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<float> 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: %f\n", i, resultData[i]);
}
// 6. Release aclTensor and aclScalar. Modify according to the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(groupIndex);
aclDestroyTensor(out);
// 7. Release device resources. Modify according to the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(groupIndexDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}