aclnnExpSegsumBackward

📄 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: Not supported
  • Atlas training products: Not supported

Function

  • Description: Backward calculation 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∗gradSelfout\_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_mulout\_mul that correspond to positions where the value in matrix A is True with 0.out_muli={out_muli,Ai==False0,Ai==Trueout\_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_flipout\_flip. From a dimensional perspective, for an element (with other dimension indices unchanged and the current dimension index increasing sequentially), out_cumsum_iout\_cumsum\_{i} is the element at the corresponding position in the output tensor.out_cumsumi=out_flip1+out_flip2+out_flip3+......+out_flipiout\_cumsum_{i} = out\_flip_{1} + out\_flip_{2} + out\_flip_{3} + ...... + out\_flip_{i}
    6. Reverse the -2 dimension of out_cumsumout\_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_flip2out\_flip2 corresponding to the positions where the value is True in matrix B with 0.out_flip2i={out_flip2i,Bi==False0,Bi==Trueout\_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 uses a two-phase API. First call the "aclnnExpSegsumBackwardGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the computation process of the operator. 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 Indicates the gradient for backward computation. Corresponds to `gradOutput` in the formula.
    • Supports empty tensors.
    • The last two dimensions of the shape have the same size.
    FLOAT32, FLOAT16, BFLOAT16 ND 4-5 √
    gradSelf Input Indicates the output of forward computation. Corresponds to `gradSelf` in the formula.
    • Supports empty tensors.
    • The shape and data type must be the same as those of the input `gradOutput`.
    FLOAT32, FLOAT16, BFLOAT16 ND 4-5 √
    gradInput Input Represents the output of backward computation. Corresponds to `gradInput` in the corresponding formula.
    • Supports empty tensors.
    • The data type must be the same as that of the input `gradOutput`.
    • The output must have one fewer dimension than the input. Supports 3D or 4D. If the input `gradOutput` is 4D, the output dimensions are the same as the first 3 dimensions of `gradOutput`. If the input `gradOutput` is 5D, the output dimensions are the same as the first 4 dimensions of `gradOutput`.
    FLOAT32, FLOAT16, BFLOAT16 ND 3-4 √
    workspaceSize Output Returns the workspace size to be allocated on the Device. - - - - -
    executor Output Returns the op executor that contains the operator computation flow. - - - - -
  • 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 gradOutput, gradSelf, or gradInput is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of gradOutput, gradSelf, and gradInput are not within the supported range.
    The shapes and data types of gradOutput, gradSelf, and gradInput do not meet the parameter requirements.

aclnnExpSegsumBackward

  • 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 the first-phase API aclnnExpSegsumBackwardGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Specifies the Stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation: aclnnExpSegsumBackward defaults to a deterministic implementation.

Example

The 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_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 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_ND, shape.data(), shape.size(),
        *deviceAddr);
    return 0;
}

int main()
{
    // 1. (Boilerplate) Initialize the 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);
    // Process the check as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct inputs and outputs. Custom construction is required 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 out 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 it with the actual 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);
    // 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 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 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 and copy the result from the device side to the host side. 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. Modify the code based on the specific API definition.
    aclDestroyTensor(gradOutput);
    aclDestroyTensor(gradSelf);
    aclDestroyTensor(gradInput);

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