aclnnGridSampler3D

📄 View Source Code

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: Provides an input tensor input and a corresponding grid. 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 grid to obtain the final output.

  • Formula:

    The dimensions of input, grid, and output are as follows:

    input:(N,C,Din,Hin,Win)grid:(N,Dout,Hout,Wout,3)output:(N,C,Dout,Hout,Wout)input: (N, C, D_{in}, H_{in}, W_{in})\\ grid: (N, D_{out}, H_{out}, W_{out}, 3)\\ output: (N, C, D_{out}, H_{out}, W_{out})

    Where N in input, grid, and output is consistent, C in input and output is consistent, DoutD_{out}, HoutH_{out}, WoutW_{out} in grid and output are consistent, and the last dimension of grid has a size of 3, indicating that the input pixel position information is (x, y, z), with the value ranges of x, y, and z normalized to [-1, 1].

    • Formula for de-normalization:

      • alignCorners=true means the feature value is located at the pixel center.

        x′=(grid_x+1)/2∗(Win−1)x' = (grid\_x + 1) / 2 * (W_{in} - 1) y′=(grid_y+1)/2∗(Hin−1)y' = (grid\_y +1) / 2 * (H_{in} - 1) z′=(grid_z+1)/2∗(Din−1)z' = (grid\_z +1) / 2 * (D_{in} - 1)
      • alignCorners=false means the feature value is located at the pixel corner.

        x′=((grid_x+1)∗Win−1)/2x' = ((grid\_x +1) * W_{in} - 1) / 2 y′=((grid_y+1)∗Hin−1)/2y' = ((grid\_y +1) * H_{in} - 1) / 2 z′=((grid_z+1)∗Din−1)/2z' = ((grid\_z +1) * D_{in} - 1) / 2
    • 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="bilinear" means taking the weighted average of the eight coordinates around (x, y, z) in input.

        output(N,C,Dout,Hout,Wout)=∑i=01∑j=01∑k=01w(i,j,k)∗f(x′,y′,z′){output(N, C, D_{out}, H_{out}, W_{out})} = \sum_{i=0}^{1}\sum_{j=0}^{1}\sum_{k=0}^{1}{w(i, j, k)} * {f(x', y', z')}

        Where:

        • f(x′,y′,z′)f(x', y', z') is the pixel value of the original image at (x′,y′,z′)(x', y', z').
        • w(i,j,k)w(i, j, k) is the weight of the eight neighboring points for bilinear interpolation, calculated as:w(i)={1−∣xi′−xi∣∣xi′−xi∣<10otherwisew(i) = \begin{cases} 1 - |x'_i - x_i| & |x'_i - x_i| < 1 \\ 0 & otherwise \end{cases} w(j)={1−∣yj′−yj∣∣yj′−yj∣<10otherwisew(j) = \begin{cases} 1 - |y'_j - y_j| & |y'_j - y_j| < 1 \\ 0 & otherwise \end{cases} w(k)={1−∣zk′−zk∣∣zk′−zk∣<10otherwisew(k) = \begin{cases} 1 - |z'_k - z_k| & |z'_k - z_k| < 1 \\ 0 & otherwise \end{cases} w(i,j,k)=w(i)∗w(j)∗w(k)w(i, j, k)= w(i) * w(j) * w(k)
      • interpolationMode="nearest" means taking the coordinate value closest to (x, y, z) in input.

        output(N,C,Dout,Hout,Wout)=input(N,C,Din,Hin,Win)output(N, C, D_{out}, H_{out}, W_{out}) = input(N, C, D_{in}, H_{in}, W_{in})

        Where:

        Wout=min(round(x′),Win−1)Wout=max(round(x′),0)W_{out} = min(round(x'), W_{in} - 1)\\ W_{out} = max(round(x'), 0) Hout=min(round(y′),Hin−1)Hout=max(round(y′),0)H_{out} = min(round(y'), H_{in} - 1)\\ H_{out} = max(round(y'), 0) Dout=min(round(z′),Din−1)Dout=max(round(z′),0)D_{out} = min(round(z'), D_{in} - 1)\\ D_{out} = max(round(z'), 0)

Function Prototype

Each operator uses a two-phase API. First call the "aclnnGridSampler3DGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process. Then call the "aclnnGridSampler3D" API to perform the computation.

aclnnStatus aclnnGridSampler3DGetWorkspaceSize(
  const aclTensor *input,
  const aclTensor *grid,
  int64_t          interpolationMode,
  int64_t          paddingMode,
  bool             alignCorners,
  aclTensor       *out,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnGridSampler3D(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnGridSampler3DGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    input (aclTensor*) Input Input tensor for the interpolation calculation, corresponding to `input` described in the formula.
    • Supports null Tensor.
    • When the data format is ND, it is processed in NCDHW format; NDHWC is supported only when the conditions are met (the data type is FLOAT32 && interpolationMode is 0 && the size of the C axis is a multiple of 4).
    FLOAT16, FLOAT32, DOUBLE, BFLOAT16 NCDHW, NDHWC, ND 5 √
    grid (aclTensor*) Input Grid for sampling, corresponding to `grid` described in the formula.
    • Supports null tensors.
    • The data type must be the same as that of the input parameter `input`.
    • The supported shape is (N, Dout, Hout, Wout, 3), where N must be the same as N in the shape of the input parameter `input`.
    FLOAT16, FLOAT32, DOUBLE, BFLOAT16 ND 5 √
    interpolationMode (int64_t) Input Indicates the interpolation mode, corresponding to `interpolationMode` in the formula description. Supports two modes: 0: bilinear (bilinear interpolation) and 1: nearest (nearest-neighbor interpolation). - - - -
    paddingMode (int64_t) Input Specifies the padding mode for values outside the grid range. When the grid has values beyond [-1, 1], the corresponding output is processed as defined by paddingMode. It corresponds to `paddingMode` in the formula description. Supports three modes: 0: zeros, 1: border, and 2: reflection. - - - -
    alignCorners (bool) Input Specifies the mapping between feature map coordinates and feature values. If True, the extreme values -1 and 1 refer to the centers of the corner pixels of the reference input. If False, they refer to the corners of the corner pixels of the reference input. - - - -
    out (aclTensor*) Output Final output of the interpolation computation, corresponding to the `output` described in the formula.
    • Supports null Tensor.
    • The data format and data type are the same as those of input.
    • The N and C axes of shape are the same as those of input, and the D, H, and W axes of shape are the same as those of grid.
    FLOAT16, FLOAT32, DOUBLE, BFLOAT16 NCDHW, NDHWC, ND 5 √
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - -
    • Atlas training products:

      The data types of parameters input, grid, and out do 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 The input, grid, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of input, grid, and out are not in the supported range or are inconsistent.
    The data formats of input, grid, and out are not in the supported range.
    The value of interpolationMode or paddingMode is not in the supported range.
    The dimension relationships of input, grid, and out do not match.

aclnnGridSampler3D

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Workspace size allocated on the Device side, obtained by the first-phase API aclnnGridSampler3DGetWorkspaceSize.
    executor Input op executor that contains the operator computation process.
    stream Input Stream for executing tasks.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Error Codes.

Constraints

  • For input input, (D-axis size * H-axis size * W-axis size) < maximum value of INT32.
  • Deterministic computation:
    • aclnnGridSampler3D 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_sampler3d.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 code: 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 side.
    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_NCDHW,
                              shape.data(), shape.size(), *deviceAddr);
    return 0;
}

int main()
{
    // 1. (Boilerplate) device/stream initialization. For details, see the acl API manual.
    // Fill in 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, 1, 3, 3};
    std::vector<int64_t> gridShape = {1, 1, 2, 2, 3};
    std::vector<int64_t> outShape = {1, 1, 1, 2, 2};
    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};
    std::vector<float> gridHostData = {-1, -1, 0, -1, 1, -1, -1, 0, 0, 0, 1, 0};
    std::vector<float> outHostData = {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 aclnnGridSampler3D.
    ret = aclnnGridSampler3DGetWorkspaceSize(input, grid, interpolationMode, paddingMode, alignCorners, out,
                                             &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGridSampler3DGetWorkspaceSize 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 aclnnGridSampler3D.
    ret = aclnnGridSampler3D(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGridSampler3D 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 side. Modify it according to 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", ret);
              return ret);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("resultData[%ld] is: %f\n", i, resultData[i]);
    }

    // 6. Release aclTensor. Modify it according to the specific API definition.
    aclDestroyTensor(input);
    aclDestroyTensor(grid);
    aclDestroyTensor(out);

    // 7. Release Device resources. Modify it according to the specific API definition.
    aclrtFree(inputDeviceAddr);
    aclrtFree(gridDeviceAddr);
    aclrtFree(outDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}