aclnnUpsampleBilinear2dBackwardV2

📄 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: Backward propagation of aclnnUpsampleBilinear2d.

    • Atlas A2 products, Atlas A3 products, and Ascend 950PR&950DT products: Compared with aclnnUpsampleBilinear2dBackward, this API supports computation using scale and adds constraints on outputSize and scale. Select an appropriate API based on the actual use case.
  • Formula:

    • Core algorithm logic of the forward pass:
      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={(inputSize[2]−1)/(outputSize[0]−1)alignCorners=true1/scalesHalignCorners=false&scalesH>0inputSize[2]/outputSize[0]alignCorners=falsescaleH =\begin{cases} (inputSize[2]-1) / (outputSize[0]-1) & alignCorners=true \\ 1 / scalesH & alignCorners=false\&scalesH>0\\ inputSize[2] / outputSize[0] & alignCorners=false \end{cases} scaleW={(inputSize[3]−1)/(outputSize[1]−1)alignCorners=true1/scalesWalignCorners=false&scalesW>0inputSize[3]/outputSize[1]alignCorners=falsescaleW =\begin{cases} (inputSize[3]-1) / (outputSize[1]-1) & alignCorners=true \\ 1 / scalesW & alignCorners=false\&scalesW>0\\ inputSize[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}}
      • Assumption: The output image out (x,y)(x, y) of forward interpolation is affected by the original image input (xi,yj)(x_i, y_j). Then:

        gradInput(xi,yj)+=gradOutput(x,y)∗lambda(xi,yj)∗lambdb(xi,yj)gradInput(x_i,y_j) += gradOutput(x,y) * lambda(x_i,y_j) * lambdb(x_i,y_j)

Function Prototype

Each operator uses a two-phase API. Call the "aclnnUpsampleBilinear2dBackwardV2GetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the operator computation process. Then call the "aclnnUpsampleBilinear2dBackwardV2" API to perform the computation.

aclnnStatus aclnnUpsampleBilinear2dBackwardV2GetWorkspaceSize(
  const aclTensor   *gradOut,
  const aclIntArray *outputSize,
  const aclIntArray *inputSize,
  bool               alignCorners,
  double             scalesH,
  double             scalesW,
  aclTensor         *out,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnUpsampleBilinear2dBackwardV2(
  void*          workspace,
  uint64_t       workspaceSize,
  aclOpExecutor* executor,
  aclrtStream    stream)

aclnnUpsampleBilinear2dBackwardV2GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gradOut (aclTensor*) Input Represents the gradient tensor for backward computation, corresponding to `gradOutput` in the formula. Empty tensors are not supported. FLOAT32, FLOAT16, BFLOAT16 NCHW, NHWC 4 √
    outputSize (aclIntArray*) Input Represents the spatial size of input `gradOut` on the H and W dimensions. Corresponds to `outputSize` in the formula. size is 2, and all elements are greater than zero. INT64 - - -
    inputSize (aclIntArray*) Input Represents the spatial sizes of the output `out` on the N, C, H, and W dimensions, respectively. Corresponds to `inputSize` in the formula. size is 4, and all elements are greater than zero. INT64 - - -
    alignCorners (bool) Input Determines whether to align corner pixels, corresponding to `alignCorners` in the corresponding formula. If set to True, the input and output tensors are aligned by the center points 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 corner points of their corner pixels, and the interpolation fills values outside the boundary with edge values so that this operation remains consistent across different input sizes. - - - -
    scalesH (double) Input Represents the multiplier on the height dimension of the output `out`, corresponding to `scalesH` in the formula. - - - - -
    scalesW (double) Input Represents the multiplier on the width dimension of output `out`, corresponding to `scalesW` in the formula. - - - - -
    out (aclTensor*) Output Represents the output tensor of backward computation, corresponding to `gradInput` in the formula.
    • Empty tensors are not supported.
    • The data type, data format, and shape must remain consistent with input parameter `gradOut`.
    FLOAT32, FLOAT16, BFLOAT16 NCHW, NHWC 4 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - -
    • Atlas training products and Atlas inference products:

      The data types of parameters gradOut 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 gradOut, outputSize, inputSize, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type and data format of gradOut and out are not within the supported range.
    The data type or shape of gradOut is inconsistent with that of out.
    The dimension of gradOut is not 4.
    The size of outputSize is not 2.
    An element value of outputSize is less than 1.
    The size of inputSize is not 4.
    An element value of inputSize is less than 1.
    The sizes of gradOut and inputSize on the N and C dimensions are different.
    The size of gradOut on the H and W dimensions is inconsistent with outputSize[0] and outputSize[1].
    The dimension sizes of gradOut and out are not equal on the N/C axis.

aclnnUpsampleBilinear2dBackwardV2

  • Parameters

    Parameter Input/Output Description
    workspace Input Memory address of the workspace applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by calling the first-phase API aclnnUpsampleBilinear2dBackwardV2GetWorkspaceSize.
    executor Input op executor, containing the operator computation process.
    stream Input Stream for executing the task.
  • Return Value

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

Constraints

  • Shape constraints for parameters gradOut 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 gradOut.

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

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

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

    outputSize_H=floor(inputSize_H∗scalesH)outputSize\_H = floor(inputSize\_H * scalesH) outputSize_W=floor(inputSize_W∗scalesW)outputSize\_W = floor(inputSize\_W * scalesW)
  • Deterministic computation:

    • Atlas A3 products, Atlas A2 products, Atlas inference products, and Atlas training products: aclnnUpsampleBilinear2dBackwardV2 defaults to a deterministic implementation.
    • Ascend 950PR&950DT products: aclnnUpsampleBilinear2dBackwardV2 defaults to a nondeterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.

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_bilinear_2d_backward_v2.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 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.
    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 the 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);

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

    // 2. Construct the input and output. Customize the construction as required by the API.
    std::vector<int64_t> selfShape = {1, 1, 6, 6};
    std::vector<int64_t> outShape = {1, 1, 3, 3};
    void* selfDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* self = nullptr;
    aclTensor* out = nullptr;
    std::vector<float> selfHostData(36, 1);
    std::vector<float> outHostData = {0, 0, 0, 0, 0, 0, 0, 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);

    std::vector<int64_t> outArraySize = {6, 6};
    const aclIntArray* outputSize = aclCreateIntArray(outArraySize.data(), outArraySize.size());
    CHECK_RET(outputSize != nullptr, return ACL_ERROR_INTERNAL_ERROR);

    std::vector<int64_t> inputArraySize = {1, 1, 3, 3};
    const aclIntArray* inputSize = aclCreateIntArray(inputArraySize.data(), inputArraySize.size());
    CHECK_RET(inputSize != nullptr, return ACL_ERROR_INTERNAL_ERROR);

    // 3. Call the CANN operator library API. Replace it with the actual API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnUpsampleBilinear2dBackwardV2.
    ret = aclnnUpsampleBilinear2dBackwardV2GetWorkspaceSize(self, outputSize, inputSize, 1, 2, 2, out, &workspaceSize,
                                                            &executor);
    CHECK_RET(ret == ACL_SUCCESS,
              LOG_PRINT("aclnnUpsampleBilinear2dBackwardV2GetWorkspaceSize 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 aclnnUpsampleBilinear2dBackwardV2.
    ret = aclnnUpsampleBilinear2dBackwardV2(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleBilinear2dBackwardV2 failed. ERROR: %d\n", ret); return ret);

    // 4. (boilerplate) Wait 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 and copy the results from the device memory to the host. Modify the code as required by 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 aclScalar. Modify the code as required by the specific API definition.
    aclDestroyTensor(self);
    aclDestroyTensor(out);
    aclDestroyIntArray(outputSize);
    aclDestroyIntArray(inputSize);

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