aclnnUpsampleBilinear2d

📄 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: Supported
  • Atlas training products: Supported

Function

  • Description: Apply 2D bilinear upsampling to an input signal composed of multiple input channels.

    • For the input shape: If the input shape is (N, C, H, W), the output shape is (N, C, outputSize[0], outputSize[1]).
    • For the choice of center alignment: A general pixel is treated as a grid. When alignCorners = True, the pixel is treated as the point at the top-left corner of the grid, and the pixel at the output corner is aligned with the corner pixel center of the original image, and points in the same direction are equally spaced; when alignCorners = False, the pixel is treated as a point on the crossing line of the grid, and the pixel at the output corner is still the corner pixel of the original image, but points in the same direction are unevenly spaced.
  • Formula:

    • Core algorithm logic:
      1. Map each point of the target image back to the original image to obtain a coordinate with a fractional part.
      2. Based on this floating-point coordinate, compute the adjacent original image points before and after.
      3. Compute the weights of the adjacent points to the corresponding target point respectively, and multiply and accumulate them according to the weights to obtain the target point value.
    • Specific computation logic: The scaling method is divided into corner alignment and edge alignment. Corner alignment (alignCorners = true) means aligning according to the pixel center point at the top-left corner of the original image; edge alignment (alignCorners = false) means aligning according to the top-left vertex and two edges of the original image. There are differences in computing the scaling coefficient and coordinate position. For a 2D interpolation point (N,C,H,W)(N, C, H, W), the following formula applies:scaleH={(self.dim[2]−1)/(outputSize[0]−1)alignCorners=true1/scalesHalignCorners=false&scalesH>0self.dim[2]/outputSize[0]alignCorners=falsescaleH =\begin{cases} (self.dim[2]-1) / (outputSize[0]-1) & alignCorners=true \\ 1 / scalesH & alignCorners=false\&scalesH>0\\ self.dim[2] / outputSize[0] & alignCorners=false \end{cases} scaleW={(self.dim[3]−1)/(outputSize[1]−1)alignCorners=true1/scalesWalignCorners=false&scalesW>0self.dim[3]/outputSize[1]alignCorners=falsescaleW =\begin{cases} (self.dim[3]-1) / (outputSize[1]-1) & alignCorners=true \\ 1 / scalesW & alignCorners=false\&scalesW>0\\ self.dim[3] / outputSize[1] & alignCorners=false \end{cases} Therefore, for a point p(x,y) in a certain direction of the output, the point mapped back to the original image is denoted as q(x',y'), and the relationship is as follows:x′={x∗scaleHalignCorners=trueMAX(0,(x+0.5)∗scaleH−0.5)alignCorners=falsex' =\begin{cases} x * scaleH & alignCorners=true \\ MAX(0,{(x+0.5)*scaleH-0.5}) & alignCorners=false \end{cases} y′={y∗scaleWalignCorners=trueMAX(0,(y+0.5)∗scaleW−0.5)alignCorners=falsey' =\begin{cases} y * scaleW & alignCorners=true \\ MAX(0,{(y+0.5)*scaleW-0.5}) & alignCorners=false \end{cases}
      • Notation:

        x0=int(x′),x1=int(x′)+1,lambda0=x1−x′,lambda1=1−lambda0x_{0} =int(x'),x_{1} =int(x')+1, lambda_{0} = x_{1}-x', lambda_{1} = 1-lambda_{0} y0=int(y′),y1=int(y′)+1,lambdb0=y1−y′,lambdb1=1−lambdb0y_{0} =int(y'),y_{1} =int(y')+1, lambdb_{0} = y_{1}-y', lambdb_{1} = 1-lambdb_{0}
      • Then the following formula applies:

        V(px,y)=V(px0,y0)∗lambda0∗lambdb0+V(px0,y1)∗lambda0∗lambdb1+V(px1,y0)∗lambda1∗lambdb0+V(px1,y1)∗lambda1∗lambdb1{V(p_{x, y})} = {V(p_{x0, y0})} * {lambda_{0}} * {lambdb_{0}} \\ + {V(p_{x0, y1})} * {lambda_{0}} * {lambdb_{1}} \\ + {V(p_{x1, y0})} * {lambda_{1}} * {lambdb_{0}} \\ + {V(p_{x1, y1})} * {lambda_{1}} * {lambdb_{1}}

Function Prototype

Each operator uses a two-phase API. Call the "aclnnUpsampleBilinear2dGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the operator computation process. Then call the "aclnnUpsampleBilinear2d" API to perform the computation.

aclnnStatus aclnnUpsampleBilinear2dGetWorkspaceSize(
  const aclTensor   *self,
  const aclIntArray *outputSize,
  const bool         alignCorners,
  const double       scalesH,
  const double       scalesW,
  aclTensor         *out,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnUpsampleBilinear2d(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnUpsampleBilinear2dGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self (aclTensor*) Input Input tensor for upsampling, corresponding to `self` in the formula.
    • Empty tensors are not supported.
    • When the data type is DOUBLE, only the NHWC format is supported.
    FLOAT32, BFLOAT16, FLOAT16, DOUBLE NCHW, NHWC 4 √
    outputSize (aclIntArray*) Input Specifies the output spatial size, indicating the spatial size of `out` in the H and W dimensions. Corresponds to `outputSize` in the formula. Size is 2, and all elements are greater than zero. INT64 - - -
    alignCorners (bool) Input Determines whether to align corner pixels, corresponding to `alignCorners` in the formula. If set to True, the input and output tensors are aligned by the center of their corner pixels, and the values at the corner pixels are preserved. If set to False, the input and output tensors are aligned by the corners of their corner pixels, and values outside the boundary are padded with edge values. - - - -
    scalesH (double) Input Multiplier for the height dimension of the spatial size, corresponding to `scalesH` in the formula. Negative values are not allowed. - - - -
    scalesW (double) Input Multiplier for the width dimension of the output spatial size, corresponding to `scalesW` in the formula. Negative values are not allowed. - - - -
    out (aclTensor*) Output Output tensor after sampling, corresponding to `out` in the formula.
    • Empty tensors are not supported.
    • The data type and data format must be the same as those of the input parameter `self`.
    • When the data type is DOUBLE, only the NHWC format is supported.
    • Only 4-dimensional shapes are supported, and the N and C dimensions must be the same as those of the input self shape.
    FLOAT32, BFLOAT16, FLOAT16, DOUBLE NCHW, NHWC 4 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas inference products, Atlas training products:

      The data types of parameters self 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 Internal API validation error, usually caused by input data or attribute specifications not within the supported range.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self is not within the supported range.
    The dimension sizes of self and out along the N/C axes are not equal.
    The data format of self and out is not within the supported range.
    The value of scalesH or scalesW is negative.

aclnnUpsampleBilinear2d

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the Device side.
    workspaceSize Input Workspace size requested on the Device side, obtained by the first-phase API aclnnUpsampleBilinear2dGetWorkspaceSize.
    executor Input Operator executor that contains the computation flow.
    stream Input Stream on which the task is executed.
  • Return Value

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

Constraints

  • Parameters self, outputSize, scalesH, and scalesW must satisfy the following constraints:

    outputSize_H=floor(self_H∗scalesH)outputSize\_H = floor(self\_H * scalesH) outputSize_W=floor(self_W∗scalesW)outputSize\_W = floor(self\_W * scalesW)
  • Deterministic computation:

    • aclnnUpsampleBilinear2d defaults to a deterministic implementation.

Example

The sample code is for reference only. For details about how to compile and run the code, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_upsample_bilinear_2d.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 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 CreateAclNchTensor(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 request 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_NCHW,
                              shape.data(), shape.size(), *deviceAddr);
    return 0;
}

int main()
{
    // 1. (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. You need to construct them based on the API.
    std::vector<int64_t> selfShape = {1, 1, 4, 2};
    std::vector<int64_t> outShape = {1, 1, 8, 4};
    void* selfDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* self = nullptr;
    aclTensor* out = nullptr;
    std::vector<float> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7};
    std::vector<float> outHostData(32, 0);
    std::vector<int64_t> outputSize = {8, 4};
    bool alignCorners = true;
    double scalesH = 2.0;
    double scalesW = 2.0;
    // Create the self aclTensor.
    ret = CreateAclNchTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the self aclIntArray.
    auto outputSizeArray = aclCreateIntArray(outputSize.data(), 2);
    // Create the out aclTensor.
    ret = CreateAclNchTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Replace with the actual API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API aclnnUpsampleBilinear2d.
    ret = aclnnUpsampleBilinear2dGetWorkspaceSize(self, outputSizeArray, alignCorners, scalesH, scalesW, out,
                                                  &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleBilinear2dGetWorkspaceSize 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 aclnnUpsampleBilinear2d.
    ret = aclnnUpsampleBilinear2d(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleBilinear2d 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.
    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 result from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
    }

    // 6. Destroy the aclTensor. Modify it according to the actual API definition.
    aclDestroyTensor(self);
    aclDestroyTensor(out);

    // 7. Release device resources. Modify it according to the actual API definition.
    aclrtFree(selfDeviceAddr);
    aclrtFree(outDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}