aclnnExpSegsumBackward

📄 View Source Code

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DT×
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products×
Atlas training products×

Function

  • Description: Backward computation of aclnnExpSegsum.

  • Formula (using 5D input as an example):

    1. Multiply the input gradOutput (N1, N2, N3, N4, N4) by the input gradSelf (the forward output).

      $$ out\_mul = gradOutput * gradSelf $$
    2. Generate a triangular matrix A of shape (N4, N4) with bool type, where the upper triangle is True, the lower triangle is False, and the diagonal is True.

    3. Fill the elements in the input $out\_mul$ that correspond to positions where the value in matrix A is True with 0.

      $$ out\_mul_i= \begin{cases}out\_mul_i,\quad A_i==False \\0, \quad A_i==True \end{cases} $$
    4. Reverse the penultimate dimension of out_mul to generate out_flip.

    5. Perform cumulative sum along the penultimate dimension of $out\_flip$. From a dimensional perspective, for an element (with other dimension indices unchanged and the current dimension index increasing sequentially), $out\_cumsum\_{i}$ is the element at the corresponding position in the output tensor.

      $$ out\_cumsum_{i} = out\_flip_{1} + out\_flip_{2} + out\_flip_{3} + ...... + out\_flip_{i} $$
    6. Reverse the -2 dimension of $out\_cumsum$ to generate out_flip2.

    7. Generate a triangular matrix B of shape (N4, N4) with bool type, where the upper triangle is True, the lower triangle is False, and the diagonal is True.

    8. Fill the elements in $out\_flip2$ corresponding to the positions where the value is True in matrix B with 0.

      $$ out\_flip2_i= \begin{cases}out\_flip2_i,\quad B_i==False \\0, \quad B_i==True \end{cases} $$
    9. Return gradInput as the sum of each row in the last dimension of out_flip2.

Function Prototype

Each operator is divided into a two-phase API. You must first call the "aclnnExpSegsumBackwardGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnExpSegsumBackward" API to perform the computation.

aclnnStatus aclnnExpSegsumBackwardGetWorkspaceSize(
  const aclTensor*     gradOutput,
  const aclTensor*     gradSelf,
  aclTensor           *gradInput,
  uint64_t            *workspaceSize,
  aclOpExecutor      **executor)
aclnnStatus aclnnExpSegsumBackward(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnExpSegsumBackwardGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gradOutput Input Gradient for backward computation. Corresponds to `gradOutput` in the formula.
    • Supports null tensor.
    • The last two dimensions of the shape have the same size.
    FLOAT32, FLOAT16, BFLOAT16 ND 4-5 √
    gradSelf Input Represents the output of the forward computation. Corresponds to `gradSelf` in the formula.
    • Supports null Tensor.
    • The shape and data type are consistent with the input `gradOutput`.
    FLOAT32, FLOAT16, BFLOAT16 ND 4-5 √
    gradInput Input Represents the output of the backward computation. Corresponds to `gradInput` in the formula.
    • Supports null tensor.
    • The data type is the same as the input `gradOutput`.
    • The output dimension must be one dimension fewer than the input dimension, supporting 3D or 4D. When the input `gradOutput` is 4D, the output dimension size is the same as the first three dimensions of `gradOutput`. When the input `gradOutput` is 5D, the output dimension size is the same as the first four dimensions of `gradOutput`.
    FLOAT32, FLOAT16, BFLOAT16 ND 3-4 √
    workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - -
    executor Output Returns the operator executor, which contains the operator computation flow. - - - - -
  • Return value:

    aclnnStatus: return code. For details, see aclnn Return Codes.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The passed gradOutput, gradSelf, or gradInput is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of gradOutput, gradSelf, or gradInput is not within the supported range.
    The shape and data type of gradOutput, gradSelf, and gradInput do not meet the parameter requirements.

aclnnExpSegsumBackward

  • Parameters:

    Parameter Input/Output Description
    workspace Input Address of the workspace memory requested on the Device side.
    workspaceSize Input Size of the workspace requested on the Device side, obtained through the first-phase API aclnnExpSegsumBackwardGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Specifies the stream for executing the task.
  • Return value

    aclnnStatus: return code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation:

    • aclnnExpSegsumBackward defaults to a deterministic implementation.

Example

The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_exp_segsum_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 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 request memory on the device side.
    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 side 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);

    // Compute the strides of a 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_ND, shape.data(), shape.size(),
        *deviceAddr);
    return 0;
}

int main()
{
    // 1. (Boilerplate) Initialize the device/stream. See the ACL API manual.
    // Enter the deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check based on your requirements.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the input and output. Customize the construction based on the API.
    void* gradOutputDeviceAddr = nullptr;
    void* gradSelfDeviceAddr = nullptr;
    void* gradInputDeviceAddr = nullptr;
    aclTensor* gradOutput = nullptr;
    aclTensor* gradSelf = nullptr;
    aclTensor* gradInput = nullptr;
    std::vector<int64_t> gradOutputShape = {1, 1, 1, 4, 4};
    std::vector<int64_t> gradSelfShape = {1, 1, 1, 4, 4};
    std::vector<int64_t> gradInputShape = {1, 1, 1, 4};
    std::vector<float> gradOutputHostData(16, 1);
    std::vector<float> gradSelfHostData(16, 1);
    std::vector<float> gradInputHostData(4, 0);

    // Create the input aclTensor.
    ret = CreateAclTensor(
        gradOutputHostData, gradOutputShape, &gradOutputDeviceAddr, aclDataType::ACL_FLOAT, &gradOutput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradSelfHostData, gradSelfShape, &gradSelfDeviceAddr, aclDataType::ACL_FLOAT, &gradSelf);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the output aclTensor.
    ret = CreateAclTensor(gradInputHostData, gradInputShape, &gradInputDeviceAddr, aclDataType::ACL_FLOAT, &gradInput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // 3. Call the CANN operator library API. Replace with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnExpSegsumBackward.
    ret = aclnnExpSegsumBackwardGetWorkspaceSize(gradOutput, gradSelf, gradInput, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnExpSegsumBackwardGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);
    // Apply for 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 aclnnExpSegsumBackward.
    ret = aclnnExpSegsumBackward(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnExpSegsumBackward failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Synchronously wait 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 value and copy the result from the device memory to the host side. Modify 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. Modify based on the specific API definition.
    aclDestroyTensor(gradOutput);
    aclDestroyTensor(gradSelf);
    aclDestroyTensor(gradInput);

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