aclnnExpSegsum

📄 View source code

Supported Products

ProductSupported
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: Performs segmentation and computation to generate a semi-separable matrix with a zero diagonal and an upper triangle being -inf.

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

    1. Reshape self from (N1, N2, N3, N4) to (N1, N2, N3, N4, 1).
    2. Perform broadcasting obtain (N1, N2, N3, N4, N4).
    3. Generate a BOOL triangular matrix A of shape (N4, N4), where the upper triangle is True, the lower triangle is False, and the diagonal is True.
    4. Fill the elements in self with 0 at the positions where the corresponding elements in matrix A are True.
    selfi={selfi,Ai==False0,Ai==Trueself_i= \begin{cases}self_i,\quad A_i==False \\0, \quad A_i==True \end{cases}
    1. Perform a cumulative sum along the second-to-last dimension of self. For an element from a dimensional perspective, other dimension indices remain unchanged while the current index increases. selfTemp_iselfTemp\_{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}
    2. Generate a BOOL triangular matrix B of shape (N4, N4), where the upper triangle is True, the lower triangle is False, and the diagonal is False.

    3. Fill the elements in selfTemp with -inf at the positions where the corresponding elements in matrix B are True.

      outi={selfTempi,Bi==False−inf,Bi==Trueout_i= \begin{cases}selfTemp_i,\quad B_i==False \\-inf, \quad B_i==True \end{cases}
    4. Compute the exponent of each element in selfTemp.

      outi=eselfTempiout_i=e^{selfTemp_i}

Prototype

Each operator has two-phase API calls. First, aclnnExpSegsumGetWorkspaceSize is called to obtain the workspace size required for computation and the executor that contains the operator computation process. Then, aclnnExpSegsum is called to perform 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:

    Name Input/Output Description Usage Notes Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    self Input Input for segmentation and computation, corresponding to self in the formula.
    • Empty tensors are supported.
    • If the last axis is too large, the output will occupy excessive space. For example, if the last axis of the input is N, the output memory will be N times that of the input.
    FLOAT16, FLOAT32, BFLOAT16 ND 3–4 √
    out Output Output after segmentation and computation, corresponding to out in the formula.
    • Empty tensors are supported.
    • The data type must be the same as that of self.
    • The output dimension must be one greater than the input dimension.
      • For a 3D input self, the sizes of the first three dimensions of the output remain the same as those of self, while the size of the last dimension matches the third dimension.
      • For a 4D input self, the sizes of the first four dimensions of the output remain the same as those of self, while the size of the last dimension matches the fourth dimension.
    FLOAT16, FLOAT32, BFLOAT16 ND 4–5 √
    workspaceSize Output Size of the workspace required to be allocated on the device. - - - - -
    executor Output Operator executor, containing the operator computation process. - - - - -
  • Returns:

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

    The first-phase API performs input parameter validation. The following errors may be returned:

    Return Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The passed self or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self or out is not supported.
    The shape of self or out does not meet the parameter requirements.

aclnnExpSegsum

  • Parameters:

    Name Input/Output Description
    workspace Input Memory address of the workspace to be allocated on the device.
    workspaceSize Input Size of the workspace to be allocated on the device, which is obtained by calling the first-phase API aclnnExpSegsumGetWorkspaceSize.
    executor Input Operator executor, containing the operator computation process.
    stream Input Stream for executing the task.
  • Returns:

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

Constraints

  • Deterministic computation:
    • aclnnExpSegsum defaults to a deterministic implementation.

Calling Example

The following example is for reference only. For details, see Compilation and Running Sample.

#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) Initialize resources.
    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 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 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 and stream. For details, see the ACL API manual.
    // Set the device ID based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Perform the check as required.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct inputs and outputs based on the API definition.
    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 a self aclTensor.
    ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create an 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, which needs to be replaced with the actual 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 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) Wait until the task execution is 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. Modify the code based on the 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. Destroy aclTensor. Modify the code based on the API definition.
    aclDestroyTensor(self);
    aclDestroyTensor(out);

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