aclnnGroupNormBackward
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 : Not supported
Atlas training products : Supported
Function
- Description: Backward computation of aclnnGroupNorm. Computes the gradients of the input tensor to update model parameters during backward propagation.
- Formula:
Function Prototype
Each operator uses a two-phase API. First call the "aclnnGroupNormBackwardGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnGroupNormBackward" API to execute the computation.
aclnnStatus aclnnGroupNormBackwardGetWorkspaceSize(
const aclTensor* gradOut,
const aclTensor* input,
const aclTensor* mean,
const aclTensor* rstd,
const aclTensor* gamma,
int64_t N,
int64_t C,
int64_t HxW,
int64_t group,
const aclBoolArray* outputMask,
aclTensor* gradInput,
aclTensor* gradGammaOut,
aclTensor* gradBetaOut,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnGroupNormBackward(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnGroupNormBackwardGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor gradOut(aclTensor*) Input Represents the gradient tensor of backward computation, corresponding to `gradOut` in the formula. - Supports null tensors.
- The data type is the same as `input`.
- The number of elements must equal N*C*HxW.
FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √ input (aclTensor*) Input Represents the first input of forward computation, corresponding to `x` in the formula. - Supports null tensor.
- The data type is the same as `gradOut`.
- The number of elements must equal N*C*HxW.
FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √ mean (aclTensor*) Input Represents the second output of the forward computation, which is the mean of each group after the input is grouped. Corresponds to `mean` in the formula. - Supports null tensor.
- The number of elements must equal N*group.
FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √ rstd (aclTensor*) Input Third output of the forward computation. Represents the reciprocal of the standard deviation of each group after input is grouped, corresponding to `rstd` in the formula. - Supports null tensors.
- The data type is the same as that of `mean`.
- The number of elements must equal N*group.
FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √ gamma (aclTensor*) Input Represents the scaling factor for each channel, corresponding to `gamma` in the formula. - Supports null tensors.
- The data type is the same as `mean`.
- The number of elements must be the same as `C`.
FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √ N (int64_t) Input Indicates the space size of the input `gradOut` on the N dimension. - - - - - C (int64_t) Input Indicates the space size of the input `gradOut` on the C dimension. - The value of C is less than or equal to 240000.
- C must be divisible by group, and C/group ≤ 8000.
- - - - HxW(int64_t) Input Represents the space size of input `gradOut` excluding the N and C dimensions. - - - - - group (int64_t) Input Indicates that the C dimension of input `gradOut` is divided into group groups. - The value of group must be greater than 0.
- - - - outputMask (aclBoolArray*) Input Output mask, indicating whether to output `gradInput`, `gradGammaOut`, and `gradBetaOut`. - size is 3. The elements indicate whether to output `gradInput`, `gradGammaOut`, and `gradBetaOut` respectively. If true, the output is returned; otherwise, null is returned at the corresponding position.
BoolArray - - - gradInput (aclTensor*) Output Represents the computed output gradient, used to update the gradient of the input data. The corresponding formula term is `gradInput`. - Supports null Tensor.
- The data type is the same as `gradOut`.
- The shape is the same as `input`.
FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √ gradGammaOut (aclTensor*) Output Represents the computed output gradient, used to update the gradient of the scale parameter. The corresponding formula term is `gradGammaOut`. - Supports null tensor.
- Same data type as `mean`.
- Same shape as `gamma`.
FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √ gradBetaOut (aclTensor*) Output Indicates the gradient of the computed output, used to update the gradient of the bias parameter. Corresponds to `gradBetaOut` in the corresponding formula. - Supports null tensor.
- Same data type as `mean`.
- Same shape as `gamma`.
FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √ workspaceSize (uint64_t*) Output Returns the workspace size that the user needs to allocate on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - - Atlas training products :- The
gradOut,input,mean,rstd,gamma,gradInput,gradGammaOut, andgradBetaOutparameters do not support the BFLOAT16 data type. - The data types of the
meanandgradOutparameters are the same.
- The
Atlas A2 products ,Atlas A3 products :The data types of the
meanandgradOutparameters are the same.
Ascend 950PR&950DT products :The supported data type correspondence between
meanandgradOutis as follows:
| Input Parameters | gradOut | Mean | |--|--|--| |Data type | FLOAT32 | FLOAT32 | |Data type | FLOAT16 | FLOAT16 | |Data type | FLOAT16 | FLOAT32 | |Data type | BFLOAT16 | BFLOAT16 | |Data type | BFLOAT16 | FLOAT32 |
Return Value
aclnnStatus: return status code. For details, see aclnn Return 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 Returned when gradOut, input, mean, or rstd is a null pointer. When outputMask[0] is true and the passed-in gradInput is a null pointer. When outputMask[1] is true and the passed-in gradGammaOut is a null pointer. When outputMask[2] is true and the passed-in gradBetaOut is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of gradOut is out of the supported range. The data types of input, mean, gamma, rstd, and gradOut do not meet the constraints described in Parameters. The length of outputMask is not 3. When outputMask[0] is true, the shape of gradInput is not the same as that of input. When outputMask[1] is true, the shape of gradGammaOut is not the same as that of gamma. When outputMask[2] is true, the shape of gradBetaOut is not the same as the shape of gamma. group is not greater than 0, or C is greater than 240000. C is not divisible by group, or C/group > 8000. The number of elements in input is not equal to N*C*HxW. The number of elements in mean is not equal to N*group. The number of elements in rstd is not equal to N*group. gamma is not a null pointer and the number of elements in gamma is not C.
aclnnGroupNormBackward
Parameters
Parameter Input/Output Description workspace Input Memory address of the workspace requested on the device. workspaceSize Input Size of the workspace requested on the device, obtained by the first-phase API aclnnGroupNormBackwardGetWorkspaceSize. executor Input Op executor, containing the operator computation process. stream Input Specifies the stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
Atlas A3 products ,Atlas A2 products ,Atlas training products : aclnnGroupNormBackward defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
Ascend 950PR&950DT products : aclnnGroupNormBackward defaults to a deterministic implementation.
Example
The 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_group_norm_backward.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 shape_size = 1;
for (auto i : shape) {
shape_size *= i;
}
return shape_size;
}
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); aclFinalize(); return ret);
ret = aclrtCreateStream(stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
aclrtResetDevice(deviceId); aclFinalize(); 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 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);
// 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) Initialize device/stream. 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 the check as needed.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the inputs and outputs. Customize the construction according to the API.
std::vector<int64_t> gradOutShape = {2, 3, 4};
std::vector<int64_t> inputShape = {2, 3, 4};
std::vector<int64_t> meanShape = {2, 1};
std::vector<int64_t> rstdShape = {2, 1};
std::vector<int64_t> gammaShape = {3};
std::vector<int64_t> gradInputShape = {2, 3, 4};
std::vector<int64_t> gradGammaOutShape = {3};
std::vector<int64_t> gradBetaOutShape = {3};
void* gradOutDeviceAddr = nullptr;
void* inputDeviceAddr = nullptr;
void* meanDeviceAddr = nullptr;
void* rstdDeviceAddr = nullptr;
void* gammaDeviceAddr = nullptr;
void* gradInputDeviceAddr = nullptr;
void* gradGammaOutDeviceAddr = nullptr;
void* gradBetaOutDeviceAddr = nullptr;
aclTensor* gradOut = nullptr;
aclTensor* input = nullptr;
aclTensor* mean = nullptr;
aclTensor* rstd = nullptr;
aclTensor* gamma = nullptr;
aclTensor* gradInput = nullptr;
aclTensor* gradGammaOut = nullptr;
aclTensor* gradBetaOut = nullptr;
std::vector<float> gradOutHostData = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0};
std::vector<float> inputHostData = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0};
std::vector<float> meanHostData = {6.5, 18.5};
std::vector<float> rstdHostData = {0.2896827, 0.2896827};
std::vector<float> gammaHostData = {1.0, 1.0, 1.0};
std::vector<float> gradInputHostData = {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> gradGammaOutHostData = {0.0, 0.0, 0.0};
std::vector<float> gradBetaOutHostData = {0.0, 0.0, 0.0};
int64_t N = 2;
int64_t C = 3;
int64_t HxW = 4;
int64_t group = 1;
std::array<bool, 3> outputMaskData = {true, true, true};
// Create gradOut aclTensor.
ret = CreateAclTensor(gradOutHostData, gradOutShape, &gradOutDeviceAddr, aclDataType::ACL_FLOAT, &gradOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create input aclTensor.
ret = CreateAclTensor(inputHostData, inputShape, &inputDeviceAddr, aclDataType::ACL_FLOAT, &input);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create mean aclTensor.
ret = CreateAclTensor(meanHostData, meanShape, &meanDeviceAddr, aclDataType::ACL_FLOAT, &mean);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create rstd aclTensor.
ret = CreateAclTensor(rstdHostData, rstdShape, &rstdDeviceAddr, aclDataType::ACL_FLOAT, &rstd);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create gamma aclTensor.
ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT, &gamma);
CHECK_RET(ret == ACL_SUCCESS, return ret);
auto outputMask = aclCreateBoolArray(outputMaskData.data(), outputMaskData.size());
CHECK_RET(outputMask != nullptr, return ACL_ERROR_INTERNAL_ERROR);
// Create gradInput aclTensor.
ret = CreateAclTensor(gradInputHostData, gradInputShape, &gradInputDeviceAddr, aclDataType::ACL_FLOAT, &gradInput);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create gradGammaOut aclTensor.
ret = CreateAclTensor(
gradGammaOutHostData, gradGammaOutShape, &gradGammaOutDeviceAddr, aclDataType::ACL_FLOAT, &gradGammaOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create gradBetaOut aclTensor.
ret = CreateAclTensor(
gradBetaOutHostData, gradBetaOutShape, &gradBetaOutDeviceAddr, aclDataType::ACL_FLOAT, &gradBetaOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the specific HostApi.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnGroupNormBackward.
ret = aclnnGroupNormBackwardGetWorkspaceSize(
gradOut, input, mean, rstd, gamma, N, C, HxW, group, outputMask, gradInput, gradGammaOut, gradBetaOut,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupNormBackwardGetWorkspaceSize 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 aclnnGroupNormBackward.
ret = aclnnGroupNormBackward(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupNormBackward failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Wait synchronously for the task 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 size = GetShapeSize(gradInputShape);
std::vector<float> gradInputResultData(size, 0);
ret = aclrtMemcpy(
gradInputResultData.data(), gradInputResultData.size() * sizeof(gradInputResultData[0]), gradInputDeviceAddr,
size * sizeof(float), 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("gradInputResultData[%ld] is: %f\n", i, gradInputResultData[i]);
}
size = GetShapeSize(gradGammaOutShape);
std::vector<float> gradGammaOutResultData(size, 0);
ret = aclrtMemcpy(
gradGammaOutResultData.data(), gradGammaOutResultData.size() * sizeof(gradGammaOutResultData[0]),
gradGammaOutDeviceAddr, size * sizeof(float), 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("gradGammaOutResultData[%ld] is: %f\n", i, gradGammaOutResultData[i]);
}
size = GetShapeSize(gradBetaOutShape);
std::vector<float> gradBetaOutResultData(size, 0);
ret = aclrtMemcpy(
gradBetaOutResultData.data(), gradBetaOutResultData.size() * sizeof(gradBetaOutResultData[0]),
gradBetaOutDeviceAddr, size * sizeof(float), 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("gradBetaOutResultData[%ld] is: %f\n", i, gradBetaOutResultData[i]);
}
// 6. Release aclTensor and aclScalar. Modify it based on the specific API definition.
aclDestroyTensor(gradOut);
aclDestroyTensor(input);
aclDestroyTensor(mean);
aclDestroyTensor(rstd);
aclDestroyTensor(gamma);
aclDestroyTensor(gradInput);
aclDestroyTensor(gradGammaOut);
aclDestroyTensor(gradBetaOut);
// 7. Release device resources. Modify it based on the specific API definition.
aclrtFree(gradOutDeviceAddr);
aclrtFree(inputDeviceAddr);
aclrtFree(meanDeviceAddr);
aclrtFree(rstdDeviceAddr);
aclrtFree(gammaDeviceAddr);
aclrtFree(gradInputDeviceAddr);
aclrtFree(gradGammaOutDeviceAddr);
aclrtFree(gradBetaOutDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}