aclnnAddLayerNormGrad
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Supported
Atlas training products : Not supported
Function
Description: LayerNorm is a normalization method that normalizes the input data of a network layer to a distribution with a mean of 0 and a variance of 1. LayerNormGrad is a key operator in the backward propagation phase of deep learning, mainly used to compute the gradient of the LayerNorm operation. AddLayerNormGrad fuses Add and LayerNormGrad to reduce copy-in and copy-out operations.
Formula:
Forward formula: (D is the size of the reduction axis)
Backward formula:
Where:
:
:
:
Where when i=j, and when i!=j.
:
Where D is the number of elements in x that participate in the mean calculation.
:
The simplified :
Function Prototype
Each operator uses a two-phase API. First call "aclnnAddLayerNormGradGetWorkspaceSize" to obtain the workspace size required for the computation and the executor containing the operator computation flow. Then call "aclnnAddLayerNormGrad" to perform the computation.
aclnnStatus aclnnAddLayerNormGradGetWorkspaceSize(
const aclTensor *dy,
const aclTensor *x1,
const aclTensor *x2,
const aclTensor *rstd,
const aclTensor *mean,
const aclTensor *gamma,
const aclTensor *dsumOptional,
const aclTensor *dxOut,
const aclTensor *dgammaOut,
const aclTensor *dbetaOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnAddLayerNormGrad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnAddLayerNormGradGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor dy (aclTensor*) Input Indicates the primary grad input. Corresponds to `inputdy` in the formula. - Does not support null tensors.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √ x1 (aclTensor*) Input Indicates the input x1 of the forward fusion operator. Corresponds to `inputx1` in the formula. - Does not support null tensors.
- The shape and data type remain consistent with those of `dy`.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √ x2(aclTensor*) Input Input x2 of the forward fusion operator. Corresponds to `inputx2` in the corresponding formula. - Does not support null tensors.
- The shape and data type remain consistent with those of `dy`.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √ rstd (aclTensor*) Input Indicates the reciprocal of the standard deviation of the sum of the forward inputs x1 and x2. Corresponds to `rstd` in the formula. - Does not support null tensors.
- The shape must satisfy the broadcast relationship with `dy` (the leading dimensions are the same as the leading dimensions of `dy`; the leading dimensions refer to the dimension of `dy` minus the dimension of `gamma`, indicating the dimensions that do not require normalization).
FLOAT32 ND 1-8 √ mean (aclTensor*) Input Indicates the mean of the sum of forward inputs x1 and x2. Corresponds to `E(x)` in the formula. - Does not support null Tensor.
- The shape must meet the broadcast relationship with `dy` (the dimensions of the leading dimensions are the same as those of the leading dimensions of `dy`, where the leading dimensions refer to the dimension of `dy` minus the dimension of `gamma`, indicating the dimensions that do not need norm).
FLOAT32 ND 1-8 √ gamma (aclTensor*) Input Indicates forward input gamma. Corresponds to `gamma` in the corresponding formula. - Does not support null tensors.
- Data type must remain consistent with the data type of `dy`.
- The shape dimension is the same as the dimension of `dy` to be normalized.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √ dsumOptional (aclTensor*) Input Optional input. Indicates an additional backward gradient accumulation input. Corresponds to `dsumOptional` in the corresponding formula. - Does not support null Tensor.
- The shape and data type must remain consistent with those of `dy`.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √ dxOut (aclTensor*) Output Indicates the gradient of the Add result output `x`. Corresponds to `dxOut` in the formula. - Does not support null Tensor.
- The shape and data type must remain consistent with those of `dy`.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √ dgammaOut (aclTensor*) Output Represents the gradient of the input parameter gamma. It corresponds to `dgammaOut` in the corresponding formula. - Does not support null tensor.
- The shape must be the same as that of the input `gamma`.
FLOAT32 ND 1-8 √ dbetaOut (aclTensor*) Output Indicates the backward gradient of forward input parameter beta. Corresponds to `dbetaOut` in the formula. - Does not support null Tensor.
- The shape remains consistent with input `gamma`.
FLOAT32 ND 1-8 √ workspaceSize (uint64_t*) Output Returns the Device-allocated workspace size. - - - - - executor(aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - Atlas inference products : The data types of parametersdy,x1,x2,gamma,dsumOptional, anddxOutdo not support BFLOAT16.
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 If a required input, output, or attribute is a null pointer, 161001 is returned. ACLNN_ERR_PARAM_INVALID 161002 The data type of a required input or output is not within the supported range.
aclnnAddLayerNormGrad
Parameters
Parameter Input/Output Description workspace Input Device-allocated workspace memory address. workspaceSize Input Size of the Device-allocated workspace, obtained by the first-phase API aclnnAddLayerNormGradGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
Functional Dimensions
Supported data types
Atlas inference products : dy, x1, x2, gamma, dsumOptional, and dxOut support FLOAT32 and FLOAT16.
Atlas A2 products andAtlas A3 products : dy, x1, x2, gamma, dsumOptional, and dxOut support FLOAT32, FLOAT16, and BFLOAT16.
- rstd, mean, dgammaOut, and dbetaOut support: FLOAT32.
Data format support: ND.
Unsupported Type Description
DOUBLE: The instruction does not support DOUBLE.
Boundary Value Scenario Description
- When the input is Inf, the output is Inf.
- When the input is NaN, the output is NaN.
Deterministic computation:
- aclnnAddLayerNormGrad defaults to a non-deterministic implementation. Deterministic computation can be enabled by calling aclrtCtxSetSysParamOpt.
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_add_layer_norm_grad.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 allocate 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 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 aclCreateTensor 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) Device/stream initialization. For details, see the acl API manual.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle 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. Custom construction is required based on the API definition.
std::vector<int64_t> dyShape = {3, 1, 4};
std::vector<int64_t> x1Shape = {3, 1, 4};
std::vector<int64_t> x2Shape = {3, 1, 4};
std::vector<int64_t> rstdShape = {3, 1, 1};
std::vector<int64_t> meanShape = {3, 1, 1};
std::vector<int64_t> gammaShape = {4};
std::vector<int64_t> dsumOptionalShape = {3, 1, 4};
std::vector<int64_t> outputpdxShape = {3, 1, 4};
std::vector<int64_t> outputpdgammaShape = {4};
std::vector<int64_t> outputpdbetaShape = {4};
void* dyDeviceAddr = nullptr;
void* x1DeviceAddr = nullptr;
void* x2DeviceAddr = nullptr;
void* rstdDeviceAddr = nullptr;
void* meanDeviceAddr = nullptr;
void* gammaDeviceAddr = nullptr;
void* dsumOptionalDeviceAddr = nullptr;
void* outputpdxDeviceAddr = nullptr;
void* outputpdgammaDeviceAddr = nullptr;
void* outputpdbetaDeviceAddr = nullptr;
aclTensor* dy = nullptr;
aclTensor* x1 = nullptr;
aclTensor* x2 = nullptr;
aclTensor* rstd = nullptr;
aclTensor* mean = nullptr;
aclTensor* gamma = nullptr;
aclTensor* dsumOptional = nullptr;
aclTensor* outputpdx = nullptr;
aclTensor* outputpdgamma = nullptr;
aclTensor* outputpdbeta = nullptr;
std::vector<float> dyHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
std::vector<int32_t> x1HostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
std::vector<int32_t> x2HostData = {2, 2, 2, 4, 4, 4, 6, 6, 6, 8, 8, 8};
std::vector<int32_t> rstdHostData = {0, 1, 2};
std::vector<int32_t> meanHostData = {0, 1, 2};
std::vector<int32_t> gammaHostData = {0, 1, 2, 3};
std::vector<int32_t> dsumOptionalHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
std::vector<int32_t> outputpdxHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
std::vector<int32_t> outputpdgammaHostData = {0, 1, 2, 3};
std::vector<int32_t> outputpdbetaHostData = {0, 1, 2, 3};
// Create the self aclTensor.
ret = CreateAclTensor(dyHostData, dyShape, &dyDeviceAddr, aclDataType::ACL_FLOAT, &dy);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT, &x1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT, &x2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(rstdHostData, rstdShape, &rstdDeviceAddr, aclDataType::ACL_FLOAT, &rstd);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(meanHostData, meanShape, &meanDeviceAddr, aclDataType::ACL_FLOAT, &mean);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT, &gamma);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(
dsumOptionalHostData, dsumOptionalShape, &dsumOptionalDeviceAddr, aclDataType::ACL_FLOAT, &dsumOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(outputpdxHostData, outputpdxShape, &outputpdxDeviceAddr, aclDataType::ACL_FLOAT, &outputpdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(
outputpdgammaHostData, outputpdgammaShape, &outputpdgammaDeviceAddr, aclDataType::ACL_FLOAT, &outputpdgamma);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(
outputpdbetaHostData, outputpdbetaShape, &outputpdbetaDeviceAddr, aclDataType::ACL_FLOAT, &outputpdbeta);
CHECK_RET(ret == ACL_SUCCESS, return ret);
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// aclnnAddLayerNormGrad API call example.
// 3. Call the CANN operator library API. Replace it with the specific API name.
// Call the first-phase API of aclnnAddLayerNormGrad.
LOG_PRINT("\nUse aclnnAddLayerNormGrad Port.");
ret = aclnnAddLayerNormGradGetWorkspaceSize(
dy, x1, x2, rstd, mean, gamma, dsumOptional, outputpdx, outputpdgamma, outputpdbeta, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAddLayerNormGradGetWorkspaceSize 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 aclnnAddLayerNormGrad.
ret = aclnnAddLayerNormGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAddLayerNormGrad 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 it based on the specific API definition.
auto outputpdxsize = GetShapeSize(outputpdxShape);
std::vector<float> resultDataPdx(outputpdxsize, 0);
ret = aclrtMemcpy(
resultDataPdx.data(), resultDataPdx.size() * sizeof(resultDataPdx[0]), outputpdxDeviceAddr,
outputpdxsize * sizeof(resultDataPdx[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("== pdx output");
for (int64_t i = 0; i < outputpdxsize; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultDataPdx[i]);
}
auto outputpdgammasize = GetShapeSize(outputpdgammaShape);
std::vector<float> resultDataPdGamma(outputpdgammasize, 0);
ret = aclrtMemcpy(
resultDataPdGamma.data(), resultDataPdGamma.size() * sizeof(resultDataPdGamma[0]), outputpdgammaDeviceAddr,
outputpdgammasize * sizeof(resultDataPdGamma[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("== pdgamma output");
for (int64_t i = 0; i < outputpdgammasize; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultDataPdGamma[i]);
}
auto outputpdbetasize = GetShapeSize(outputpdbetaShape);
std::vector<float> resultDataPdBeta(outputpdbetasize, 0);
ret = aclrtMemcpy(
resultDataPdBeta.data(), resultDataPdBeta.size() * sizeof(resultDataPdBeta[0]), outputpdbetaDeviceAddr,
outputpdbetasize * sizeof(resultDataPdBeta[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("== pdbeta output");
for (int64_t i = 0; i < outputpdbetasize; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultDataPdBeta[i]);
}
// 6. Release the aclTensor and aclScalar. Modify it based on the specific API definition.
aclDestroyTensor(dy);
aclDestroyTensor(x1);
aclDestroyTensor(x2);
aclDestroyTensor(rstd);
aclDestroyTensor(mean);
aclDestroyTensor(gamma);
aclDestroyTensor(dsumOptional);
aclDestroyTensor(outputpdx);
aclDestroyTensor(outputpdgamma);
aclDestroyTensor(outputpdbeta);
// 7. Release device resources. Modify as required by the specific API definition.
aclrtFree(dyDeviceAddr);
aclrtFree(x1DeviceAddr);
aclrtFree(x2DeviceAddr);
aclrtFree(rstdDeviceAddr);
aclrtFree(meanDeviceAddr);
aclrtFree(gammaDeviceAddr);
aclrtFree(dsumOptionalDeviceAddr);
aclrtFree(outputpdxDeviceAddr);
aclrtFree(outputpdgammaDeviceAddr);
aclrtFree(outputpdbetaDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}