aclnnExpSegsum
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: Performs segment sum computation. Generates a half-separable matrix where the diagonal is 1 and the upper triangle is 0.
Formula (using 4D input as an example):
The input self is expanded from (N1, N2, N3, N4) to (N1, N2, N3, N4, 1).
Broadcasting is performed to obtain (N1, N2, N3, N4, N4).
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.
Fill the elements in self that correspond to positions where the value in matrix A is True with 0.
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), is the element at the corresponding position in the output tensor.
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.
Fill the elements in selfTemp that correspond to positions where the value in matrix B is True with -inf.
Calculate the exponential of each element in selfTemp.
Function Prototype
Each operator uses a two-phase API. Call the "aclnnExpSegsumGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the operator computation process, 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 Input for the segment sum computation, corresponding to `self` in the formula. - Empty tensors are supported.
- An excessively large trailing dimension leads to large output space usage. For example, if the trailing dimension of the input is N, the output memory usage is N times that of the input.
FLOAT16, FLOAT32, BFLOAT16 ND 3-4 √ out Output Output of the segment sum computation, corresponding to `out` in the formula. - Supports empty tensors.
- The data type is the same as that of input `self`.
- The output dimension must be 1 greater than the input dimension.
- When the input `self` is 3D, the sizes of the dimensions of the first 3 dimensions of the output are the same as those of `self`, and the size of the dimension of the last dimension is the same as that of the 3rd dimension.
- When the input `self` is 4D, the sizes of the dimensions of the first 4 dimensions of the output are the same as those of `self`, and the size of the dimension of the last dimension is the same as that of the 4th dimension.
FLOAT16, FLOAT32, BFLOAT16 ND 4-5 √ workspaceSize Output Returns the size of the Device-side-applied workspace. - - - - - 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 self or out is a null pointer, or workspaceSize or executor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of self and out are not within the supported range. The shapes of self and out do not meet the parameter requirements. The formats of self and out are not ND.
aclnnExpSegsum
Parameters:
Parameter Input/Output Description workspace Input Memory address of the workspace side-applied on the Device. workspaceSize Input Size of the workspace side-applied on the Device, obtained by calling the first-phase API aclnnExpSegsumGetWorkspaceSize. executor Input Op executor that contains the operator computation process. stream Input Stream where the task is executed. Return value:
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation:
- aclnnExpSegsum defaults to a deterministic implementation.
Example
The following 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_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 allocate 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 device/stream. For details, see the acl API manual.
// Fill in deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle check as required.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct inputs and outputs. Customize the construction based on the API.
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 it 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 using 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 aclnnExpSegsum.
ret = aclnnExpSegsum(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnExpSegsum failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronously wait for the task 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 device-side memory to host-side memory. Modify it according to 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 it according to the specific API definition.
aclDestroyTensor(self);
aclDestroyTensor(out);
// 7. Release device resources. Modify it according to the specific API definition.
aclrtFree(selfDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}