aclnnMhcPostBackward
Applicable Products
Ascend 950PR&950DT products : 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: mhc_post performs Post Mapping on the previous layer output $h_{t}^{out}$ in the MHC (Manifold-Constrained Hyper-Connection) architecture through a series of computations, performs ResMapping on the previous layer input $x_j$, and then performs residual connection on the two to obtain the next layer input $x_{l+1}$. This operator implements the backward function of the preceding process.
Formula:
When hRes is passed (hRes is not nullptr):
$ grad\_x = H_{l}^{res} \times grad\_output\\ grad\_h\_res = x_{l} \times {grad\_output}^{T} $ $ grad\_h\_out=({grad\_output} * (H_{l}^{post}.unsqueeze(-1))).sum(dim=-2)\\ grad\_h\_post=({grad\_output} * (h_{l}^{out}.unsqueeze(-2))).sum(dim=-1) $When hRes is not passed (hRes is nullptr):
$ grad\_x = grad\_output $ $ grad\_h\_res = x_{l} \times {grad\_output}^{T} $ $ grad\_h\_out=({grad\_output} * (H_{l}^{post}.unsqueeze(-1))).sum(dim=-2)\\ grad\_h\_post=({grad\_output} * (h_{l}^{out}.unsqueeze(-2))).sum(dim=-1) $Note: hRes, as an optional parameter (which can be set to nullptr), is supported only on
Ascend 950PR&950DT products .
Function Prototype
The operator execution API is a two-phase API. You must first call the "aclnnMhcPostBackwardGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the computation process, and then call the "aclnnMhcPostBackward" API to perform the computation.
aclnnStatus aclnnMhcPostBackwardGetWorkspaceSize(
const aclTensor *gradOutput,
const aclTensor *x,
const aclTensor *hRes,
const aclTensor *hOut,
const aclTensor *hPost,
aclTensor *gradX,
aclTensor *gradHRes,
aclTensor *gradHOut,
aclTensor *gradHPost,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMhcPostBackward(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnMhcPostBackwardGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor gradOutput Input Data to be computed, indicating the input data of the MHC layer in the network. - Empty tensor not supported.
FLOAT16, BFLOAT16 ND [B,S,N,D], [T,N,D] √ x Input Data to be computed, indicating the input data of the MHC layer in the network. - Empty tensors not supported.
Data type is the same as gradOutput ND [B,S,N,D], [T,N,D] √ hRes Input hRes transformation matrix of MHC - Optional parameter. Set to nullptr if not passed.
- Empty tensors not supported.
FLOAT32 ND [B,S,N,N], [T,N,N] √ hOut Input Output of the Atten/MLP layer. - Empty tensor not supported.
Data type: same as gradOutput ND [B,S,D], [T,D] √ hPost Input hPost transformation matrix of MHC. - Empty Tensor Not Supported
Data type: same as hRes ND [B,S,N], [T,N] √ gradX Output Gradient of the MHC layer input data x in the network. - Same data type as gradOutput. ND [B,S,N,D], [T,N,D] √ gradHRes Output Gradient of the MHC layer input data hRes in the network. - Same data type as hRes. ND [B,S,N,N], [T,N,N] √ gradHOut Output Gradient of hOut, the layer input data of the MHC layer in network. - Same data type as hOut. ND [B,S,D], [T,D] √ gradHPost Output Gradient of h_post, the layer input data of the MHC layer in network. - Data type is the same as hPost. ND [B,S,N], [T,N] √ workspaceSize Output Returns the required Device Side-Applied workspace size. - - - - - executor Output Returns the op executor, which contains the operator computation process. - - - - - Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Value Error Codes Description ACLNN_ERR_PARAM_NULLPTR 161001 gradOutput, x, hRes, hOut, or hPost is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of gradOutput, x, hRes, hOut, and hPost are not within the supported range. The shape dimensions or values of gradOutput, x, hRes, hOut, and hPost are not within the supported range. The data types or shapes of gradOutput, x, hRes, hOut, and hPost do not match.
aclnnMhcPostBackward
Parameters:
Parameter Input/Output Description workspace Input Device Side-Applied workspace memory address. workspaceSize Input Device Side-Applied workspace size, obtained by the first-phase API aclnnMhcPostBackwardGetWorkspaceSize. executor Input Op executor that contains the operator computation process. stream Input Specifies the AscendCL stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Atlas A2 products andAtlas A3 products : In Parameters, dimension N currently supports only the value 4, and dimension D must be 128-aligned with a value range of [1,100000].
Ascend 950PR&950DT products : In Parameters, dimension N currently supports only the values 4, 6, and 8.
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 <cmath>
#include <cstring>
#include "acl/acl.h"
#include "aclnnop/aclnn_mhc_post_backward.h"
#include "securec.h"
using namespace std;
namespace {
#define CHECK_RET(cond) ((cond) ? true :(false))
#define LOG_PRINT(message, ...) \
do { \
printf(message, ##__VA_ARGS__); \
} while (0)
int64_t GetShapeSize(const std::vector<int64_t> &shape) {
int64_t shapeSize = 1;
for (auto i : shape) {
shapeSize *= i;
}
return shapeSize;
}
int Init(int32_t deviceId, aclrtStream *stream) {
// Fixed writing method, AscendCL initialization.
auto ret = aclInit(nullptr);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclInit failed. ERROR: %d\n", ret);
return ret;
}
ret = aclrtSetDevice(deviceId);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret);
return ret;
}
ret = aclrtCreateStream(stream);
if (!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 request device side memory.
auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
if (!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);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret);
return ret;
}
// Calculate the strides of continuous tensors.
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 interface to create aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
} // namespace
int main() {
// 1. (Fixed writing method) device/stream initialization. Refer to AscendCL's list of external interfaces.
// Fill in the deviceId based on your actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("Init acl failed. ERROR: %d\n", ret);
return ret;
}
LOG_PRINT("ACL environment initialized successfully!\n");
// 2. To construct input and output, it is necessary to customize the construction according to the API interface.
// Example: BSND format (B, S, n, D)
std::vector<int64_t> gradYShape = {1, 1024, 4, 5120}; // BSND
std::vector<int64_t> xShape = {1, 1024, 4, 5120}; // BSND
std::vector<int64_t> hResShape = {1, 1024, 4, 4}; // BSND
std::vector<int64_t> hOutShape = {1, 1024, 5120}; // BSD
std::vector<int64_t> hPostShape = {1, 1024, 4}; // BSn
std::vector<int64_t> gradXShape = {1, 1024, 4, 5120}; // BSND
std::vector<int64_t> gradHResShape = {1, 1024, 4, 4}; // BSND
std::vector<int64_t> gradHOutShape = {1, 1024, 5120}; // BSD
std::vector<int64_t> gradHPostShape = {1, 1024, 4}; // BSn
void *gradYDeviceAddr = nullptr;
void *xDeviceAddr = nullptr;
void *hResDeviceAddr = nullptr;
void *hOutDeviceAddr = nullptr;
void *hPostDeviceAddr = nullptr;
void *gradXDeviceAddr = nullptr;
void *gradHResDeviceAddr = nullptr;
void *gradHOutDeviceAddr = nullptr;
void *gradHPostDeviceAddr = nullptr;
aclTensor *gradYTensor = nullptr;
aclTensor *xTensor = nullptr;
aclTensor *hResTensor = nullptr;
aclTensor *hOutTensor = nullptr;
aclTensor *hPostTensor = nullptr;
aclTensor *gradXTensor = nullptr;
aclTensor *gradHResTensor = nullptr;
aclTensor *gradHOutTensor = nullptr;
aclTensor *gradHPostTensor = nullptr;
int64_t gradYShapeSize = GetShapeSize(gradYShape);
int64_t xShapeSize = GetShapeSize(xShape);
int64_t hResShapeSize = GetShapeSize(hResShape);
int64_t hOutShapeSize = GetShapeSize(hOutShape);
int64_t hPostShapeSize = GetShapeSize(hPostShape);
int64_t gradXShapeSize = GetShapeSize(gradXShape);
int64_t gradHResShapeSize = GetShapeSize(gradHResShape);
int64_t gradHOutShapeSize = GetShapeSize(gradHOutShape);
int64_t gradHPostShapeSize = GetShapeSize(gradHPostShape);
std::vector<aclFloat16> gradYHostData(gradYShapeSize, aclFloatToFloat16(1.0f));
std::vector<aclFloat16> xHostData(xShapeSize, aclFloatToFloat16(1.0f));
std::vector<float> hResHostData(hResShapeSize, 1.0f);
std::vector<aclFloat16> hOutHostData(hOutShapeSize, aclFloatToFloat16(1.0f));
std::vector<float> hPostHostData(hPostShapeSize, 1.0f);
std::vector<aclFloat16> gradXHostData(gradXShapeSize, aclFloatToFloat16(1.0f));
std::vector<float> gradHResHostData(gradHResShapeSize, 1.0f);
std::vector<aclFloat16> gradHOutHostData(gradHOutShapeSize, aclFloatToFloat16(1.0f));
std::vector<float> gradHPostHostData(gradHPostShapeSize, 1.0f);
ret = CreateAclTensor(gradYHostData, gradYShape, &gradYDeviceAddr, aclDataType::ACL_FLOAT16, &gradYTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &xTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create hRes aclTensor.
ret = CreateAclTensor(hResHostData, hResShape, &hResDeviceAddr, aclDataType::ACL_FLOAT, &hResTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create hOut aclTensor.
ret = CreateAclTensor(hOutHostData, hOutShape, &hOutDeviceAddr, aclDataType::ACL_FLOAT16, &hOutTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create hPost aclTensor.
ret = CreateAclTensor(hPostHostData, hPostShape, &hPostDeviceAddr, aclDataType::ACL_FLOAT, &hPostTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create gradX aclTensor.
ret = CreateAclTensor(gradXHostData, gradXShape, &gradXDeviceAddr, aclDataType::ACL_FLOAT16, &gradXTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create gradHRes aclTensor.
ret = CreateAclTensor(gradHResHostData, gradHResShape, &gradHResDeviceAddr, aclDataType::ACL_FLOAT, &gradHResTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create gradHOut aclTensor.
ret = CreateAclTensor(gradHOutHostData, gradHOutShape, &gradHOutDeviceAddr, aclDataType::ACL_FLOAT16, &gradHOutTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create gradHPost aclTensor.
ret = CreateAclTensor(gradHPostHostData, gradHPostShape, &gradHPostDeviceAddr, aclDataType::ACL_FLOAT, &gradHPostTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// 3. Call CANN operator library API.
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
// Call the first interface.
ret = aclnnMhcPostBackwardGetWorkspaceSize(
gradYTensor, xTensor, hResTensor, hOutTensor, hPostTensor, gradXTensor, gradHResTensor, gradHOutTensor,
gradHPostTensor, &workspaceSize, &executor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclnnMhcPostBackwardGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret;
}
// Allocate device memory based on the workspaceSize calculated from the first interface paragraph.
void *workspaceAddr = nullptr;
if (workspaceSize > 0U) {
ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret);
return ret;
}
}
// Call the second interface.
ret = aclnnMhcPostBackward(workspaceAddr, workspaceSize, executor, stream);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclnnMhcPostBackward failed. ERROR: %d\n", ret);
return ret;
}
// 4. (Fixed writing method) Synchronize and wait for task execution to end.
ret = aclrtSynchronizeStream(stream);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret);
return ret;
}
//gradX, gradHRes, gradHOut, gradHPost
// 5. Retrieve the output value, copy the gradX from the device side memory to the host side.
auto gradXsize = GetShapeSize(gradXShape);
std::vector<aclFloat16> gradXData(gradXsize, aclFloatToFloat16(0.0f));
ret = aclrtMemcpy(gradXData.data(), gradXData.size() * sizeof(gradXData[0]), gradXDeviceAddr,
gradXsize * sizeof(gradXData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("copy gradX from device to host failed. ERROR: %d\n", ret);
return ret;
}
auto gradHRessize = GetShapeSize(gradHResShape);
std::vector<float> gradHResData(gradHRessize, 0.0f);
ret = aclrtMemcpy(gradHResData.data(), gradHResData.size() * sizeof(gradHResData[0]), gradHResDeviceAddr,
gradHRessize * sizeof(gradHResData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("copy gradHRes from device to host failed. ERROR: %d\n", ret);
return ret;
}
auto gradHOutsize = GetShapeSize(gradHOutShape);
std::vector<aclFloat16> gradHOutData(gradHOutsize, aclFloatToFloat16(0.0f));
ret = aclrtMemcpy(gradHOutData.data(), gradHOutData.size() * sizeof(gradHOutData[0]), gradHOutDeviceAddr,
gradHOutsize * sizeof(gradHOutData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("copy gradHOut from device to host failed. ERROR: %d\n", ret);
return ret;
}
auto gradHPostsize = GetShapeSize(gradHPostShape);
std::vector<float> gradHPostData(gradHPostsize, 0.0f);
ret = aclrtMemcpy(gradHPostData.data(), gradHPostData.size() * sizeof(gradHPostData[0]), gradHPostDeviceAddr,
gradHPostsize * sizeof(gradHPostData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("copy gradHPost from device to host failed. ERROR: %d\n", ret);
return ret;
}
// 6. Release resources.
aclDestroyTensor(gradYTensor);
aclDestroyTensor(xTensor);
aclDestroyTensor(hResTensor);
aclDestroyTensor(hOutTensor);
aclDestroyTensor(hPostTensor);
aclDestroyTensor(gradXTensor);
aclDestroyTensor(gradHResTensor);
aclDestroyTensor(gradHOutTensor);
aclDestroyTensor(gradHPostTensor);
aclrtFree(gradYDeviceAddr);
aclrtFree(xDeviceAddr);
aclrtFree(hResDeviceAddr);
aclrtFree(hOutDeviceAddr);
aclrtFree(hPostDeviceAddr);
aclrtFree(gradXDeviceAddr);
aclrtFree(gradHResDeviceAddr);
aclrtFree(gradHOutDeviceAddr);
aclrtFree(gradHPostDeviceAddr);
if (workspaceSize > 0U) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}