aclnnGridSampler2DBackward
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 propagation of aclnnGridSampler2D. Computes the gradients of tensor input and tensor grid.
Calculation Process:
- Calculate the coordinates mapped onto input based on the (x, y) values stored in grid. These coordinates are related to alignCorners and paddingMode.
- Based on the input interpolationMode, select bilinear, nearest, or bicubic interpolation mode to compute the weight values assigned to the gradient at the points around the coordinate.
- Multiply the gradient value stored in grad by the weight value of the corresponding point to compute the final dx and dgrid results.
Formula:
The dimensions of grad, input, grid, dx, and dgrid are as follows:
Where Ns in grad, input, grid, dx, and dgrid are all the same; Cs in grad, input, and dx are the same; and in input and dx are the same; and in grad, grid, and dgrid are the same; and the last dimension of grid has a size of 2, indicating that the input pixel position information is (x, y). The value ranges of x and y are normalized to [-1, 1], where (-1, 1) represents the top-left corner coordinate and (1, -1) represents the bottom-right corner coordinate.
Coordinate de-normalization: The (x, y) in grid must first be de-normalized to the input pixel coordinates (ix, iy), and the gradient multipliers
gix_multandgiy_multare computed (used for subsequent dgrid computation):alignCorners = true:
alignCorners = false:
Effect of paddingMode on gradient multipliers:
- paddingMode="zeros",
gix_multremains unchanged - paddingMode="border", (grad_clip=0 when the coordinate is outside the boundary, otherwise =1)
- paddingMode="reflection", (grad_refl is the derivative of the reflection coordinate transformation function with respect to the input coordinate, indicating the direction and rate at which the reflected output coordinate changes with the input coordinate. The value is -1, 0, or 1).
- paddingMode="zeros",
Gradient formulas for each interpolation mode:
Bilinear
The coordinates and weights of the four corner points are:
Corner Coordinate Weight nw (northwest) ne (northeast) sw (southwest) se (southeast) Where:
dx (input gradient): Scatter the upstream gradient to the corresponding position of input according to the weight
That is, for each output pixel (h, w), multiply its gradient by the bilinear weight and accumulate it to the four adjacent pixel positions of input (positions out of bounds are not accumulated).
dgrid (grid gradient): Partial derivative with respect to (ix, iy)
where (participates in computation only when the corner point is within the boundary).
Final:
Nearest
dx: Accumulate the upstream gradient directly to the nearest neighbor position
dgrid: Nearest interpolation is not differentiable with respect to coordinates, so dgrid = 0.
Bicubic
dx:
Where:
, , positions out of bounds are handled according to paddingMode.
dgrid:
Where:
,
x_coeffs_gradandy_coeffs_gradare the derivatives of the cubic interpolation coefficients with respect to tx/ty:Final:
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnGridSampler2DBackwardGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the computation process of the operator, and then call the "aclnnGridSampler2DBackward" API to perform the computation.
aclnnStatus aclnnGridSampler2DBackwardGetWorkspaceSize(
const aclTensor* gradOutput,
const aclTensor* input,
const aclTensor* grid,
int64_t interpolationMode,
int64_t paddingMode,
bool alignCorners,
const aclBoolArray* outputMask,
aclTensor* inputGrad,
aclTensor* gridGrad,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnGridSampler2DBackward(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnGridSampler2DBackwardGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor gradOutput (aclTensor*) Input Indicates the output gradient of the previous layer in backward propagation, corresponding to `grad` in the formula description. - Supports empty tensors.
- The data type must be the same as that of `input`.
- Supports a shape of (N, C, Hout, Wout).
BFLOAT16, FLOAT16, FLOAT32, DOUBLE ND 4 √ input (aclTensor*) Input Indicates the input tensor of backward propagation, corresponding to `input` in the formula description. - Supports empty tensors.
- The values of the N and C axes of `input` must be consistent with those of `gradOutput`, and the dimension values of the last two dimensions of `input` cannot be 0.
- Supports the shape (N, C, Hin, Win).
BFLOAT16, FLOAT16, FLOAT32, DOUBLE ND 4 √ grid (aclTensor*) Input Tensor that indicates the positions of sampled pixels, corresponding to `grid` in the formula description. - Supports empty tensors.
- The data type is consistent with that of `input`.
- The values of the N, H, and W axes of `grid` must be consistent with those of `gradOutput`, and the value of the last dimension of `grid` must be 2.
- Supports the shape (N, Hout, Wout, 2).
BFLOAT16, FLOAT16, FLOAT32, DOUBLE ND 4 √ interpolationMode (int64_t) Input Indicates the interpolation mode, corresponding to `interpolationMode` in the formula description. Supports three modes: 0: bilinear (bilinear interpolation), 1: nearest (nearest neighbor interpolation), 2: bicubic (bicubic interpolation). - - - - paddingMode (int64_t) Input Indicates the padding mode, which specifies the value returned when (x, y) exceeds the sampling range of the input feature map. Corresponds to `paddingMode` in the formula description. Supports three modes: 0: zeros, 1: border, and 2: reflection. - - - - alignCorners (bool) Input Indicates the mapping between feature map coordinates and feature values, corresponding to `alignCorners` in the formula description. When set to true, the feature value is located at the pixel center. When set to false, the feature value is located at the corner point of the pixel. - - - - outputMask (aclBoolArray*) Input Mask used to indicate the outputs. outputMask[0] set to true/false indicates whether to obtain the output `inputGrad`; outputMask[1] set to true/false indicates whether to obtain the output `gridGrad`. BOOLARRAY - - - inputGrad (aclTensor*) Output Indicates the output gradient of backward propagation, corresponding to `dx` in the formula description. - Supports empty tensors.
- The data type is the same as the data type of `input`.
- The shape is the same as that of `input`.
BFLOAT16, FLOAT16, FLOAT32, DOUBLE ND 4 √ gridGrad (aclTensor*) Output Indicates the grid gradient, corresponding to `dgrid` in the formula description. - Supports empty tensors.
- The data type is the same as that of `input`.
- The shape is consistent with `grid`.
BFLOAT16, FLOAT16, FLOAT32, DOUBLE ND 4 √ workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - Atlas training products :The data types of parameters
gradOutput,input,grid,inputGrad, andgridGraddo not support BFLOAT16 or DOUBLE.
Return Value
aclnnStatus: Returns the status code. For details, see aclnn return code.
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 gradOutput, input, grid, inputGrad, or gridGrad passed in is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of gradOutput, input, grid, inputGrad, or gridGrad is out of the supported range. The shape dimension value of gradOutput, input, or grid is not 4. The value of interpolationMode or paddingMode is out of the supported range. The first dimension of input is different from the first dimensions of grid and gradOutput. The second dimension of input is different from the second dimension of gradOutput. The second dimension of grid is different from the third dimension of gradOutput. The third dimension of grid is different from the fourth dimension of gradOutput. The last two dimensions of input are 0. The last dimension of grid is not 2. The shape of input is different from the shape of inputGrad, or the shape of grid is different from the shape of gridGrad.
aclnnGridSampler2DBackward
Parameters
Parameter Input/Output Description workspace Input Memory address of the workspace applied on the Device side. workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnGridSampler2DBackwardGetWorkspaceSize. executor Input Op executor that contains the operator computation process. stream Input Stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnGridSampler2DBackward defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt. The deterministic implementation must meet all the following conditions:
- The data types of the input and output are not DOUBLE.
- The C-axis values of the input and output are less than or equal to 2048.
- aclnnGridSampler2DBackward defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt. The deterministic implementation must meet all the following conditions:
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_grid_sampler2d_backward.h"
namespace {
constexpr uint64_t kNum2 = 2U;
}
#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 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 on the host to memory on the device.
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 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 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 device/stream. For details, see the acl API manual.
// Set deviceId according to your actual device.
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);
// 2. Construct the input and output. Customize the construction based on the API.
int64_t interpolationMode = 0;
int64_t paddingMode = 0;
bool alignCorners = false;
aclBoolArray* outputMask = nullptr;
std::vector<int64_t> gradOutputShape = {1, 1, 3, 3};
std::vector<int64_t> inputShape = {1, 1, 5, 8};
std::vector<int64_t> gridShape = {1, 3, 3, 2};
std::vector<int64_t> inputGradShape = {1, 1, 5, 8};
std::vector<int64_t> gridGradShape = {1, 3, 3, 2};
void* gradOutputDeviceAddr = nullptr;
void* inputDeviceAddr = nullptr;
void* gridDeviceAddr = nullptr;
void* inputGradDeviceAddr = nullptr;
void* gridGradDeviceAddr = nullptr;
aclTensor* gradOutput = nullptr;
aclTensor* input = nullptr;
aclTensor* grid = nullptr;
aclTensor* inputGrad = nullptr;
aclTensor* gridGrad = nullptr;
std::vector<float> gradOutputHostData = {1, 1, 1, 1, 1, 1, 1, 1, 1};
std::vector<float> inputHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40};
std::vector<float> gridHostData = {-1, -1, 0, -1, 1, -1, -1, 0, 0, 0, 1, 0, -1, 1, 0, 1, 1, 1};
std::vector<float> inputGradHostData = {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> gridGradHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
bool maskValue[2] = {true, true};
outputMask = aclCreateBoolArray(&(maskValue[0]), kNum2);
// Create the gradOutput aclTensor.
ret = CreateAclTensor(gradOutputHostData, gradOutputShape, &gradOutputDeviceAddr, aclDataType::ACL_FLOAT,
&gradOutput);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the input aclTensor.
ret = CreateAclTensor(inputHostData, inputShape, &inputDeviceAddr, aclDataType::ACL_FLOAT, &input);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the grid aclTensor.
ret = CreateAclTensor(gridHostData, gridShape, &gridDeviceAddr, aclDataType::ACL_FLOAT, &grid);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create inputGrad aclTensor.
ret = CreateAclTensor(inputGradHostData, inputGradShape, &inputGradDeviceAddr, aclDataType::ACL_FLOAT, &inputGrad);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create gridGrad aclTensor.
ret = CreateAclTensor(gridGradHostData, gridGradShape, &gridGradDeviceAddr, aclDataType::ACL_FLOAT, &gridGrad);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API, and change the name to the actual API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnGridSampler2DBackward.
ret = aclnnGridSampler2DBackwardGetWorkspaceSize(gradOutput, input, grid, interpolationMode, paddingMode,
alignCorners, outputMask, inputGrad, gridGrad, &workspaceSize,
&executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGridSampler2DBackwardGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory according to 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 aclnnGridSampler2DBackward.
ret = aclnnGridSampler2DBackward(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGridSampler2DBackward failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronize and wait until the task is complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output values and copy the result from device memory to host memory. Modify the code according to the actual API definition.
auto inputGradSize = GetShapeSize(inputGradShape);
std::vector<float> inputGradResultData(inputGradSize, 0);
ret = aclrtMemcpy(inputGradResultData.data(), inputGradResultData.size() * sizeof(inputGradResultData[0]),
inputGradDeviceAddr, inputGradSize * sizeof(inputGradResultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy inputGradResultData from device to host failed. ERROR: %d\n", ret);
return ret);
for (int64_t i = 0; i < inputGradSize; i++) {
LOG_PRINT("inputGradResultData[%ld] is: %f\n", i, inputGradResultData[i]);
}
auto gridGradSize = GetShapeSize(gridGradShape);
std::vector<float> gridGradResultData(gridGradSize, 0);
ret = aclrtMemcpy(gridGradResultData.data(), gridGradResultData.size() * sizeof(gridGradResultData[0]),
gridGradDeviceAddr, gridGradSize * sizeof(gridGradResultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy gridGradResultData from device to host failed. ERROR: %d\n", ret);
return ret);
for (int64_t i = 0; i < gridGradSize; i++) {
LOG_PRINT("gridGradResultData[%ld] is: %f\n", i, gridGradResultData[i]);
}
// 6. Release aclTensor and aclBoolArray. Modify the code according to the actual API definition.
aclDestroyTensor(gradOutput);
aclDestroyTensor(input);
aclDestroyTensor(grid);
aclDestroyTensor(inputGrad);
aclDestroyTensor(gridGrad);
aclDestroyBoolArray(outputMask);
// 7. Release device resources. Modify the code according to the actual API definition.
aclrtFree(gradOutputDeviceAddr);
aclrtFree(inputDeviceAddr);
aclrtFree(gridDeviceAddr);
aclrtFree(inputGradDeviceAddr);
aclrtFree(gridGradDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}