aclnnFFNV2
Applicable Products
Ascend 950PR&950DT products : Not supported
Atlas A3 products : Not supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Supported
Atlas training products : Not supported
Function
Description: This FFN operator provides the computation capabilities of MoeFFN and FFN. When there is no expert group (expertTokens is empty), it is FFN; when there is an expert group, it is MoeFFN. Both are collectively referred to as FFN and belong to the MoE structure. MoE (Mixture-of-Experts) is a technique for training models with trillions of parameters. MoE decomposes the predictive modeling task into several subtasks, trains an expert model on each subtask, and develops a gating model that assigns one or more experts based on the input data, ultimately combining the computation results of multiple experts as the prediction result. The Mixture-of-Experts model assigns input data to the most relevant one or more experts and combines the computation results of all involved experts to determine the final result.
Compared with the FFN API, this API adds support for the expertTokens index input, which is distinguished by tokensIndexFlag.
Formula:
Non-quantized scenario:
$$ y=activation(x * W1 + b1) * W2 + b2 $$Quantization scenario:
$$ y=((activation((x * W1 + b1) * deqScale1) * scale + offset) * W2 + b2) * deqScale2 $$Pseudo-Quantized Scenario:
$$ y=activation(x * ((W1 + antiquantOffset1) * antiquantScale1) + b1) * ((W2 + antiquantOffset2) * antiquantScale2) + b2 $$
NOTE: Whether FFN delivers a performance gain in the no-expert or single-expert use case depends on actual test results. Try this fusion operator if the vector time of the small operators corresponding to the FFN structure in the entire network exceeds 30us and accounts for more than 10% of the FFN structure time. Do not use it if actual tests show performance degradation.
Function Prototype
Each operator follows the two-phase API. First call the "aclnnFFNV2GetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnFFNV2" API to perform the computation.
aclnnStatus aclnnFFNV2GetWorkspaceSize(
const aclTensor* x,
const aclTensor* weight1,
const aclTensor* weight2,
const aclIntArray* expertTokens,
const aclTensor* bias1,
const aclTensor* bias2,
const aclTensor* scale,
const aclTensor* offset,
const aclTensor* deqScale1,
const aclTensor* deqScale2,
const aclTensor* antiquantScale1,
const aclTensor* antiquantScale2,
const aclTensor* antiquantOffset1,
const aclTensor* antiquantOffset2,
const char* activation,
int64_t innerPrecise,
bool tokensIndexFlag,
const aclTensor* y,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnFFNV2(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnFFNV2GetWorkspaceSize
The common variables involved in Parameters are described as follows:
M indicates the number of tokens, corresponding to BS in the transformer (B: Batch, indicating the batch size of input samples.
S: Seq-Length, indicating the sequence length of input samples).
K1 indicates the number of input channels of the first matmul, corresponding to H in the transformer (Head-Size, indicating the hidden layer size).
N1 indicates the number of output channels of the first matmul.
K2 indicates the number of input channels of the second matmul.
N2 indicates the number of output channels of the second matmul, corresponding to H in the transformer.
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input Computation input, which is the input x in the formula. - FLOAT16, BFLOAT16, INT8 ND - √ weight1 (aclTensor*) Input Expert weight data, W1 in the formula. - FLOAT16, BFLOAT16, INT8, INT4 ND - √ weight2 (aclTensor*) Input Expert weight data, W2 in the formula. - FLOAT16, BFLOAT16, INT8, INT4 ND - √ expertTokens (aclIntArray*) Optional input Number of tokens for each expert. - INT64 ND - - bias1 (aclTensor*) Optional input Correction value of the weight data, which is b1 in the formula. - FLOAT16, FLOAT32, INT32 ND - - bias2(aclTensor*) Optional input Weight correction value, b2 in the formula. - FLOAT16, FLOAT32, INT32 ND - - scale(aclTensor*) Optional input Quantization parameter, quantization scaling factor. - FLOAT32 ND - √ offset (aclTensor*) Optional input Quantization parameter, quantization offset. - FLOAT32 ND - - deqScale1 (aclTensor*) Optional input Quantization parameter. Dequantization scale coefficient for the first matmul. - UINT64, INT64, FLOAT32, BFLOAT16 ND - - deqScale2 (aclTensor*) Optional input Quantization parameter, which is the dequantization scale of the second matmul. - UINT64, INT64, FLOAT32, BFLOAT16 ND - - antiquantScale1 (aclTensor*) Optional input Pseudo-quantization parameter, the scaling factor of the first matmul. - FLOAT16, BFLOAT16 ND - √ antiquantScale2 (aclTensor*) Optional input Pseudo-quantization parameter, the scaling factor of the second matmul. - FLOAT16, BFLOAT16 ND - √ antiquantOffset1 (aclTensor*) Optional input Pseudo-quantization parameter, the offset of the first matmul. - FLOAT16, BFLOAT16 ND - √ antiquantOffset2 (aclTensor*) Optional input Pseudo-quantization parameter. It is the offset of the second matmul. - FLOAT16, BFLOAT16 ND - √ activation (char*) Input Represents the activation function used, i.e., activation in the formula. - - - - - innerPrecise (int64_t) Optional input Specifies the choice between high precision and high performance. - When innerPrecise is 0, high-precision mode is enabled. In the non-quantized field, when all required parameters are FLOAT16, the operator uses the FLOAT32 data type to compute the inputs and outputs of the internal activation layers.
- When innerPrecise is 1, high-performance mode is enabled.
INT64 - - - tokensIndexFlag (bool) Optional input Indicates whether expertTokens is an index value. - If tokensIndexFlag is true, expertTokens indicates index values.
- If tokensIndexFlag is false, expertTokens indicates the number of tokens for each expert.
BOOL - - - y (aclTensor*) Output Output y in the formula. - FLOAT16, BFLOAT16 ND - √ workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - Atlas A2 products :- x supports FLOAT16, BFLOAT16, and INT8, and supports input with a minimum of 2 dimensions [M, K1] and a maximum of 8 dimensions.
- weight1 supports FLOAT16, BFLOAT16, INT8, and INT4. The dimension is [E, K1, N1] when experts are present and [K1, N1] when no experts are present.
- weight2 supports FLOAT16, BFLOAT16, INT8, and INT4. The dimension is [E, K2, N2] when experts are present and [K2, N2] when no experts are present.
- expertTokens supports INT64. If not empty, the maximum supported length is 256.
- bias1 supports FLOAT16, FLOAT32, and INT32. The dimension is [E, N1] when experts are present and [N1] when experts are absent.
- bias2 supports FLOAT16, FLOAT32, and INT32. The dimension is [E, N2] when experts are present and [N2] when experts are absent.
- scale supports FLOAT32: For per-tensor, the input is always a one-dimensional vector when experts are present/absent, and the number of input elements is [E]/[1] when experts are present/absent, respectively; for per-channel, the input is a two-dimensional vector/one-dimensional vector when experts are present/absent, and the number of input elements is [E, N1]/[N1] when experts are present/absent, respectively.
- offset supports FLOAT32 and is a one-dimensional vector. The number of input elements is [E]/[1] when experts are present/absent, respectively.
- deqScale1 supports UINT64, INT64, FLOAT32, and BFLOAT16. The input is [E, N1]/[N1] when experts are present/absent, respectively.
- deqScale2 supports UINT64, INT64, FLOAT32, and BFLOAT16. The input is [E, N2] when experts are present and [N2] when experts are absent.
- antiquantScale1 supports FLOAT16 and BFLOAT16. In per-channel mode, the input is [E, N1] when experts are present and [N1] when experts are absent. In per-group mode, the input is [E, G, N1] when experts are present and [G, N1] when experts are absent.
- antiquantScale2 supports FLOAT16 and BFLOAT16. In per-channel mode, the input is [E, N2] when experts are present and [N2] when experts are absent. In per-group mode, the input is [E, G, N2] when experts are present and [G, N2] when experts are absent.
- antiquantOffset1 supports FLOAT16 and BFLOAT16. In per-channel mode, the input is [E, N1] when experts are present and [N1] when experts are absent. In per-group mode, the input is [E, G, N1] when experts are present and [G, N1] when experts are absent.
- antiquantOffset2 supports FLOAT16 and BFLOAT16. In per-channel mode, the input is [E, N2] when experts are present and [N2] when experts are absent. In per-group mode, the input is [E, G, N2] when experts are present and [G, N2] when experts are absent.
- activation supports fastgelu/gelu/relu/silu and geglu/swiglu/reglu.
- innerPrecise takes effect only when all mandatory parameters are FLOAT16 in the non-quantized field. In other use cases, no distinction is made between high precision and high performance.
- y supports FLOAT16 and BFLOAT16. The output dimension is the same as that of x.
Atlas inference products :- x supports FLOAT16, and its dimension is 2D [M, K1].
- weight1 supports FLOAT16 and the dimension is 2D [K1, N1].
- weight2 supports FLOAT16 and the dimension is 2D [K2, N2].
- expertTokens supports only null pointers.
- bias1 supports FLOAT16, and the supported input dimension is 1D [N1].
- bias2 supports FLOAT16, and the supported input dimension is 1D [N2].
- scale, offset, deqScale1, deqScale2, antiquantScale1, antiquantScale2, antiquantOffset1, and antiquantOffset2 support only null pointers.
- activation supports fastgelu/gelu/relu/silu.
- innerPrecise only supports passing 1.
- y supports FLOAT16, and the output dimension is the same as that of x.
Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
The first-phase API validates input parameters. If the following error codes are returned, the causes are:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 Returned if the parameter passed in is a mandatory input, output, or attribute and is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of x, weight1, weight2, activation, expertTokens, bias1, bias2, and y are not within the supported range.
aclnnFFNV2
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Workspace size allocated on the Device, obtained by calling the first-phase API aclnnFFNV2GetWorkspaceSize. executor Input Executor of the op, containing the operator computation flow. stream Input Stream used to execute tasks. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnFFNV2 defaults to a non-deterministic implementation. You can enable deterministic computation through aclrtCtxSetSysParamOpt.
- In all scenarios, K1 = N2, K1 < 65536, K2 < 65536, and the M-axis after 32-byte alignment must be less than the maximum value of INT32.
Atlas A2 products :- With expert, the total number of expert data must be consistent with M of x.
- When the activation layer is geglu/swiglu/reglu, only the FLOAT16 high-performance scenario without expert grouping is supported (FLOAT16 scenario refers to the scenario where all required parameters of the aclTensor type are of the FLOAT16 data type), and N1=2*K2.
- When the activation layer is gelu/fastgelu/relu/silu, the FLOAT16 high-precision and high-performance scenarios, BFLOAT16 scenario, quantization scenario, and pseudo-quantization scenario with or without expert grouping are supported, and N1=K2.
- Quantization parameters and pseudo-quantization parameters cannot be input in the non-quantization scenario, pseudo-quantization parameters cannot be input in the quantization scenario, and quantization parameters cannot be input in the pseudo-quantization scenario.
- Quantization scenario parameter types: x is INT8, weight is INT8, bias is INT32, scale is FLOAT32, offset is FLOAT32. The types of other parameters fall into two cases depending on y:
- When y is FLOAT16, deqScale supports the following data types: UINT64, INT64, FLOAT32.
- y is BFLOAT16, and deqScale supports the following data type: BFLOAT16.
- deqScale1 and deqScale2 must have the same data type.
- In the quantization scenario, the per-channel mode parameter types for scale are: x is INT8, weight is INT8, bias is INT32, scale is FLOAT32, offset is FLOAT32. The types of the remaining parameters fall into two cases depending on y:
- When y is FLOAT16, deqScale supports the following data types: UINT64, INT64.
- y is BFLOAT16, and deqScale supports the following data type: BFLOAT16.
- deqScale1 and deqScale2 must have the same data type.
- The pseudo-quantization scenario supports two different parameter types:
- y is FLOAT16, x is FLOAT16, bias is FLOAT16, antiquantScale is FLOAT16, antiquantOffset is FLOAT16, and weight supports data types INT8 and INT4.
- y is BFLOAT16, x is BFLOAT16, bias is FLOAT32, antiquantScale is BFLOAT16, antiquantOffset is BFLOAT16, and weight supports data types INT8 and INT4.
- When the data type of weight1/weight2 is INT4, the last dimension of its shape must be an even number.
- In the pseudo-quantization scenario, under per-group mode, the group count G in antiquantScale1 and antiquantOffset1 must be divisible by K1, and the group count G in antiquantScale2 and antiquantOffset2 must be divisible by K2.
- In the BFLOAT16 non-quantization scenario, the innerPrecise parameter can only be set to 0. In the FLOAT16 non-quantization scenario, it can be set to 0 or 1. In the quantization or pseudo-quantization scenario, both 0 and 1 can be configured, but the configuration does not take effect.
- When tokensIndexFlag is true and there are experts (expertTokens is not empty), the values in expertTokens must satisfy the following condition: if i and j are both valid array indices in expertTokens and j is greater than i, then the value of the j-th element in expertTokens must be greater than or equal to the value of the i-th element in expertTokens.
Atlas inference products :- Only the without-expert scenario is supported.
- N1=K2 must be satisfied.
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_ffn_v2.h"
#include "aclnn/opdev/fp16_t.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) * aclDataTypeSize(dataType);
// 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 data from the host 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 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 AscendCL external API list.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the check as needed.
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> selfShape = {4, 2};
std::vector<int64_t> outShape = {4, 2};
std::vector<int64_t> weight1Shape = {2, 2};
std::vector<int64_t> weight2Shape = {2, 2};
void* selfDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
void* weight1DeviceAddr = nullptr;
void* weight2DeviceAddr = nullptr;
aclTensor* self = nullptr;
aclTensor* out = nullptr;
aclTensor* weight1 = nullptr;
aclTensor* weight2 = nullptr;
std::vector<op::fp16_t> selfHostData = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};
std::vector<op::fp16_t> outHostData = {0, 0, 0, 0};
std::vector<op::fp16_t> weight1HostData = {0.1, 0.2, 0.3, 0.4};
std::vector<op::fp16_t> weight2HostData = {0.4, 0.3, 0.2, 0.1};
// Create the self aclTensor.
ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT16, &self);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the weight1 aclTensor.
ret = CreateAclTensor(weight1HostData, weight1Shape, &weight1DeviceAddr, aclDataType::ACL_FLOAT16, &weight1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the weight2 aclTensor.
ret = CreateAclTensor(weight2HostData, weight2Shape, &weight2DeviceAddr, aclDataType::ACL_FLOAT16, &weight2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Example of calling the aclnnFFNV2 API
LOG_PRINT("test aclnnFFNV2\n");
// 3. Call the CANN operator library API. Change it to the specific API name.
// Call the first-phase API of aclnnFFNV2.
ret = aclnnFFNV2GetWorkspaceSize(self, weight1, weight2, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "relu", 1, false, out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFFNV2GetWorkspaceSize 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 second-phase API of aclnnFFNV2.
ret = aclnnFFNV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFFNV2 failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for the task execution to end.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value, copy the result from device memory to host memory, and modify it according to the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<op::fp16_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++) {
std::cout << "index: " << i << ": " << static_cast<float>(resultData[i]) << std::endl;
}
// 6. Release aclTensor, and modify it according to the specific API definition.
aclDestroyTensor(self);
aclDestroyTensor(out);
aclDestroyTensor(weight1);
aclDestroyTensor(weight2);
// 7. Release device resources.
aclrtFree(selfDeviceAddr);
aclrtFree(outDeviceAddr);
aclrtFree(weight1DeviceAddr);
aclrtFree(weight2DeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}