aclnnUpsampleBicubic2d

📄 View Source Code

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: Apply 2D bicubic upsampling to an input signal composed of multiple input channels. If the shape of input tensor x is (N, C, H, W), the shape of output tensor out is (N, C, outputSize[0], outputSize[1]).

  • Formula: For a 2D interpolation point (N,C,h,w)(N, C, h, w), the interpolation out(N,C,h,w)out(N, C, h, w) can be expressed as:

    out(N,C,h,w)=∑i=03∑j=03W(i,j)∗f(hi,wj){out(N, C, h, w)}=\sum_{i=0}^{3}\sum_{j=0}^{3}{W(i, j)}*{f(h_i, w_j)} scaleH={(self.dim(2)−1)/(outputSize[0]−1)alignCorners=true1/scalesHalignCorners=false&scalesH>0self.dim(2)/outputSize[0]otherwisescaleH =\begin{cases} (self.dim(2)-1) / (outputSize[0]-1) & alignCorners=true \\ 1 / scalesH & alignCorners=false\&scalesH>0\\ self.dim(2) / outputSize[0] & otherwise \end{cases} scaleW={(self.dim(3)−1)/(outputSize[1]−1)alignCorners=true1/scalesWalignCorners=false&scalesW>0self.dim(3)/outputSize[1]otherwisescaleW =\begin{cases} (self.dim(3)-1) / (outputSize[1]-1) & alignCorners=true \\ 1 / scalesW & alignCorners=false\&scalesW>0\\ self.dim(3) / outputSize[1] & otherwise \end{cases}

    Where:

    • alignCorners = true means the corner pixels of the input and output tensors are aligned; alignCorners = false means the edge pixels of the input and output tensors are aligned.
    • i and j are the index variables of W(i,j)W(i, j).
    • f(hi,wj)f(h_i, w_j) is the pixel value of the original image at (hi,wj)(h_i, w_j).
    • W(i,j)W(i, j) is the weight of bicubic anti-aliasing interpolation, defined as:W(d)={(a+2)∣d∣3−(a+3)∣d∣2+1∣d∣≤1a∣d∣3−5a∣d∣2+8a∣d∣−4a1<∣d∣<20otherwiseW(d) =\begin{cases} (a+2)|d|^3-(a+3)|d|^2+1 & |d|\leq1 \\ a|d|^3-5a|d|^2+8a|d|-4a & 1<|d|<2 \\ 0 & otherwise \end{cases} Where:
      • a=−0.75a=-0.75
      • d=∣(h,w)−(hi,wj)∣d = |(h, w) - (h_i, w_j)|

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnUpsampleBicubic2dGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnUpsampleBicubic2d" API to perform the computation.

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

aclnnUpsampleBicubic2dGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self (aclTensor*) Input Represents the input tensor for upsampling, corresponding to `self` in the formula.
    • Empty tensors are not supported.
    • When the data format is ND, it is processed in NCHW format by default.
    FLOAT32, FLOAT16, BFLOAT16 NCHW, ND, NHWC 4 √
    outputSize (aclIntArray*) Input Represents the spatial size of `out` on the H and W dimensions. Corresponds to `outputSize` in the formula. The size is 2, and each element is greater than 0. INT64 - - -
    alignCorners (bool) Input Determines whether to align the corner pixels, corresponding to `alignCorners` in the formula. If alignCorners is True, the corner pixels of the input and output tensors are aligned. Otherwise, the edge pixels of the input and output tensors are aligned. - - - -
    scalesH (double) Input Specifies the multiplier of the height dimension of the spatial size, corresponding to `scalesH` in the formula. - - - - -
    scalesW (double) Input Specifies the multiplier on the width dimension of the spatial size, corresponding to `scalesW` in the formula. - - - - -
    out (aclTensor*) Output Represents the output tensor after upsampling, corresponding to `out` in the formula.
    • Empty tensors are not supported.
    • The data type and data format must be the same as those of `self`.
    • Supports 4D shapes: (batch, channel, height, width), where batch and channel come from the 0th and 1st dimensions of `self`, and height and width come from the first and second values of `outputSize`.
    FLOAT32, FLOAT16, BFLOAT16 NCHW, ND, NHWC 4 √
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas 200I/500 A2 inference products, Atlas inference products, Atlas training products:
      • Data type: The parameters self and out do not support BFLOAT16.
      • Data format: The parameters self and out do not support NHWC.
    • Atlas A2 products, Atlas A3 products:

      The data format of parameters self and out does not support NHWC.

  • 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 The passed self, outputSize, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self is not in the supported range.
    The data types of self and out are inconsistent.
    The data format of self is not in the supported range.
    The data formats of self and out are inconsistent.
    The shapes of self and out are not 4D.
    The size of outputSize is not 2.
    The size of self on the C, H, and W dimensions is not greater than 0.
    The value of an element in outputSize is not greater than 0.
    The size of out on the N and C dimensions is not equal to the size of self on the N and C dimensions.
    The size of out on the H and W dimensions is not equal to the corresponding element value in outputSize.
    self, outputSize, scalesH, and scalesW do not meet the constraints.

aclnnUpsampleBicubic2d

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnUpsampleBicubic2dGetWorkspaceSize.
    executor Input op executor, which contains the operator computation flow.
    stream Input Specifies the Stream for executing tasks.
  • Return Value

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

Constraints

  • Shape constraints for parameters self and out:

    • The value of each dimension is less than or equal to 2^20.

    • The N and C axes of parameter out are the same as those of self.

    • The memory usage must be less than 60 GB. The formula for memory usage is as follows:

      (self_H∗self_W+out_H∗out_W+self_H∗out_W)∗N∗C∗sizeof(dtype)<60∗1024∗1024∗1024(self\_H * self\_W + out\_H * out\_W + self\_H * out\_W) * N * C * sizeof(dtype) < 60 * 1024 * 1024 * 1024

      Where:

      • N represents the N axis of the input and output.
      • C represents the C axis of the input and output.
      • dtype represents the data type of the input tensor.
    • N * C * self_H < 2^31

  • When the value of scalesH is greater than 0, parameters self, outputSize, and scalesH must satisfy the following constraints:

    outputSize_H=floor(self_H∗scalesH)outputSize\_H = floor(self\_H * scalesH)
  • When the value of scalesW is greater than 0, parameters self, outputSize, and scalesW must satisfy the following constraints:

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

    • aclnnUpsampleBicubic2d defaults to a deterministic implementation.

Example

The following sample code is for reference only. For details about compiling and running the sample, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_upsample_bicubic_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: 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 the 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 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 the 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);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init failed. ERROR: %d\n", ret); return ret);

    // 2. Construct input and output, which need to be customized based on the API
    constexpr int64_t INPUT_H = 3;
    constexpr int64_t INPUT_W = 3;
    constexpr int64_t OUTPUT_H = 5;
    constexpr int64_t OUTPUT_W = 5;
    std::vector<int64_t> selfShape = {1, 1, INPUT_H, INPUT_W};
    std::vector<int64_t> outShape = {1, 1, OUTPUT_H, OUTPUT_W};
    void* selfDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* self = nullptr;
    aclTensor* out = nullptr;
    std::vector<float> selfHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::vector<float> outHostData(OUTPUT_H * OUTPUT_W, 0);
    std::vector<int64_t> outputSizeData = {OUTPUT_H, OUTPUT_W};
    bool alignCorners = false;
    double scalesH = 0.0;
    double scalesW = 0.0;
    // Create self aclTensor
    ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create out aclTensor
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create outputSize aclIntArray
    const aclIntArray* outputSize = aclCreateIntArray(outputSizeData.data(), outputSizeData.size());
    CHECK_RET(outputSize != nullptr, return ret);

    // 3. Call the CANN operator library API, which needs to be changed to the specific API name
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnUpsampleBicubic2d
    ret = aclnnUpsampleBicubic2dGetWorkspaceSize(self, outputSize, alignCorners, scalesH, scalesW, out, &workspaceSize,
                                                 &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleBicubic2dGetWorkspaceSize 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 of aclnnUpsampleBicubic2d
    ret = aclnnUpsampleBicubic2d(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleBicubic2d failed. ERROR: %d\n", ret); return ret);

    // 4. (boilerplate) Wait for the task execution to complete synchronously
    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-side memory to the host side, which needs to be modified 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 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. Release aclTensor and aclIntArray. Modify the code according to the specific API definition.
    aclDestroyTensor(self);
    aclDestroyIntArray(outputSize);
    aclDestroyTensor(out);

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