aclnnGridSampler2D
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Supported
Atlas inference products : Supported
Atlas training products : Supported
Function
Description: Provides an input tensor and a corresponding grid. Then, based on the coordinate information at each position in the grid, fill the pixel values at the corresponding positions in input into the positions specified by the grid to obtain the final output.
Formula:
The dimensions of input, grid, and output are as follows:
Here, N of input, grid, and output are consistent; C of input and output are consistent; and of grid and output are consistent; the last dimension of grid is 2, indicating that the input pixel position information is (x, y), and the value ranges of x and y are normalized to [-1, 1], where (-1, 1) indicates the top-left corner coordinate and (1, -1) indicates the bottom-right corner coordinate.
Formula for de-normalization:
alignCorners=true means the feature value is located at the pixel center.
alignCorners=false means the feature value is located at the pixel corner.
Coordinates out of range are handled differently according to paddingMode:
- paddingMode=0 means out-of-range positions are filled with 0.
- paddingMode=1 means out-of-range positions are filled with the boundary value.
- paddingMode=2 means out-of-range positions are filled with the symmetric value of the boundary value.
When sampling input, different processing is applied according to interpolationMode:
interpolationMode=0 means taking the weighted average of the four coordinates around (x, y).
Where:
- is the pixel value of the original image at .
- is the weight of the four neighboring points for bilinear interpolation, calculated as:
interpolationMode=1 means taking the coordinate value closest to (x, y) in input.
Where:
interpolationMode=2 means taking the weighted average of the sixteen coordinates around (x, y).
Where:
- i and j are the index variables of .
- is the pixel value of the original image at .
- is the weight of bicubic interpolation, defined as:
Where:
Function Prototype
Each operator uses a two-phase API. Call the "aclnnGridSampler2DGetWorkspaceSize" API first to obtain the workspace size required for the calculation and the executor that includes the operator calculation process, and then call the "aclnnGridSampler2D" API to perform the calculation.
aclnnStatus aclnnGridSampler2DGetWorkspaceSize(
const aclTensor *input,
const aclTensor *grid,
int64_t interpolationMode,
int64_t paddingMode,
bool alignCorners,
aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnGridSampler2D(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnGridSampler2DGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor input (aclTensor*) Input Input tensor for interpolation, corresponding to `input` described in the formula. - Supports null Tensor.
- The shape is (N, C, Hin, Win). H*W < the maximum value of INT32. The last two dimensions of the `input` shape cannot be 0.
FLOAT32, FLOAT16, DOUBLE, BFLOAT16 ND 4 √ grid (aclTensor*) Input Sampling grid, corresponding to `grid` described in the formula. - Supports null Tensor.
- The data type is consistent with the data type of input parameter `input`.
- Supports shape (N, Hout, Wout, 2), where N is consistent with N in the shape of input parameter `input`.
FLOAT32, FLOAT16, DOUBLE, BFLOAT16 ND 4 √ interpolationMode (int64_t) Input Indicates the interpolation mode, corresponding to `interpolationMode` in the formula description. Supports three modes: 0: bilinear, 1: nearest, 2: bicubic. - - - - paddingMode (int64_t) Input Indicates the padding mode, which specifies that a specific value is returned when the value of (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 correspondence between feature map coordinates and eigenvalues. When set to true, the eigenvalue position is at the pixel center. When set to false, the eigenvalue position is at the pixel corner. When set to true, the eigenvalue position is at the pixel center. When set to false, the eigenvalue position is at the pixel corner. - - - - out (aclTensor*) Output Final output of the interpolation calculation, corresponding to the `output` described in the formula. - Supports null Tensor.
- The data type is consistent with the data type of input.
- Supports shape (N, C, Hout, Wout), where N and C are consistent with N and C in the shape of input, and Hout and Wout are consistent with Hout and Wout in the shape of grid.
FLOAT32, FLOAT16, DOUBLE, BFLOAT16 ND 4 √ workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied for on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which includes calculation flow of the operator. - - - - - Atlas training products :- The parameter
interpolationModedoes not support interpolation mode 2: bicubic. - The data types of parameters
input,grid, andoutdo not support BFLOAT16.
- The parameter
Atlas A2 products ,Atlas A3 products :For input parameter
interpolationMode, the 2: bicubic mode is supported only when the input data type is FLOAT32, FLOAT16, or BFLOAT16.
Atlas 200I/500 A2 inference products :When the API runs on the AI Core, the following conditions must be met:
- The input parameter
interpolationModeis bilinear. - The input parameter
paddingModeis zeros. - The data types of parameters
input,grid, andoutare FLOAT16. - The shape of parameter
inputmust have a C dimension value of 32.
- The input parameter
Atlas inference products :When the API runs on the AI Core, the following conditions must be met:
- The input parameter
interpolationModeis bilinear. - The input parameter
paddingModeis zeros. - The data types of parameters
input,grid, andoutare FLOAT32. - The shape of parameter
inputmust have a C dimension value of 32, or CHW < 20480. - The data format of parameter
inputdoes not support NHWC.
- The input parameter
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 input, grid, or out is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of input, grid, and out are unsupported or inconsistent. The value of interpolationMode or paddingMode is out of the supported range. When interpolationMode is bicubic, the data types of input, grid, and out are not FLOAT32 or FLOAT16. The dimension relationships of input, grid, and out do not match. The last two dimensions of input are empty.
aclnnGridSampler2D
Parameters
Parameter Input/Output Description workspace Input Workspace memory address applied on the Device side. workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnGridSampler2DGetWorkspaceSize. executor Input opExecutor, includes the calculation process of the operator. stream Input Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- The data format of parameters
input,grid, andoutonly supports (N, C, H, W). When other data formats are input, they are processed as (N, C, H, W) by default. - For input
input, (H-axis size * W-axis size) < maximum value of INT32. - When the input value of grid multiplied by the image length or width exceeds the 24-bit binary number (16777216), sampling points may have errors and precision may deviate.
- If grid contains a large amount of data exceeding the [-1, 1] range, using the zeros or border padding strategy will cause many duplicate values in the result.
Atlas A2 products ,Atlas A3 products :- If grid contains values outside the range [-1, 1], using bicubic interpolation may introduce errors in small-value computations and cause precision deviations.
- When bilinear or bicubic interpolation is used, the FLOAT16 data type requires workspace memory.
Atlas training products : When bilinear interpolation is used, workspace memory is required for the FLOAT16 data type.
- Deterministic computation:
- aclnnGridSampler2D defaults to a deterministic implementation.
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.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)
{
// Fixed boilerplate for 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);
// 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. (Fixed 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);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Perform custom construction based on the API.
int64_t interpolationMode = 0;
int64_t paddingMode = 0;
bool alignCorners = false;
std::vector<int64_t> inputShape = {1, 1, 5, 8};
std::vector<int64_t> gridShape = {1, 3, 3, 2};
std::vector<int64_t> outShape = {1, 1, 3, 3};
void* inputDeviceAddr = nullptr;
void* gridDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
aclTensor* input = nullptr;
aclTensor* grid = nullptr;
aclTensor* out = nullptr;
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> outHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0};
// 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 the out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Change it to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnGridSampler2D.
ret = aclnnGridSampler2DGetWorkspaceSize(input, grid, interpolationMode, paddingMode, alignCorners, out,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGridSampler2DGetWorkspaceSize failed. ERROR: %d.\n[ERROR msg]%s", ret,
aclGetRecentErrMsg());
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[ERROR msg]%s", ret, aclGetRecentErrMsg());
return ret);
}
// Call the second-phase API of aclnnGridSampler2D.
ret = aclnnGridSampler2D(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnGridSampler2D failed. ERROR: %d.\n[ERROR msg]%s", ret, aclGetRecentErrMsg());
return ret);
// 4. (Boilerplate) Wait synchronously until the task is complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d.\n[ERROR msg]%s", ret, aclGetRecentErrMsg());
return ret);
// 5. Obtain the output value and copy the result on device memory to the host. Modify the code based on the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<float> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy resultData from device to host failed. ERROR: %d.\n[ERROR msg]%s",
ret, aclGetRecentErrMsg());
return ret);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("resultData[%ld] is: %f\n", i, resultData[i]);
}
// 6. Release aclTensor. Modify the code based on the specific API definition.
aclDestroyTensor(input);
aclDestroyTensor(grid);
aclDestroyTensor(out);
// 7. Release device resources. Modify the code based on the specific API definition.
aclrtFree(inputDeviceAddr);
aclrtFree(gridDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}