aclnnAddLayerNormGrad
Applicable Products
| Product | Supported |
|---|---|
| √ | |
| √ | |
| √ | |
| × | |
| √ | |
| × |
Function
Description: LayerNorm is a normalization method that normalizes the input data of a network layer to the range [0, 1]. The LayerNormGrad operator is a key operator used in the backward propagation phase of deep learning, primarily for computing the gradient of the LayerNorm operation. The AddLayerNormGrad operator fuses Add and LayerNormGrad to reduce data movement in and out.
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 is divided into a two-phase API. The "aclnnAddLayerNormGradGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnAddLayerNormGrad" API is called 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
Atlas inference products : The data type of parametersdy,x1,x2,gamma,dsumOptional, anddxOutdoes not support BFLOAT16.
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 Returns 161001 if a required input, output, or required attribute is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of a required input or required output is not within the supported range.
aclnnAddLayerNormGrad
Parameters
Parameter Input/Output Description workspace Input The workspace memory address applied for on the Device side. workspaceSize Input The workspace size applied for on the Device side, obtained from the first-phase API aclnnAddLayerNormGradGetWorkspaceSize. executor Input Operator executor, which contains the operator computation process. stream Input Specifies the stream for task execution. Return Value
aclnnStatus: return code. For details, see aclnn Return Code.
Constraints
Functional Dimensions
Data Type Support
Atlas inference products : dy, x1, x2, gamma, dsumOptional, and dxOut support FLOAT32 and FLOAT16.Atlas A2 training products/Atlas A2 inference products andAtlas A3 training products/Atlas A3 inference 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 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_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: initialize resources.
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 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 data to 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);
// Compute strides for 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 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) Initialize device/stream. See the ACL API documentation.
// Fill in the deviceId based on your actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the check based on your needs.
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the inputs and outputs. Customize the construction based on the API interface.
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;
// Example of calling the aclnnAddLayerNormGrad API.
// 3. Call the CANN operator library API. Replace with the specific API name.
// Call the aclnnAddLayerNormGrad first-phase API.
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);
// Apply for 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 aclnnAddLayerNormGrad second-phase API.
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 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 the device memory to the host. Modify 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 aclTensor and aclScalar. Modify 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 based on 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;
}