aclnnUpsampleTrilinear3dBackward

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Not 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 computation of aclnnUpsampleTrilinear3d.md.

  • 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 3D interpolation point (N,C,D,H,W)(N, C, D, H, W), the following formula applies:

      scale_d={(inputSize[2]−1)/(outputSize[0]−1)alignCorners=true1/scales_dalignCorners=false&scales_d>0inputSize[2]/outputSize[0]alignCorners=falsescale\_d =\begin{cases} (inputSize[2]-1) / (outputSize[0]-1) & alignCorners=true \\ 1 / scales\_d & alignCorners=false\&scales\_d>0\\ inputSize[2] / outputSize[0] & alignCorners=false \end{cases} scale_h={(inputSize[3]−1)/(outputSize[1]−1)alignCorners=true1/scales_halignCorners=false&scales_h>0inputSize[3]/outputSize[1]alignCorners=falsescale\_h =\begin{cases} (inputSize[3]-1) / (outputSize[1]-1) & alignCorners=true \\ 1 / scales\_h & alignCorners=false\&scales\_h>0\\ inputSize[3] / outputSize[1] & alignCorners=false \end{cases} scale_w={(inputSize[4]−1)/(outputSize[2]−1)alignCorners=true1/scales_walignCorners=false&scales_w>0inputSize[4]/outputSize[2]alignCorners=falsescale\_w =\begin{cases} (inputSize[4]-1) / (outputSize[2]-1) & alignCorners=true \\ 1 / scales\_w & alignCorners=false\&scales\_w>0\\ inputSize[4] / outputSize[2] & alignCorners=false \end{cases}

      Therefore, for a point p(x,y,z) in a certain direction of the output, the point mapped back to the original image is denoted as q(x',y',z'), and the relationship is as follows:

      x′={x∗scale_dalignCorners=trueMAX(0,(x+0.5)∗scale_d−0.5)alignCorners=falsex' =\begin{cases} x * scale\_d & alignCorners=true \\ MAX(0,{(x+0.5)*scale\_d-0.5}) & alignCorners=false \end{cases} y′={y∗scale_halignCorners=trueMAX(0,(y+0.5)∗scale_h−0.5)alignCorners=falsey' =\begin{cases} y * scale\_h & alignCorners=true \\ MAX(0,{(y+0.5)*scale\_h-0.5}) & alignCorners=false \end{cases} z′={z∗scale_walignCorners=trueMAX(0,(z+0.5)∗scale_w−0.5)alignCorners=falsez' =\begin{cases} z * scale\_w & alignCorners=true \\ MAX(0,{(z+0.5)*scale\_w-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} z0=int(z′),z1=int(z′)+1,lambdc0=z1−z′,lambdc1=1−lambdc0z_{0} =int(z'),z_{1} =int(z')+1, lambdc_{0} = z_{1}-z', lambdc_{1} = 1-lambdc_{0}
      • Then the following formula applies:

        V(px,y,z)=V(px0,y0,z0)∗lambda0∗lambdb0∗lambdc0+V(px0,y0,z1)∗lambda0∗lambdb0∗lambdc1+V(px0,y1,z0)∗lambda0∗lambdb1∗lambdc0+V(px0,y1,z1)∗lambda0∗lambdb1∗lambdc1+V(px1,y0,z0)∗lambda1∗lambdb0∗lambdc0+V(px1,y0,z1)∗lambda1∗lambdb0∗lambdc1+V(px1,y1,z0)∗lambda1∗lambdb1∗lambdc0+V(px1,y1,z1)∗lambda1∗lambdb1∗lambdc1{V(p_{x, y, z})} = {V(p_{x0, y0, z0})} * {lambda_{0}} * {lambdb_{0}} * {lambdc_{0}} + {V(p_{x0, y0, z1})} * {lambda_{0}} * {lambdb_{0}} * {lambdc_{1}} + {V(p_{x0, y1, z0})} * {lambda_{0}} * {lambdb_{1}} * {lambdc_{0}} + {V(p_{x0, y1, z1})} * {lambda_{0}} * {lambdb_{1}} * {lambdc_{1}} + {V(p_{x1, y0, z0})} * {lambda_{1}} * {lambdb_{0}} * {lambdc_{0}} + {V(p_{x1, y0, z1})} * {lambda_{1}} * {lambdb_{0}} * {lambdc_{1}} + {V(p_{x1, y1, z0})} * {lambda_{1}} * {lambdb_{1}} * {lambdc_{0}} + {V(p_{x1, y1, z1})} * {lambda_{1}} * {lambdb_{1}} * {lambdc_{1}}
      • Assumption: The output image out (x,y,z)(x, y, z) of forward interpolation is affected by the original image input (xi,yj,zk)(x_i, y_j, z_k). Then:

        gradInput(xi,yj,zk)+=gradOut(x,y,z)∗lambda(xi,yj,zk)∗lambdb(xi,yj,zk)∗lambdc(xi,yj,zk)gradInput(x_i,y_j,z_k) += gradOut(x,y,z) * lambda(x_i,y_j,z_k)* lambdb(x_i,y_j,z_k)* lambdc(x_i,y_j,z_k)

Function Prototype

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

aclnnStatus aclnnUpsampleTrilinear3dBackwardGetWorkspaceSize(
  const aclTensor   *gradOut,
  const aclIntArray *outputSize,
  const aclIntArray *inputSize,
  bool               alignCorners,
  double             scalesD,
  double             scalesH,
  double             scalesW,
  aclTensor         *gradInput,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnUpsampleTrilinear3dBackward(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnUpsampleTrilinear3dBackwardGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gradOut (aclTensor*) Input Represents the gradient tensor of backward computation, corresponding to `gradOut` in the formula.
    • Empty tensors are not supported.
    • When the data format is ND, it is processed in NCDHW format by default.
    FLOAT32, FLOAT16, BFLOAT16, DOUBLE NCDHW, NDHWC, ND 5 √
    outputSize (aclIntArray*) Input Represents the dimension-wise spatial size of the input `gradOut` in D, H, and W, corresponding to `outputSize` in the formula. size is 3, and all elements are greater than zero. INT64 - - -
    inputSize (aclIntArray*) Input Represents the dimension-wise spatial size of the output `gradInput` in N, C, D, H, and W, corresponding to `inputSize` in the formula. size is 5, and all of the last three elements are greater than zero. INT64 - - -
    alignCorners (bool) Input Represents whether corner pixels are aligned, corresponding to `alignCorners` in the formula. If true, the corner pixels of the input and output tensors are aligned. Otherwise, they are not aligned. - - - -
    scalesD (double) Input Represents the depth dimension multiplier of output `gradInput`, corresponding to `scales_d` in the formula. - - - - -
    scalesH (double) Input Represents the dimension multiplier of the height dimension of the output `gradInput`, corresponding to `scales_h` in the formula. - - - - -
    scalesW (double) Input Represents the dimension multiplier of the width dimension of the output `gradInput`, corresponding to `scales_w` in the formula. - - - - -
    gradInput (aclTensor*) Output Represents the output tensor of the backward computation, corresponding to `gradInput` in the formula.
    • Empty tensors are not supported.
    • The dimension-wise shape sizes in N, C, D, H, and W must be the same as the spatial sizes of N, C, D, H, and W specified in `inputSize`.
    • The data type, data format, and shape must be consistent with the input parameter `gradOut`.
    FLOAT32, FLOAT16, BFLOAT16, DOUBLE NCDHW, NDHWC, ND 5 √
    workspaceSize (uint64_t*) Output Returns the size of the Device side-applied workspace. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas training products:

      The data types of parameters gradOut and gradInput 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 gradInput is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of gradOut or the data format is not in the supported range.
    The data type of gradOut is inconsistent with that of gradInput.
    The dimension of gradOut is not 5.
    The size of outputSize is not 3.
    An element value of outputSize is not greater than 0.
    The size of inputSize is not 5.
    An element value of the last three elements of inputSize is not greater than 0.
    The N and C dimension-wise sizes of gradOut are different from those of inputSize.
    The D, H, and W dimension-wise sizes of gradOut are inconsistent with outputSize[0], outputSize[1], and outputSize[2].
    The shape of gradInput is inconsistent with inputSize[0], inputSize[1], inputSize[2], inputSize[3], and inputSize[4].

aclnnUpsampleTrilinear3dBackward

  • Parameters

    Parameter Input/Output Description
    workspace Input Memory address of the workspace side-applied on the Device.
    workspaceSize Input Size of the workspace side-applied on the Device, obtained by calling the first-phase API aclnnUpsampleTrilinear3dBackwardGetWorkspaceSize.
    executor Input Op executor, which contains the computation process of the operator.
    stream Input Stream used to execute the task.
  • Return Value

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

Constraints

  • Shape constraints for parameters gradOut and gradInput:

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

    • The N and C axes of parameter gradInput are the same as those of gradOut.

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

      N∗C∗(gradOut_D∗gradOut_H∗gradOut_W+gradInput_D∗gradInput_H∗gradInput_W+gradOut_D∗gradOut_H∗gradInput_W+gradOut_D∗gradInput_H∗gradInput_W)∗sizeof(dtype)<60∗1024∗1024∗1024N * C * (gradOut\_D * gradOut\_H * gradOut\_W + gradInput\_D * gradInput\_H * gradInput\_W + gradOut\_D * gradOut\_H * gradInput\_W + gradOut\_D * gradInput\_H * gradInput\_W) * 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_D * gradOut_H < 2^31

    • gradInput_W * gradInput_H < 2^31

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

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

    • aclnnUpsampleTrilinear3dBackward defaults to a deterministic implementation.

Example

The following sample code is for reference only. For the compilation and execution procedure, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_upsample_trilinear_3d_backward.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 code, 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);

    // 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 the aclCreateTensor API 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.
    // Set 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 input and output. Custom construction is required based on the API.
    std::vector<int64_t> gradOutShape = {2, 2, 2, 2, 2};
    std::vector<int64_t> gradInputShape = {2, 2, 1, 1, 1};
    void* gradOutDeviceAddr = nullptr;
    void* gradInputDeviceAddr = nullptr;
    aclTensor* gradOut = nullptr;
    aclTensor* gradInput = nullptr;
    std::vector<float> gradOutHostData = {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};
    std::vector<float> gradInputHostData = {2.0, 2, 2, 2};
    std::vector<int64_t> outputSizeData = {2, 2, 2};
    std::vector<int64_t> inputSizeData = {2, 2, 1, 1, 1};
    bool alignCorners = false;
    double scalesD = 0.0;
    double scalesH = 0.0;
    double scalesW = 0.0;
    // Create gradOut aclTensor.
    ret = CreateAclTensor(gradOutHostData, gradOutShape, &gradOutDeviceAddr, aclDataType::ACL_FLOAT, &gradOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create gradInput aclTensor.
    ret = CreateAclTensor(gradInputHostData, gradInputShape, &gradInputDeviceAddr, aclDataType::ACL_FLOAT, &gradInput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

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

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

    // 3. Call the CANN operator library API. Modify it to the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnUpsampleTrilinear3dBackward.
    ret = aclnnUpsampleTrilinear3dBackwardGetWorkspaceSize(gradOut, outputSize, inputSize, alignCorners, scalesD,
                                                           scalesH, scalesW, gradInput, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS,
              LOG_PRINT("aclnnUpsampleTrilinear3dBackwardGetWorkspaceSize 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 aclnnUpsampleTrilinear3dBackward.
    ret = aclnnUpsampleTrilinear3dBackward(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleTrilinear3dBackward failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Wait synchronously for 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 device memory to host memory. Modify the code based on the specific API definition.
    auto size = GetShapeSize(gradInputShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), gradInputDeviceAddr,
                      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. Modify the code based on the specific API definition.
    aclDestroyTensor(gradOut);
    aclDestroyTensor(gradInput);

    // 7. Release device resources. Modify the code based on the specific API definition.
    aclrtFree(gradOutDeviceAddr);
    aclrtFree(gradInputDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}