aclnnUpsampleNearest1dBackward

📄 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 aclnnUpsampleNearest1dV2.

  • Formula:

    For input gradOut(N, C, l), for any point (N, C, L) on output gradInput, the following applies:

    gradInput(N,C,L)=∑h=srcLsrcLUp−1gradOut(N,C,l)gradInput(N, C, L) = \sum_{h = srcL}^{srcLUp - 1}gradOut(N, C, l)

    Where:

    scalesL=outputSize[0]/inputSize[2]scalesL = outputSize[0]/inputSize[2] srcL=Min(ceil(scalesL∗L),outputSize[0])srcL = Min(ceil(scalesL * L), outputSize[0]) srcLUp=Min(ceil(scalesL∗(L+1)),outputSize[0])srcLUp = Min(ceil(scalesL * (L + 1)), outputSize[0])

Function Prototype

Each operator uses a two-phase API. First call "aclnnUpsampleNearest1dBackwardGetWorkspaceSize" to obtain the input parameters and calculate the required workspace size based on the computation process. Then call "aclnnUpsampleNearest1dBackward" to perform the computation.

aclnnStatus aclnnUpsampleNearest1dBackwardGetWorkspaceSize(
  const aclTensor   *gradOut,
  const aclIntArray *outputSize,
  const aclIntArray *inputSize,
  double             scales,
  aclTensor         *out,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnUpsampleNearest1dBackward(
  void          *workspace,
  uint64_t       workspace_size,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnUpsampleNearest1dBackwardGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gradOut (aclTensor*) Input Gradient tensor for the backward computation. Corresponds to 'gradOut' in the formula.
    • The L axis does not support empty tensors.
    • If the data format is ND, it is processed as NCL by default.
    • The input must be 3-dimensional.
    FLOAT32, FLOAT16, BFLOAT16, DOUBLE NCL, ND 3 √
    outputSize (aclIntArray*) Input Spatial size of the input `gradOut` in the L dimension. The size is 1 and the value is greater than 0. INT64 - - -
    inputSize (aclIntArray*) Input Spatial sizes of output `out` in the N, C, and L dimensions respectively. The size is 3 and the value of the third element is greater than 0. INT64 - - -
    scales (double) Input Represents the multiplier of the L dimension of output `out`, corresponding to 'scales' in the formula. - - - - -
    out (aclTensor*) Output Indicates the output tensor of backward propagation, corresponding to 'out' in the formula.
    • Empty tensor is not supported in the L dimension.
    • The data type is the same as `gradOut`.
    • The input must be 3-dimensional.
    FLOAT32, FLOAT16, BFLOAT16, DOUBLE NCL, ND 3 √
    workspaceSize (uint64_t*) Output Returns the workspace size applied by the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - -
    • Atlas inference products, Atlas training products: The data types of input parameter gradOut and output parameter out support only FLOAT16.
  • 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 If a parameter is a required input, output, or required attribute and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002
    The data type of gradOut is not within the supported range.
    The data types of gradOut and out are inconsistent.
    The dimension of gradOut is not 3.
    The size of outputSize is not 1.
    The value of an element in outputSize is less than 1.
    The size of inputSize is not 3.
    The size of gradOut in the L dimension is different from outputSize[0].
    The dimension sizes of gradOut and out are not equal on the N/C axes.

aclnnUpsampleNearest1dBackward

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied by the Device.
    workspace_size Input Size of the workspace applied by the Device. Obtained by the first-phase API aclnnUpsampleNearest1dBackwardGetWorkspaceSize.
    executor Input Operator executor. Contains the operator computation flow.
    stream Input Specifies the Stream for task execution.
  • Return Value

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

Constraints

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

    outputSize=floor(inputSize_L∗scales)outputSize = floor(inputSize\_L * scales)
  • Deterministic computation:

    • aclnnUpsampleNearest1dBackward defaults to a deterministic implementation.

Example

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

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

    // 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_NCL,
                              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);
    CHECK_RET(ret == ACL_SUCCESS, 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> selfShape = {1, 1, 2};
    std::vector<int64_t> outShape = {1, 1, 3};
    void* selfDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* self = nullptr;
    aclTensor* out = nullptr;
    std::vector<float> selfHostData = {1, 4.1};
    std::vector<float> outHostData = {0, 0, 0};
    double scales = 1.1;

    // 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 = {2};
    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};
    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 specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnUpsampleNearest1dBackward.
    ret = aclnnUpsampleNearest1dBackwardGetWorkspaceSize(self, outputSize, inputSize, scales, out, &workspaceSize,
                                                         &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleNearest1dBackwardGetWorkspaceSize 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 aclnnUpsampleNearest1dBackward.
    ret = aclnnUpsampleNearest1dBackward(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleNearest1dBackward 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 value. Copy the result in device memory to the host. 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 aclScalar. Modify it based on the specific API definition.
    aclDestroyTensor(self);
    aclDestroyTensor(out);
    aclDestroyIntArray(outputSize);
    aclDestroyIntArray(inputSize);

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