aclnnUpsampleBicubic2dAA

📄 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: Not supported

Function

  • Description: Apply the bicubic anti-aliasing algorithm to upsample 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=0kW∑j=0kHW(i,j)∗f(hi,wj){out(N, C, h, w)}=\sum_{i=0}^{kW}\sum_{j=0}^{kH}{W(i, j)}*{f(h_i, w_j)} scaleH={(x.dim(2)−1)/(outputSize[0]−1)alignCorners=true1/scalesHalignCorners=false&scalesH>0x.dim(2)/outputSize[0]otherwisescaleH =\begin{cases} (x.dim(2)-1) / (outputSize[0]-1) & alignCorners=true \\ 1 / scalesH & alignCorners=false\&scalesH>0\\ x.dim(2) / outputSize[0] & otherwise \end{cases} scaleW={(x.dim(3)−1)/(outputSize[1]−1)alignCorners=true1/scalesWalignCorners=false&scalesW>0x.dim(3)/outputSize[1]otherwisescaleW =\begin{cases} (x.dim(3)-1) / (outputSize[1]-1) & alignCorners=true \\ 1 / scalesW & alignCorners=false\&scalesW>0\\ x.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).
    • If scaleH>=1scaleH >= 1, then kH=1/scaleHkH = 1/scaleH; otherwise kH=4kH = 4
    • If scaleW>=1scaleW >= 1, then kW=1/scaleWkW = 1/scaleW; otherwise kW=4kW = 4
    • hi=∣h∣+ih_i = |h| + i
    • wj=∣w∣+jw_j = |w| + 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:
      • For the anti-aliasing case, a=−0.5a=-0.5.
      • 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 "aclnnUpsampleBicubic2dAAGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnUpsampleBicubic2dAA" API to perform the computation.

aclnnStatus aclnnUpsampleBicubic2dAAGetWorkspaceSize(
  const aclTensor*   x,
  const aclIntArray* outputSize,
  const bool         alignCorners,
  const double       scalesH,
  const double       scalesW,
  aclTensor*         out,
  uint64_t*          workspaceSize,
  aclOpExecutor**    executor)
aclnnStatus aclnnUpsampleBicubic2dAA(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnUpsampleBicubic2dAAGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Input tensor for upsampling, corresponding to `x` in the formula.
    • Empty tensors are supported.
    • When the data format is ND, the tensor is processed in NCHW format by default.
    FLOAT16, FLOAT32, BFLOAT16 NCHW, ND 4 √
    outputSize (aclIntArray*) Input Spatial size of `out` in the H and W dimensions, corresponding to `outputSize` in the formula. size is 2, and all elements are greater than 0. INT64 - - -
    alignCorners (bool) Input Determines whether to align corner pixels, corresponding to `alignCorners` in the formula. If alignCorners is true, the corner pixels of the input and output tensors are aligned; otherwise, they are not aligned. - - - -
    scalesH (double) Input Specifies the height dimension multiplier of the spatial size, corresponding to `scalesH` in the formula. - - - - -
    scalesW (double) Input Multiplier for the width dimension of the spatial size, corresponding to `scalesW` in the formula. - - - - -
    out (aclTensor*) Output Indicates the output tensor after sampling, corresponding to `out` in the formula.
    • Empty tensor is supported.
    • The data type is the same as that of the input parameter `x`.
    FLOAT16, FLOAT32, BFLOAT16 NCHW, ND 4 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the device. - - - - -
    executor(aclOpExecutor**) Output Returns the op executor containing the operator computation process. - - - - -
  • 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 x, outputSize, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of x or out is not within the supported range.
    The data types of x and out are inconsistent.
    The shape of x is not 4D.
    The value of elements in outputSize is not greater than 0.

aclnnUpsampleBicubic2dAA

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Workspace size allocated on the device, obtained by the first-phase API aclnnUpsampleBicubic2dAAGetWorkspaceSize.
    executor Input Op executor, which contains the computation process of the operator.
    stream Input Stream for executing the task.
  • Return Value

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

Constraints

  • Shape constraints for parameters x 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 x, and the C, H, and W axes are greater than 0.

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

      (x_H∗x_W+out_H∗out_W+x_H∗out_W)∗N∗C∗sizeof(dtype)<60∗1024∗1024∗1024(x\_H * x\_W + out\_H * out\_W + x\_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 * x_H < 2^31

  • Atlas A3 products and Atlas A2 products:

    In the input data scaling use case, the downscaling factor must be less than or equal to 50, that is:

    InputshapeheightH/outputSize_H<=50Input shape height H/outputSize\_H <= 50 InputshapewidthW/outputSize_W<=50Input shape width W/outputSize\_W <=50
  • Parameters x, outputSize, scalesH, and scalesW must satisfy the following constraints:

    outputSize_H=floor(x_H∗scalesH)outputSize\_H = floor(x\_H * scalesH) outputSize_W=floor(x_W∗scalesW)outputSize\_W = floor(x\_W * scalesW)
  • Deterministic computation:

    • aclnnUpsampleBicubic2dAA 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_upsample_bicubic2d_aa.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 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);

    // Compute 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) 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("aclInit failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the input and output as required by the API.
    std::vector<int64_t> selfShape = {1, 1, 3, 3};
    std::vector<int64_t> outShape = {1, 1, 5, 5};
    void* selfDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* out = nullptr;
    std::vector<float> selfHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    const size_t kSize25 = 25U;
    std::vector<float> outHostData(kSize25, 0);
    const size_t kSize5 = 5U;
    std::vector<int64_t> outputSizeData = {kSize5, 5};
    bool alignCorners = false;
    double scalesH = 0.0;
    double scalesW = 0.0;
    // Create the self aclTensor.
    ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &x);
    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);
    // Create the outputSize aclIntArray.
    const aclIntArray* outputSize = aclCreateIntArray(outputSizeData.data(), outputSizeData.size());
    CHECK_RET(outputSize != nullptr, return ret);

    // 3. Call the CANN operator library API. Replace the API name with the actual one.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnUpsampleBicubic2dAA.
    ret = aclnnUpsampleBicubic2dAAGetWorkspaceSize(x, outputSize, alignCorners, scalesH, scalesW, out, &workspaceSize,
                                                   &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleBicubic2dAAGetWorkspaceSize 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 aclnnUpsampleBicubic2dAA.
    ret = aclnnUpsampleBicubic2dAA(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleBicubic2dAA failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Synchronously wait for the task execution to finish.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    // 5. Obtain the output value, copy the result on the device to the host, and modify it 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 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, and modify it based on the specific API definition
    aclDestroyTensor(x);
    aclDestroyIntArray(outputSize);
    aclDestroyTensor(out);

    // 7. Release device resources, and modify it based on the specific API definition
    aclrtFree(selfDeviceAddr);
    aclrtFree(outDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}