aclnnSwiGluQuant
Applicable Products
| Product | Supported |
|---|---|
| √ | |
| √ | |
| √ | |
| × | |
| × | |
| × |
Function
Description: Adds a quant operation after the SwiGlu activation function to implement SwiGluQuant computation on input x.
Supported scope: SwiGluQuant currently supports only MoE scenarios. The inputs x and group_index of SwiGluQuant come from the outputs of the GroupedMatMul operator and MoeInitRouting. The group_index parameter enables MoE group-based dynamic quantization, static per_tensor quantization, and static per_channel quantization.
Dynamic quantization formula:
Where A represents the first half of input x, B represents the second half of input x, g represents group_index, and G is the number of groups in group_index.
Static quantization formula:
Where A represents the first half of input x, B represents the second half of input x, g represents group_index, and G is the number of groups in group_index.
Function Prototype
Each operator is divided into a two-phase API. The "aclnnSwiGluQuantGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnSwiGluQuant" API is called to perform the computation.
aclnnStatus aclnnSwiGluQuantGetWorkspaceSize(
const aclTensor *x,
const aclTensor *smoothScalesOptional,
const aclTensor *offsetsOptional,
const aclTensor *groupIndexOptional,
bool activateLeft,
char *quantModeOptional,
const aclTensor *yOut,
const aclTensor *scaleOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSwiGluQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSwiGluQuantGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor x (aclTensor*) Input. Input data to be processed, i.e., x in the formula. - Empty tensors are not supported.
- The last dimension of x must be a multiple of 2, and the number of dimensions of x must be greater than 1. Currently, only the last dimension length of input x not exceeding 8192 is supported.
FLOAT16, BFLOAT16, FLOAT ND - × smoothScalesOptional (aclTensor*) Input smooth_scales for quantization, i.e., smooth_scales in the formula. - Empty tensors are not supported.
- The shape supports [G, N] and [G, ], where G is the number of groupIndex groups and N is half the size of the last dimension of the input x. Null pointers are not supported in the current version.
FLOAT ND - × offsetsOptional (aclTensor*) Input offsets in the formula. - Supports empty tensors.
- This parameter does not take effect in dynamic quantization scenarios. Pass a null pointer.
- In static quantization scenarios: the data type supports FLOAT.
- In per_channel mode, the shape supports [G, N].
- In per_tensor mode, the shape supports [G, ], and the data type and shape must be consistent with smoothScalesOptional.
FLOAT ND - × groupIndexOptional (aclTensor*) Input group_index required for MoE grouping, corresponding to group_index in the formula. - Supports empty tensor.
- The shape supports [G, ]. Elements in group_index must be non-decreasing, and the maximum value must not exceed the product of all dimension sizes of input x except the last dimension. The value of G must not exceed the product of all dimension sizes of input x except the last dimension.
INT32 ND - × activateLeft (bool) Input Computation input. true indicates activating the first half of input x, and false indicates activating the second half of input x. BOOL - - - quantModeOptional (char*) Input Computation input. "static" indicates static quantization, "dynamic" indicates dynamic quantization, and "dynamic_msd" indicates dynamic MSD quantization. Currently, only "dynamic" dynamic quantization and "static" static quantization are supported. Static quantization supports only per-tensor quantization and per-channel quantization. A null pointer passed by the user indicates dynamic quantization. STRING - - - yOut (aclTensor*) Output Output tensor. The last dimension of the computed output yOut is half the size of the last dimension of the input x, and the remaining dimensions are the same as those of x. INT8 ND - × scaleOut (aclTensor*) Output Output tensor. The shape of the output scaleOut, compared with the input x, has no last dimension, and the remaining dimensions are consistent with the input x. FLOAT ND - × workspaceSize (uint64_t*) Output Size of the workspace to be applied for on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - Return value
aclnnStatus: return code. For details, see aclnn Return Code.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 x or yOut is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not within the supported range. The parameter dimension of the input or output is not within the supported range. quantModeOptional is not within the specified value range.
aclnnSwiGluQuant
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied for on the Device side. workspaceSize Input Workspace size applied for on the Device side, obtained from the first-phase API aclnnSwiGluQuantGetWorkspaceSize. executor Input Operator executor that contains the operator computation flow. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return code. For details, see aclnn Return Code.
Constraints
Deterministic computation:
- aclnnSwiGluQuant defaults to a deterministic implementation.
Example
The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_swi_glu_quant.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: resource 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 apply for device-side memory.
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 data from the host side to the 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 a 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. See the ACL API.
// 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 input and output. Customize the construction based on the API.
std::vector<int64_t> xShape = {3, 32};
std::vector<int64_t> smoothScalesShape = {2, 16};
std::vector<int64_t> groupIndexShape = {2};
std::vector<int64_t> outShape = {3, 16};
std::vector<int64_t> scaleShape = {3};
void* xDeviceAddr = nullptr;
void* smoothScalesDeviceAddr = nullptr;
void* groupIndexDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
void* scaleDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* smoothScales = nullptr;
aclTensor* groupIndex = nullptr;
aclTensor* out = nullptr;
aclTensor* scale = 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, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95};
std::vector<float> smoothScalesHostData = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1};
std::vector<float> groupIndexHostData = {1, 3};
std::vector<int8_t> 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
std::vector<float> scaleHostData = {0, 0, 0};
// Create the x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the scale aclTensor.
ret = CreateAclTensor(smoothScalesHostData, smoothScalesShape, &smoothScalesDeviceAddr, aclDataType::ACL_FLOAT, &smoothScales);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the groupIndex aclTensor.
ret = CreateAclTensor(groupIndexHostData, groupIndexShape, &groupIndexDeviceAddr, aclDataType::ACL_INT32, &groupIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_INT8, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the scale aclTensor.
ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnSwiGluQuant.
ret = aclnnSwiGluQuantGetWorkspaceSize(x, smoothScales, nullptr, groupIndex, false, "dynamic", out, scale, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwiGluQuantGetWorkspaceSize 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 aclnnSwiGluQuant.
ret = aclnnSwiGluQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwiGluQuant failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronously wait for task execution to finish.
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 the device-side memory to the host side. Modify based on the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<int8_t> 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: %d\n", i, resultData[i]);
}
// 6. Destroy aclTensor and aclScalar. Modify based on the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(smoothScales);
aclDestroyTensor(groupIndex);
aclDestroyTensor(out);
aclDestroyTensor(scale);
// 7. Release device resources. Modify based on the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(smoothScalesDeviceAddr);
aclrtFree(groupIndexDeviceAddr);
aclrtFree(outDeviceAddr);
aclrtFree(scaleDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}