aclnnExpSegsumBackward
Supported Products
| Product | Supported |
|---|---|
| √ | |
| √ | |
| × | |
| × | |
| × |
Function
Description: Performs backward pass of aclnnExpSegsum.
Formula (using 5D input as an example):
Multiply the input
gradOutputof shape (N1, N2, N3, N4, N4) with the inputgradSelf(forward output).Generate a BOOL triangular matrix A of shape (N4, N4), where the upper triangle is
True, the lower triangle isFalse, and the diagonal isTrue.Fill the elements in with
0at the positions where the corresponding elements in matrix A areTrue.Reverse the second-to-last dimension of
out_multo generateout_flip.Perform a cumulative sum along the second-to-last dimension of
$out\_flip$. For an element from a dimensional perspective, other dimension indices remain unchanged while the current index increases. is the element at the corresponding position in the output tensor.Reverse the second-to-last dimension of to generate
out_flip2.Generate a BOOL triangular matrix B of shape (N4, N4), where the upper triangle is
True, the lower triangle isFalse, and the diagonal isTrue.Fill the elements in with
0at the positions where the corresponding elements in matrix B areTrue.Return
gradInputas the sum of each row along the last dimension ofout\_flip2.
Prototype
Each operator has two-phase API calls. First, aclnnExpSegsumBackwardGetWorkspaceSize is called to obtain the workspace size required for computation and the executor that contains the operator computation process. Then, aclnnExpSegsumBackward is called to perform 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:
Name Input/Output Description Usage Notes Data Type Data Format Dimension (Shape) Non-contiguous Tensor gradOutput Input Gradient for backward pass. It corresponds to gradOutput in the formula. - Empty tensors are supported.
- The last two dimensions of the shape must have the same size.
FLOAT32, FLOAT16, BFLOAT16 ND 4–5 √ gradSelf Input Forward pass output. It corresponds to gradSelf in the formula. - Empty tensors are supported.
- The shape and data type are the same as those of gradOutput.
FLOAT32, FLOAT16, BFLOAT16 ND 4–5 √ gradInput Input Backward pass output. It corresponds to gradInput in the formula. - Empty tensors are supported.
- The data type must be the same as that of gradOutput.
- The output dimension must be one less than the input dimension. 3D or 4D is supported. 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 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 gradOutput, gradSelf, or gradInput is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of gradOutput, gradSelf, or gradInput is not supported. The shape and data type of gradOutput, gradSelf, or gradInput do not meet the parameter requirements.
aclnnExpSegsumBackward
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 aclnnExpSegsumBackwardGetWorkspaceSize. 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:
aclnnExpSegsumBackwarddefaults 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_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) 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.
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 an 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 an 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, which needs to be replaced 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 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 aclnnExpSegsumBackward.
ret = aclnnExpSegsumBackward(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnExpSegsumBackward 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(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. Destroy aclTensor. Modify the code based on the API definition.
aclDestroyTensor(gradOutput);
aclDestroyTensor(gradSelf);
aclDestroyTensor(gradInput);
// 7. Free device resources. Modify the code based on the API definition.
aclrtFree(gradOutputDeviceAddr);
aclrtFree(gradSelfDeviceAddr);
aclrtFree(gradInputDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}