aclnnSwigluGroup
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: Executes the SwiGLU activation and outputs the activation result with the same data type as input x.
Formula:
Let the size of the last dimension of input x be D. The left half is A, and the right half is B (that is,
h = D // 2,A = x[..., :h], andB = x[..., h:]).When
clampLimitis greater than 0, truncate A and B first:Calculate SwiGLU:
When
weightOptionalis not empty, multiply y by the weight token by token:When
groupIndexOptionalis not empty, the count mode controls the number of tokens actually processed: the number of tokens actually processed is the smaller value between the sum of all elements ingroupIndexOptionalandbs, wherebsis the product of the dimensions of x except the last dimension.
Function Prototype
Each operator uses a two-phase API. First call the "aclnnSwigluGroupGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the computation process, and then call the "aclnnSwigluGroup" API to perform the computation.
aclnnStatus aclnnSwigluGroupGetWorkspaceSize(
const aclTensor *x,
const aclTensor *weightOptional,
const aclTensor *groupIndexOptional,
double clampLimit,
const aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor);aclnnStatus aclnnSwigluGroup(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream);aclnnSwigluGroupGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input Input x in the formula. The last dimension is evenly divided into parts A and B. Does not support null pointers but supports empty tensors. The dimension must be greater than 0, and the last dimension must be an even number. FLOAT16, BFLOAT16, FLOAT32 ND 1-8 × weightOptional (aclTensor*) Input Input weightOptional in the formula. Per-token weight. Supports null pointers and empty tensors. If not a null pointer, the number of elements must equal the product of the dimensions of x excluding the last dimension (bs). FLOAT32 ND 1-8 × groupIndexOptional (aclTensor*) Input Input groupIndexOptional in the formula, which specifies the number of tokens per group in count mode. Supports null pointers, but does not support empty tensors alone. 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 tokens of x to be processed by the i-th group. The sum of all elements after truncation is the actual number of tokens processed. INT64 ND 1 × clampLimit (double) Input Input clampLimit in the formula. Indicates the upper bound for clamping A and B before activation. Clamps A and B before activation. The default value is -1.0, which means no clamping. A value greater than 0 must be passed when clamping is enabled. - - - N/A out (aclTensor*) Output Output y in the formula, which is the SwiGLU computation result. The data type is the same as that of x. The last dimension is half of the last dimension of x, and the other dimensions are the same as those of x. FLOAT16, BFLOAT16, FLOAT32 ND 1-8 × workspaceSize (uint64_t*) Output Returns the workspace size that needs to be allocated on the Device side. - - - - N/A executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - N/A 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 x or out is not in the supported range, or the data type of out is inconsistent with that of x. ACLNN_ERR_INNER_TILING_ERROR 561002 x is a 0-dimension tensor (scalar), or the last dimension of x is not an even number. clampLimit is neither -1.0 nor greater than 0. The data type of weightOptional is not FLOAT32, or the number of elements in weightOptional is inconsistent with the product of the dimensions of x excluding the last dimension. The data type of groupIndexOptional is not INT64, or groupIndexOptional alone is an empty tensor. The shape and dtype of other input tensors or the input attributes are out of the valid value range (see Parameters and Constraints for details).
aclnnSwigluGroup
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 calling the first-phase API aclnnSwigluGroupGetWorkspaceSize. executor Input Executor of the op, containing the operator computation flow. stream Input Stream where the task is executed. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Non-contiguous tensors are not supported: inputs x, weightOptional, groupIndexOptional, and output out must all be contiguous tensors.
- The last dimension of input x must be an even number (evenly split into two parts, A and B, and the last dimension of the output is half of the input).
- The data type of input x supports only FLOAT16, BFLOAT16, and FLOAT32, and the data type of out must be consistent with that of x.
- Deterministic computation: aclnnSwigluGroup defaults to a deterministic implementation. Non-deterministic implementation is not supported currently.
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 <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_swiglu_group.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 ACL_SUCCESS;
}
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-side 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);
// Compute 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, ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return ACL_SUCCESS;
}
int main()
{
// 1. (Boilerplate) Initialize the device/stream. For details, see the list of ACL APIs.
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 as needed based on the API
std::vector<int64_t> xShape = {2, 256};
std::vector<int64_t> yShape = {2, 128};
std::vector<uint16_t> xHostData(GetShapeSize(xShape), 0);
for (size_t i = 0; i < xHostData.size(); ++i) {
xHostData[i] = static_cast<uint16_t>(i % 23);
}
std::vector<uint16_t> yHostData(GetShapeSize(yShape), 0);
void* xDeviceAddr = nullptr;
void* yDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* y = nullptr;
// Create an aclTensor for x
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, ACL_FLOAT16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create an aclTensor for y
ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, ACL_FLOAT16, &y);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// weightOptional and groupIndexOptional are optional inputs. Passing nullptr here indicates that they are not used.
double clampLimit = -1.0;
// 3. Call the CANN operator library API. Replace it with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
// Call the first-phase API of aclnnSwigluGroup
ret = aclnnSwigluGroupGetWorkspaceSize(x, nullptr, nullptr, clampLimit, y, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluGroupGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate Device memory based on the workspaceSize computed 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 second-phase API of aclnnSwigluGroup.
ret = aclnnSwigluGroup(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluGroup failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Wait synchronously 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 values and copy the result from Device memory to the Host side.
std::vector<uint16_t> resultData(GetShapeSize(yShape), 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), yDeviceAddr,
resultData.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);
LOG_PRINT("result[0] is: %u\n", resultData[0]);
// 6. Release aclTensor and aclScalar. Modify according to the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(y);
// 7. Release Device resources. Modify according to the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(yDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}