aclnnUpsampleNearest3d

📄 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 nearest-neighbor interpolation to upsample an input signal composed of multiple input channels. If the input shape is (N, C, D, H, W), the output shape is (N, C, outputSize[0], outputSize[1], outputSize[2]).
  • 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. Calculate the point in the original image nearest to this floating-point coordinate, and directly copy the value of the latter to the former.
    • Specific computation logic:scaleD={scalesDscalesD>0&scalesH>0&scalesW>0outputSize[0]/self_DOtherwisescaleD =\begin{cases} scalesD & scalesD>0\&scalesH>0\&scalesW>0\\ outputSize[0] / self\_D & Otherwise\\ \end{cases} scaleH={scalesHscalesD>0&scalesH>0&scalesW>0outputSize[1]/self_HOtherwisescaleH =\begin{cases} scalesH & scalesD>0\&scalesH>0\&scalesW>0\\ outputSize[1] / self\_H & Otherwise\\ \end{cases} scaleW={scalesWscalesD>0&scalesH>0&scalesW>0outputSize[2]/self_WOtherwisescaleW =\begin{cases} scalesW & scalesD>0\&scalesH>0\&scalesW>0\\ outputSize[2] / self\_W & Otherwise\\ \end{cases} dsrc=min(floor(ddst/scaleD),self_D−1)d_{src} = min(floor(d_{dst} / scaleD), self\_D - 1) hsrc=min(floor(hdst/scaleH),self_H−1)h_{src} = min(floor(h_{dst} / scaleH), self\_H - 1) wsrc=min(floor(wdst/scaleW),self_W−1)w_{src} = min(floor(w_{dst} / scaleW), self\_W - 1) out(N,C,ddst,hdst,wdst)=self(N,C,dsrc,hsrc,wsrc)out(N, C, d_{dst},h_{dst}, w_{dst}) = self(N, C, d_{src},h_{src}, w_{src})

Function Prototype

Each operator uses a two-phase API. Call the aclnnUpsampleNearest3dGetWorkspaceSize API first to obtain the input parameters and calculate the required workspace size based on the computation process, and then call the aclnnUpsampleNearest3d API to perform the computation.

aclnnStatus aclnnUpsampleNearest3dGetWorkspaceSize(
  const aclTensor   *self,
  const aclIntArray *outputSize,
  double             scalesD,
  double             scalesH,
  double             scalesW,
  aclTensor         *out,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnUpsampleNearest3d(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  aclrtStream       stream)

aclnnUpsampleNearest3dGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self (aclTensor*) Input Input tensor for upsampling. Corresponding formula variable: `self`.
    • Empty tensors are not supported.
    • When the data format is ND, the tensor is processed as NCDHW by default.
    • The value of each dimension of self is less than or equal to (2^31-1).
    • The size of the C, D, H, and W dimensions of shape is greater than 0.
    FLOAT32, FLOAT16, BFLOAT16, DOUBLE, UINT8 NCDHW, NDHWC, ND 5 √
    outputSize (aclIntArray*) Input Spatial size of the specified output out on the D, H, and W dimensions. Corresponding formula variable: `outputSize`. The size is 3, and all element values must be greater than zero. INT64 - - -
    scalesD (double) Input Specifies the dimension multiplier of the depth dimension of the output out, corresponding to `scalesD` in the formula. - - - - -
    scalesH (double) Input Dimension multiplier of the specified output out for the height dimension, corresponding to `scalesH` in the formula. - - - - -
    scalesW (double) Input Specifies the width dimension multiplier of the output out, corresponding to `scalesW` in the formula. - - - - -
    out (aclTensor*) Output Represents the output tensor after sampling, corresponding to the coordinates of point p of `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.
    • The N and C axes of the input and output shapes must be the same.
    • All dimension values of out must be less than or equal to (2^31-1).
    FLOAT32, FLOAT16, BFLOAT16, DOUBLE, UINT8 NCDHW, NDHWC, ND 5 √
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be allocated on the Device by the user. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor that contains the operator computation flow. - - - - -
    • Atlas inference products:

      The data types of input parameter self and output parameter out do not support BFLOAT16, DOUBLE, or UINT8.

    • Atlas training products:

      The data types of input parameter self and output parameter out do not support BFLOAT16 or UINT8.

    • Atlas A2 products and Atlas A3 products:

      The data types of input parameter self and output parameter out do not support UINT8.

  • 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 parameter is a required input, output, or required attribute, and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self is not supported, or the data type of self is different from that of out.
    The shape of self is not 5-dimensional.
    The size of outputSize is not 3.
    The size of self in the C, D, H, or W dimension is not greater than 0.
    Any element in outputSize is not greater than 0.
    The D, H, or W dimension in the shape of out is not equal to outputSize.

aclnnUpsampleNearest3d

  • Parameters

    Parameter Input/Output Description
    workspace Input Memory address of the workspace allocated on the device.
    workspaceSize Input Size of the workspace allocated on the device, obtained by calling the first-phase API aclnnUpsampleNearest3dGetWorkspaceSize.
    executor Input Op executor, which contains the computation flow of the operator.
    stream Input Stream used to execute tasks.
  • Return Value

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

Constraints

  • If the values of input scalesD, scalesH, and scalesW are all greater than 0, parameters self, outputSize, and scalesD must satisfy the following constraints:

    outputSize_D=floor(self_D∗scalesD)outputSize\_D = floor(self\_D * scalesD) 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:

    • aclnnUpsampleNearest3d 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_nearest_3d.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 shape_size = 1;
    for (auto i : shape) {
        shape_size *= i;
    }
    return shape_size;
}

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 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 data from the host to device 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_NCDHW,
                              shape.data(), shape.size(), *deviceAddr);
    return 0;
}

int main()
{
    // 1. (Boilerplate) Initialize device/stream. For details, see the acl API documentation.
    // Fill in deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check as required.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the inputs and outputs. Custom construction is required based on the API.
    std::vector<int64_t> selfShape = {2, 2, 2, 2, 3};
    std::vector<int64_t> outShape = {2, 2, 1, 1, 1};
    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,  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, 41, 42, 43, 44, 45, 46, 47, 48};
    std::vector<float> outHostData = {1, 2, 3, 4};
    std::vector<int64_t> outputSizeData = {1, 1, 1};
    double scalesD = 0.0;
    double scalesH = 0.0;
    double scalesW = 0.0;
    // Create the self aclTensor.
    ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
    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);

    const aclIntArray* outputSize = aclCreateIntArray(outputSizeData.data(), outputSizeData.size());
    CHECK_RET(outputSize != nullptr, return ACL_ERROR_INTERNAL_ERROR);

    // 3. Call the CANN operator library API. Replace it with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnUpsampleNearest3d.
    ret = aclnnUpsampleNearest3dGetWorkspaceSize(self, outputSize, scalesD, scalesH, scalesW, out, &workspaceSize,
                                                 &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleNearest3dGetWorkspaceSize 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 aclnnUpsampleNearest3d.
    ret = aclnnUpsampleNearest3d(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleNearest3d failed. ERROR: %d\n", ret); return ret);
    // 4. (boilerplate) Wait synchronously for the 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 values, copy the result from the device memory 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(float),
                      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 aclScalar, and modify it based on the specific API definition.
    aclDestroyTensor(self);
    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;
}