aclnnSwigluBackwardGroupQuantWithDualAxis
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: A fused operator that performs SwiGLU backward computation with optional clamp and weight, applies dynamic MX quantization using the CuBLAS algorithm to grad_x along axis -1 and axis -2 respectively, and outputs FP8 results and E8M0 scaling factors.
Backward computation formula:
Split x along the last dimension into a and b:
When clampLimit > 0:
When clampLimit=-1, and . Let:
If weight is not passed in, ; if weight is passed in, . The backward results are:
where , . If Clamp is disabled, both masks are 1. The final result is:
gradWeight computation formula (computed only when both weight and yOrigin are provided):
Dual-axis dynamic MX quantization:
Take 32 elements as one MX quantization block, and compute the power-of-two scaling factor corresponding to the maximum absolute value within the block:
When dstType=36, use the fp8_max corresponding to FLOAT8_E4M3FN and convert to this format; when dstType=35, use the fp8_max corresponding to FLOAT8_E5M2 and convert to this format.
- The -1 axis quantization result consists of y1Out and scale1Out.
- The -2 axis quantization result consists of y2Out and scale2Out.
- The data types of both scale1Out and scale2Out are FLOAT8_E8M0.
In the group use case, groupIndexOptional uses the cumsum mode. Let its elements be , which must satisfy:
Group g covers the row interval , where . groupIndexOptional is used only for the -2 axis quantization group boundaries and does not change any of the T rows in the SwiGLU backward computation.
In the group use case, the shape of scale2Out is [floor(T/64)+G, 2H, 2]. The additional grouped rows are used to implement the group boundary offset layout, not ordinary invalid padding; the same group layout must be followed when reading scale2Out.
Function Prototype
Each operator uses a two-phase API. First call the aclnnSwigluBackwardGroupQuantWithDualAxisGetWorkspaceSize API to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the aclnnSwigluBackwardGroupQuantWithDualAxis API to perform the computation.
aclnnStatus aclnnSwigluBackwardGroupQuantWithDualAxisGetWorkspaceSize(
const aclTensor *gradY,
const aclTensor *x,
const aclTensor *weightOptional,
const aclTensor *yOriginOptional,
const aclTensor *groupIndexOptional,
double clampLimit,
double alpha,
double bias,
int64_t quantMode,
int64_t dstType,
const aclTensor *y1Out,
const aclTensor *scale1Out,
const aclTensor *y2Out,
const aclTensor *scale2Out,
const aclTensor *gradWeightOutOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSwigluBackwardGroupQuantWithDualAxis(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSwigluBackwardGroupQuantWithDualAxisGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor gradY (aclTensor*) Input Backward gradient of the SwiGLU output. - The shape is [T, H].
- The data type must be the same as that of x.
- Empty tensors are not supported.
FLOAT16, BFLOAT16 ND 2 √ x (aclTensor*) Input Forward input of SwiGLU. - The shape is [T, 2H].
- The last dimension must be a multiple of 64.
- The data type must be FLOAT16 or BFLOAT16.
FLOAT16, BFLOAT16 ND 2 √ weightOptional (aclTensor*) Input (optional) Weight of each token. - The shape is [T].
- Supported only in the group use case.
- When weight is passed in, yOrigin must also be passed in.
FLOAT16, BFLOAT16, FLOAT ND 1 √ yOriginOptional (aclTensor*) Input (optional) Raw value of the SwiGLU forward output, used for computing gradWeight. - The shape is [T, H] and must be the same as that of gradY.
- The data type must be the same as that of x.
- Must be passed in pairs with weight.
FLOAT16, BFLOAT16 ND 2 √ groupIndexOptional(aclTensor*) Input (optional) Group quantization boundary. - shape is [G], and dtype is INT64.
- Uses the cumsum mode. Values must be strictly increasing, and the last value must be T.
- A null pointer indicates a non-group use case.
INT64 ND 1 √ clampLimit(double) Input Clamp backward propagation threshold. - Value: -1.0 or greater than 0.
- -1.0 indicates that Clamp is disabled.
DOUBLE - - - alpha (double) Input Alpha coefficient of the SwiGLU variant. alpha coefficient, which must be greater than 0. DOUBLE - - - bias (double) Input bias coefficient of the SwiGLU variant. bias coefficient. DOUBLE - - - quantMode (int64_t) Input Quantization mode. Currently, only 1 is supported, indicating dual-axis MX quantization. INT64 - - - dstType (int64_t) Input FP8 output type. 35 indicates FLOAT8_E5M2, and 36 indicates FLOAT8_E4M3FN. INT64 - - - y1Out (aclTensor*) Output -1 axis quantization result. Same shape as x. The data type is determined by dstType. FLOAT8_E4M3FN, FLOAT8_E5M2 ND 2 √ scale1Out(aclTensor*) Output -1 axis MX scaling factor. The shape is [T, ceil(2H/64), 2], and the dtype is FLOAT8_E8M0. FLOAT8_E8M0 ND 3 √ y2Out (aclTensor*) Output -2-axis quantization result. The shape is the same as x, and the data type is determined by dstType. FLOAT8_E4M3FN, FLOAT8_E5M2 ND 2 √ scale2Out (aclTensor*) Output MX scaling factor for the -2 axis. - Non-group: shape is [ceil(T/64), 2H, 2].
- group: shape is [floor(T/64)+G, 2H, 2], with the extra rows used for the group offset layout.
- dtype is FLOAT8_E8M0.
FLOAT8_E8M0 ND 3 √ gradWeightOutOptional (aclTensor*) Output (optional) Gradient of weight. - Output only when both weight and yOrigin are passed in.
- Shape is [T], and the data type is the same as that of weight.
FLOAT16, BFLOAT16, FLOAT ND 1 √ workspaceSize (uint64_t*) Output Returns the size of the Device-side workspace required for operator execution, in bytes. - - - - - executor (aclOpExecutor**) Output Returns the executor containing the operator execution flow, for use with the second-phase API. - - - - - Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
The first-phase API performs input parameter validation. Errors include:
Error Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 A required input, output, or workspace/executor pointer is null. ACLNN_ERR_PARAM_INVALID 161002 The input or output data type, data format, shape, or attribute value does not meet the constraints. ACLNN_ERR_RUNTIME_ERROR 361001 The current platform is not within the operator support scope.
aclnnSwigluBackwardGroupQuantWithDualAxis
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size on the device, in bytes. Set this parameter to the value returned by the first-phase API aclnnSwigluBackwardGroupQuantWithDualAxisGetWorkspaceSize. executor Input Operator executor returned by the first-phase API. stream Input Stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Defaults to a deterministic implementation.
- Batch consistency is not supported.
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_swiglu_backward_group_quant_with_dual_axis.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;
}
template <typename T>
int CreateAclTensorWithValue(const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
aclTensor** tensor, T value)
{
int64_t shapeSize = GetShapeSize(shape);
std::vector<T> hostData(shapeSize, value);
return CreateAclTensor(hostData, shape, deviceAddr, dataType, tensor);
}
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);
std::vector<int64_t> gradYShape = {128, 64};
std::vector<int64_t> xShape = {128, 128};
std::vector<int64_t> weightShape = {128};
std::vector<int64_t> groupIndexShape = {2};
std::vector<int64_t> y1Shape = {128, 128};
std::vector<int64_t> scale1Shape = {128, 2, 2};
std::vector<int64_t> scale2Shape = {4, 128, 2};
void* gradYDeviceAddr = nullptr;
void* xDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* yOriginDeviceAddr = nullptr;
void* groupIndexDeviceAddr = nullptr;
void* y1DeviceAddr = nullptr;
void* scale1DeviceAddr = nullptr;
void* y2DeviceAddr = nullptr;
void* scale2DeviceAddr = nullptr;
void* gradWeightDeviceAddr = nullptr;
aclTensor* gradYTensor = nullptr;
aclTensor* xTensor = nullptr;
aclTensor* weightTensor = nullptr;
aclTensor* yOriginTensor = nullptr;
aclTensor* groupIndexTensor = nullptr;
aclTensor* y1Tensor = nullptr;
aclTensor* scale1Tensor = nullptr;
aclTensor* y2Tensor = nullptr;
aclTensor* scale2Tensor = nullptr;
aclTensor* gradWeightTensor = nullptr;
int64_t gradYSize = GetShapeSize(gradYShape);
std::vector<aclFloat16> gradYHostData(gradYSize, aclFloatToFloat16(0.0f));
for (int64_t i = 0; i < gradYSize; i++) {
gradYHostData[i] = aclFloatToFloat16(static_cast<float>(i % 10) * 0.1f);
}
int64_t xSize = GetShapeSize(xShape);
std::vector<aclFloat16> xHostData(xSize, aclFloatToFloat16(0.0f));
for (int64_t i = 0; i < xSize; i++) {
xHostData[i] = aclFloatToFloat16(static_cast<float>((i % 20) - 10) * 0.5f);
}
int64_t weightSize = GetShapeSize(weightShape);
std::vector<float> weightHostData(weightSize, 0.0f);
for (int64_t i = 0; i < weightSize; i++) {
weightHostData[i] = static_cast<float>((i % 5) + 1) * 0.2f;
}
int64_t yOriginSize = GetShapeSize(gradYShape);
std::vector<aclFloat16> yOriginHostData(yOriginSize, aclFloatToFloat16(0.0f));
for (int64_t i = 0; i < yOriginSize; i++) {
yOriginHostData[i] = aclFloatToFloat16(static_cast<float>((i % 8) + 1) * 0.3f);
}
int64_t groupIndexSize = GetShapeSize(groupIndexShape);
std::vector<int64_t> groupIndexHostData(groupIndexSize, 0);
int64_t groupStride = gradYShape[0] / groupIndexSize;
for (int64_t i = 0; i < groupIndexSize; i++) {
groupIndexHostData[i] = (i + 1) * groupStride;
}
ret = CreateAclTensor(gradYHostData, gradYShape, &gradYDeviceAddr, aclDataType::ACL_FLOAT16, &gradYTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &xTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weightTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(yOriginHostData, gradYShape, &yOriginDeviceAddr, aclDataType::ACL_FLOAT16, &yOriginTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(groupIndexHostData, groupIndexShape, &groupIndexDeviceAddr, aclDataType::ACL_INT64,
&groupIndexTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorWithValue<uint8_t>(y1Shape, &y1DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &y1Tensor, 0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorWithValue<uint8_t>(scale1Shape, &scale1DeviceAddr, aclDataType::ACL_FLOAT8_E8M0,
&scale1Tensor, 0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorWithValue<uint8_t>(y1Shape, &y2DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &y2Tensor, 0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorWithValue<uint8_t>(scale2Shape, &scale2DeviceAddr, aclDataType::ACL_FLOAT8_E8M0,
&scale2Tensor, 0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorWithValue<float>(weightShape, &gradWeightDeviceAddr, aclDataType::ACL_FLOAT,
&gradWeightTensor, 0.0f);
CHECK_RET(ret == ACL_SUCCESS, return ret);
double clampLimit = -1.0f;
double alpha = 1.702f;
double bias = 0.0f;
int64_t quantMode = 1;
int64_t dstType = 36;
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
ret = aclnnSwigluBackwardGroupQuantWithDualAxisGetWorkspaceSize(
gradYTensor, xTensor, weightTensor, yOriginTensor, groupIndexTensor, clampLimit, alpha, bias, quantMode,
dstType, y1Tensor, scale1Tensor, y2Tensor, scale2Tensor, gradWeightTensor, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnSwigluBackwardGroupQuantWithDualAxisGetWorkspaceSize 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 = aclnnSwigluBackwardGroupQuantWithDualAxis(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwigluBackwardGroupQuantWithDualAxis 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 y1ResultSize = GetShapeSize(y1Shape);
std::vector<uint8_t> y1ResultData(y1ResultSize, 0);
ret = aclrtMemcpy(y1ResultData.data(), y1ResultData.size() * sizeof(uint8_t), y1DeviceAddr,
y1ResultSize * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y1 result from device to host failed. ERROR: %d\n", ret);
return ret);
LOG_PRINT("y1 output (first 10 elements):\n");
for (int64_t i = 0; i < 10 && i < y1ResultSize; i++) {
LOG_PRINT("y1[%ld] = %d\n", i, static_cast<int>(y1ResultData[i]));
}
auto scale1ResultSize = GetShapeSize(scale1Shape);
std::vector<uint8_t> scale1ResultData(scale1ResultSize, 0);
ret = aclrtMemcpy(scale1ResultData.data(), scale1ResultData.size() * sizeof(uint8_t), scale1DeviceAddr,
scale1ResultSize * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy scale1 result from device to host failed. ERROR: %d\n", ret);
return ret);
LOG_PRINT("scale1 output (first 10 elements):\n");
for (int64_t i = 0; i < 10 && i < scale1ResultSize; i++) {
LOG_PRINT("scale1[%ld] = %d\n", i, static_cast<int>(scale1ResultData[i]));
}
auto y2ResultSize = GetShapeSize(y1Shape);
std::vector<uint8_t> y2ResultData(y2ResultSize, 0);
ret = aclrtMemcpy(y2ResultData.data(), y2ResultData.size() * sizeof(uint8_t), y2DeviceAddr,
y2ResultSize * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y2 result from device to host failed. ERROR: %d\n", ret);
return ret);
LOG_PRINT("y2 output (first 10 elements):\n");
for (int64_t i = 0; i < 10 && i < y2ResultSize; i++) {
LOG_PRINT("y2[%ld] = %d\n", i, static_cast<int>(y2ResultData[i]));
}
auto scale2ResultSize = GetShapeSize(scale2Shape);
std::vector<uint8_t> scale2ResultData(scale2ResultSize, 0);
ret = aclrtMemcpy(scale2ResultData.data(), scale2ResultData.size() * sizeof(uint8_t), scale2DeviceAddr,
scale2ResultSize * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy scale2 result from device to host failed. ERROR: %d\n", ret);
return ret);
LOG_PRINT("scale2 output (first 10 elements):\n");
for (int64_t i = 0; i < 10 && i < scale2ResultSize; i++) {
LOG_PRINT("scale2[%ld] = %d\n", i, static_cast<int>(scale2ResultData[i]));
}
auto gradWeightResultSize = GetShapeSize(weightShape);
std::vector<float> gradWeightResultData(gradWeightResultSize, 0);
ret = aclrtMemcpy(gradWeightResultData.data(), gradWeightResultData.size() * sizeof(float), gradWeightDeviceAddr,
gradWeightResultSize * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy gradWeight result from device to host failed. ERROR: %d\n", ret);
return ret);
LOG_PRINT("gradWeight output (first 10 elements):\n");
for (int64_t i = 0; i < 10 && i < gradWeightResultSize; i++) {
LOG_PRINT("gradWeight[%ld] = %f\n", i, gradWeightResultData[i]);
}
aclDestroyTensor(gradYTensor);
aclDestroyTensor(xTensor);
aclDestroyTensor(weightTensor);
aclDestroyTensor(yOriginTensor);
aclDestroyTensor(groupIndexTensor);
aclDestroyTensor(y1Tensor);
aclDestroyTensor(scale1Tensor);
aclDestroyTensor(y2Tensor);
aclDestroyTensor(scale2Tensor);
aclDestroyTensor(gradWeightTensor);
aclrtFree(gradYDeviceAddr);
aclrtFree(xDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(yOriginDeviceAddr);
aclrtFree(groupIndexDeviceAddr);
aclrtFree(y1DeviceAddr);
aclrtFree(scale1DeviceAddr);
aclrtFree(y2DeviceAddr);
aclrtFree(scale2DeviceAddr);
aclrtFree(gradWeightDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}