aclnnExpSegsum

๐Ÿ“„ View Source Code

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DTNot supported
Atlas A3 training products/Atlas A3 inference productsSupported
Atlas A2 training products/Atlas A2 inference productsSupported
Atlas 200I/500 A2 inference productsNot supported
Atlas inference productsNot supported
Atlas training productsNot supported

Function

  • Description: Performs segment sum computation. Generates a semi-separable matrix with zeros on the diagonal and -inf in the upper triangle.

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

    1. The input self is expanded from (N1, N2, N3, N4) to (N1, N2, N3, N4, 1).

    2. Broadcasting is performed to obtain (N1, N2, N3, N4, N4).

    3. 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.

    4. Fill the elements in self that correspond to positions where the value in matrix A is True with 0.

      selfi={selfi,Ai==False0,Ai==Trueself_i= \begin{cases}self_i,\quad A_i==False \\0, \quad A_i==True \end{cases}
    5. Perform cumsum accumulation along the second-to-last dimension of self. For an element from the dimensional perspective (with other dimension indices unchanged and the current dimension index increasing sequentially), selfTempiselfTemp_{i} is the element at the corresponding position in the output tensor.

      selfTempi=self1+self2+self3+......+selfiselfTemp_{i} = self_{1} + self_{2} + self_{3} + ...... + self_{i}
    6. 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 False.

    7. Fill the elements in selfTemp that correspond to positions where the value in matrix B is True with -inf.

      outi={selfTempi,Bi==Falseโˆ’inf,Bi==Trueout_i= \begin{cases}selfTemp_i,\quad B_i==False \\-inf, \quad B_i==True \end{cases}
    8. Calculate the exponential of each element in selfTemp.

      outi=eselfTempiout_i=e^{selfTemp_i}

Function Prototype

Each operator is divided into a two-phase API. You must first call the "aclnnExpSegsumGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow, and then call the "aclnnExpSegsum" API to perform the computation.

aclnnStatus aclnnExpSegsumGetWorkspaceSize(
  const aclTensor   *self,
  aclTensor         *out,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnExpSegsum(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnExpSegsumGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data type Data format Dimension (shape) Non-contiguous tensor
    self Input The input for segmentation and computation, corresponding to `self` in the formula.
    • Supports empty tensors.
    • When the last axis is too large, the output occupies excessive memory. For example, when the last axis of the input is N, the output memory usage is N times that of the input.
    FLOAT16, FLOAT32, BFLOAT16 ND 3-4 Supported
    out Output Output after segmentation and computation, corresponding to `out` in the formula.
    • Supports empty tensors.
    • The data type is the same as that of the input `self`.
    • The output dimension must be one greater than the input dimension.
      • When the input `self` is 3D, the first three dimensions of the output are the same as those of `self`, and the last dimension is the same as the third dimension.
      • When the input `self` is 4D, the first four dimensions of the output are the same as those of `self`, and the last dimension is the same as the fourth dimension.
    FLOAT16, FLOAT32, BFLOAT16 ND 4-5 Supported
    workspaceSize Output Returns the workspace size to be allocated 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 Indicates that self or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self or out is not within the supported range.
    The shape of self or out does not meet the parameter requirements.

aclnnExpSegsum

  • Parameters:

    Parameter Input/Output Description
    workspace Input The workspace memory address applied for on the Device side.
    workspaceSize Input Size of the workspace requested on the Device side, obtained by the first-phase API aclnnExpSegsumGetWorkspaceSize.
    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:

    • aclnnExpSegsum 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_segsum.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: 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 apply for 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 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);

    // 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 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 your 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. You need to customize the construction based on the API interface.
    std::vector<int64_t> selfShape = {1, 1, 1, 4};
    std::vector<int64_t> outShape = {1, 1, 1, 4, 4};
    void* selfDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* self = nullptr;
    aclTensor* out = nullptr;
    std::vector<float> selfHostData = {0, 1, 2, 3};
    std::vector<int64_t> outputSizeHostData = {16};
    std::vector<float> outHostData(16, 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);
    // 3. Call the CANN operator library API. Replace with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnExpSegsum.
    ret = aclnnExpSegsumGetWorkspaceSize(self, out, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnExpSegsumGetWorkspaceSize 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 aclnnExpSegsum.
    ret = aclnnExpSegsum(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnExpSegsum failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Synchronize and 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 side memory to the host side. Modify 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(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(self);
    aclDestroyTensor(out);

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