aclnnBlockAttentionResidualsGrad
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:
BlockAttentionResidualsGradis the backward propagation operator of the forward operatorBlockAttentionResiduals(attention residual). Based on the invNorm and probs saved during forward propagation, the forward parameters projWeight and normWeight, and gradHiddenStates, this API computes the gradients of partialBlock, blockRes, projWeight, and normWeight. Only -1 is supported for validBlockNum; other values cause an error.Formula:
$$ g_{t,i} = \sum_{h=0}^{H-1} grad\_output_{t,h} \cdot v_{t,i,h} $$$$ grad\_score_{t,i} = probs_{t,i} \cdot \left(g_{t,i} - \sum_{j=0}^{N} probs_{t,j} \cdot g_{t,j}\right) $$$$ grad\_k_{t,i,h} = grad\_score_{t,i} \cdot score\_weight_{h} $$$$ grad\_score\_weight_{h} = \sum_{t=0}^{T-1} \sum_{i=0}^{N} grad\_score_{t,i} \cdot k_{t,i,h} $$$$ grad\_inv\_rms_{t,i} = \sum_{h=0}^{H-1} grad\_k_{t,i,h} \cdot v_{t,i,h} $$$$ grad\_v_{t,i,h} = grad\_output_{t,h} \cdot probs_{t,i} + grad\_k_{t,i,h} \cdot inv\_rms_{t,i} - \frac{grad\_inv\_rms_{t,i} \cdot inv\_rms_{t,i}^{3}}{H} \cdot v_{t,i,h} $$Where:
$$ grad\_block\_res_{t,i,h} = grad\_v_{t,i,h}, \quad i < N $$$$ grad\_partial\_block_{t,h} = grad\_v_{t,N,h} $$$$ grad\_norm\_weight_{h} = grad\_score\_weight_{h} \cdot proj\_weight_{0,h} $$$$ grad\_proj\_weight_{0,h} = grad\_score\_weight_{h} \cdot norm\_weight_{h} $$The current version directly uses the probs saved in the forward pass for backward computation and does not reconstruct the mask based on validBlockNum.
Function Prototype
Each operator uses a two-phase API. First, call the "aclnnBlockAttentionResidualsGradGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation flow, and then call the "aclnnBlockAttentionResidualsGrad" API to perform the computation.
aclnnStatus aclnnBlockAttentionResidualsGradGetWorkspaceSize(
const aclTensor *partialBlock,
const aclTensor *blockRes,
const aclTensor *projWeight,
const aclTensor *normWeight,
const aclTensor *gradHiddenStates,
const aclTensor *invNorm,
const aclTensor *probs,
int64_t validBlockNum,
const aclTensor *gradPartialBlock,
const aclTensor *gradBlockRes,
const aclTensor *gradProjWeight,
const aclTensor *gradNormWeight,
uint64_t *workspaceSize,
aclOpExecutor **executor);aclnnStatus aclnnBlockAttentionResidualsGrad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream);aclnnBlockAttentionResidualsGradGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format dimension (shape) Non-contiguous Tensor partialBlock (aclTensor*) Input Forward input prefix sum, corresponding to the (N+1)-th value in the formula. - Data type must remain consistent with the other inputs.
FLOAT16, BFLOAT16, FLOAT32 ND (T,H) √ blockRes (aclTensor*) Input Forward input block residual, corresponding to the first N values in the formula. - The data type remains consistent with partialBlock.
FLOAT16, BFLOAT16, FLOAT32 ND (T,N,H) √ projWeight (aclTensor*) Input Forward linear projection weight, which forms score_weight together with normWeight. - The data type remains consistent with partialBlock.
FLOAT16, BFLOAT16, FLOAT32 ND (1,H) √ normWeight (aclTensor*) Input Forward normalization weight. Forms score_weight together with projWeight. - Data type must remain consistent with partialBlock.
FLOAT16, BFLOAT16, FLOAT32 ND (H) √ validBlockNum (int64_t) attribute Reserved attribute. Currently does not participate in computation; only -1 is supported. - Reserved attribute. Currently does not participate in computation; only -1 is supported.
INT64 - scalar - gradHiddenStates (aclTensor*) Input Gradient of the forward output out. - The data type must remain consistent with partialBlock.
FLOAT16, BFLOAT16, FLOAT32 ND (T,H) √ invNorm (aclTensor*) Input Row-wise normalization coefficients saved in the forward pass. - Only FLOAT32 is supported.
FLOAT32 ND (T,N+1) √ probs (aclTensor*) Input Softmax output probabilities in the forward pass. - Only FLOAT32 is supported.
FLOAT32 ND (T,N+1) √ gradPartialBlock(aclTensor*) Output Gradient of partialBlock. - Data type and shape remain consistent with partialBlock.
FLOAT16, BFLOAT16, FLOAT32 ND (T,H) - gradBlockRes (aclTensor*) Output Gradient of blockRes. - Data type and shape remain consistent with blockRes.
FLOAT16, BFLOAT16, FLOAT32 ND (T,N,H) - gradProjWeight (aclTensor*) Output Gradient of projWeight. - Data type and shape remain consistent with projWeight.
FLOAT16, BFLOAT16, FLOAT32 ND (1,H) - gradNormWeight(aclTensor*) Output Gradient of normWeight. - Data type and shape remain consistent with those of normWeight.
FLOAT16, BFLOAT16, FLOAT32 ND (H) - workspaceSize (uint64_t*) Output Returns the size of the workspace to be allocated on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, including 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 Code Description ACLNN_ERR_PARAM_NULLPTR 161001 partialBlock, blockRes, projWeight, normWeight, gradHiddenStates, invNorm, probs, or an output tensor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, or shape of the input tensor is out of the supported range. ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the npu runtime interface for memory.
aclnnBlockAttentionResidualsGrad
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device side. workspaceSize Input Size of the workspace allocated on the Device side, obtained by calling the first-phase API aclnnBlockAttentionResidualsGradGetWorkspaceSize. executor Input Executor of the op, which contains the operator computation flow. stream Input Stream for task execution. Return Value aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation: aclnnBlockAttentionResidualsGrad defaults to a deterministic implementation.
- The data types of partialBlock, blockRes, projWeight, normWeight, gradHiddenStates, and their corresponding outputs must remain consistent. FLOAT16, BFLOAT16, and FLOAT32 are supported.
- validBlockNum is an INT64 reserved attribute with a default value of -1. It does not participate in the computation currently. Only -1 is supported. Other values return a parameter error.
- Only the ND format is supported for partialBlock, blockRes, projWeight, normWeight, gradHiddenStates, invNorm, and probs.
- Shapes must meet the following requirements: partialBlock is (T,H), blockRes is (T,N,H), projWeight is (1,H), normWeight is (H), gradHiddenStates is (T,H), invNorm is (T,N+1), and probs is (T,N+1), where T must be greater than or equal to 64, H must be within [2048,500000], N must be within [0,128], and the values of T and H across all tensors as well as the N+1 values of invNorm and probs must remain consistent.
- Non-contiguous input tensors are supported. The API internally converts them to the Contiguous format before computation.
- probs must be the forward softmax output, and invNorm must be the forward row-wise normalization coefficient. Only FLOAT32 is supported for invNorm and probs. The current implementation relies entirely on the saved probs and invNorm.
- validBlockNum is a reserved attribute and does not participate in actual computation; only -1 is supported.
- If T<64, H<2048, or H>500000, the first-phase API returns ACLNN_ERR_PARAM_INVALID and the kernel is not executed.
- Only when N=0 and both T and H are non-zero, the API does not return early; partialBlock and the weight gradients are still computed.
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 <cstring>
#include "acl/acl.h"
#include "aclnnop/aclnn_block_attention_residuals_grad.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 shapeSize = 1;
for (auto i : shape) {
shapeSize *= i;
}
return shapeSize;
}
int Init(int32_t deviceId, aclrtStream* stream)
{
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);
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);
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);
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];
}
*tensor = aclCreateTensor(
shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(),
*deviceAddr);
return 0;
}
int main()
{
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
const int64_t T = 64;
const int64_t N = 4;
const int64_t H = 2048;
const int64_t N1 = N + 1;
std::vector<int64_t> partialBlockShape = {T, H};
std::vector<int64_t> blockResShape = {T, N, H};
std::vector<int64_t> projWeightShape = {1, H};
std::vector<int64_t> normWeightShape = {H};
std::vector<int64_t> gradHiddenStatesShape = {T, H};
std::vector<int64_t> invNormShape = {T, N1};
std::vector<int64_t> probsShape = {T, N1};
std::vector<uint16_t> partialBlockData (GetShapeSize(partialBlockShape), 0x3C00);
std::vector<uint16_t> blockResData (GetShapeSize(blockResShape), 0x3C00);
std::vector<uint16_t> projWeightData (GetShapeSize(projWeightShape), 0x3C00);
std::vector<uint16_t> normWeightData (GetShapeSize(normWeightShape), 0x3C00);
std::vector<uint16_t> gradHiddenStatesData (GetShapeSize(gradHiddenStatesShape), 0x3C00);
std::vector<float> invNormData (GetShapeSize(invNormShape), 1.0f);
std::vector<float> probsData (GetShapeSize(probsShape), 1.0f);
int64_t validBlockNum = -1; // Reserved attribute; only -1 is supported.
aclTensor *partialBlock = nullptr, *blockRes = nullptr, *projWeight = nullptr, *normWeight = nullptr;
aclTensor *gradHiddenStates = nullptr, *invNorm = nullptr, *probs = nullptr;
void *d_partialBlock = nullptr, *d_blockRes = nullptr, *d_projWeight = nullptr, *d_normWeight = nullptr;
void *d_gradHiddenStates = nullptr, *d_invNorm = nullptr, *d_probs = nullptr;
ret = CreateAclTensor(partialBlockData, partialBlockShape, &d_partialBlock, aclDataType::ACL_FLOAT16, &partialBlock); CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(blockResData, blockResShape, &d_blockRes, aclDataType::ACL_FLOAT16, &blockRes); CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(projWeightData, projWeightShape, &d_projWeight, aclDataType::ACL_FLOAT16, &projWeight); CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(normWeightData, normWeightShape, &d_normWeight, aclDataType::ACL_FLOAT16, &normWeight); CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradHiddenStatesData, gradHiddenStatesShape, &d_gradHiddenStates, aclDataType::ACL_FLOAT16, &gradHiddenStates); CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(invNormData, invNormShape, &d_invNorm, aclDataType::ACL_FLOAT, &invNorm); CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(probsData, probsShape, &d_probs, aclDataType::ACL_FLOAT, &probs); CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor *gradPartialBlock = nullptr, *gradBlockRes = nullptr, *gradProjWeight = nullptr, *gradNormWeight = nullptr;
void *d_gradPartialBlock = nullptr, *d_gradBlockRes = nullptr, *d_gradProjWeight = nullptr, *d_gradNormWeight = nullptr;
std::vector<uint16_t> gradPartialBlockData (GetShapeSize(partialBlockShape), 0);
std::vector<uint16_t> gradBlockResData(GetShapeSize(blockResShape), 0);
std::vector<uint16_t> gradProjWeightData (GetShapeSize(projWeightShape), 0);
std::vector<uint16_t> gradNormWeightData (GetShapeSize(normWeightShape), 0);
ret = CreateAclTensor(gradPartialBlockData, partialBlockShape, &d_gradPartialBlock, aclDataType::ACL_FLOAT16, &gradPartialBlock); CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradBlockResData, blockResShape, &d_gradBlockRes, aclDataType::ACL_FLOAT16, &gradBlockRes); CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradProjWeightData, projWeightShape, &d_gradProjWeight, aclDataType::ACL_FLOAT16, &gradProjWeight); CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradNormWeightData, normWeightShape, &d_gradNormWeight, aclDataType::ACL_FLOAT16, &gradNormWeight); CHECK_RET(ret == ACL_SUCCESS, return ret);
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
ret = aclnnBlockAttentionResidualsGradGetWorkspaceSize(
partialBlock, blockRes, projWeight, normWeight,
gradHiddenStates, invNorm, probs, validBlockNum,
gradPartialBlock, gradBlockRes, gradProjWeight, gradNormWeight,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockAttentionResidualsGradGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
void* workspaceAddr = nullptr;
if (workspaceSize > static_cast<uint64_t>(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);
}
ret = aclnnBlockAttentionResidualsGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockAttentionResidualsGrad failed. ERROR: %d\n", ret); return ret);
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
LOG_PRINT("BlockAttentionResidualsGrad example ran successfully!\n");
aclDestroyTensor(partialBlock); aclDestroyTensor(blockRes); aclDestroyTensor(projWeight);
aclDestroyTensor(normWeight); aclDestroyTensor(gradHiddenStates); aclDestroyTensor(invNorm);
aclDestroyTensor(probs);
aclrtFree(d_partialBlock); aclrtFree(d_blockRes); aclrtFree(d_projWeight);
aclrtFree(d_normWeight); aclrtFree(d_gradHiddenStates); aclrtFree(d_invNorm);
aclrtFree(d_probs);
aclDestroyTensor(gradPartialBlock); aclDestroyTensor(gradBlockRes); aclDestroyTensor(gradProjWeight);
aclDestroyTensor(gradNormWeight);
aclrtFree(d_gradPartialBlock); aclrtFree(d_gradBlockRes); aclrtFree(d_gradProjWeight);
aclrtFree(d_gradNormWeight);
if (workspaceSize > static_cast<uint64_t>(0)) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}