aclnnBlockAttentionResiduals
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: Concatenates
partialBlockandblockRes, then applies RMS normalization, linear projection, and softmax weighted fusion to outputhiddenStates. WhenneedBackwardis true,invNormandprobsrequired for backward computation are also output.Formula:
The forward computation can be expressed as:
$$ v_{t,i,h} = \begin{cases} block\_res_{t,i,h}, & i < N \\ partial\_block_{t,h}, & i = N \end{cases} $$$$ variance_{t,i} = \frac{1}{H}\sum_{h=0}^{H-1} v_{t,i,h}^{2} $$$$ inv\_rms_{t,i} = \frac{1}{\sqrt{variance_{t,i} + norm\_eps}} $$$$ k_{t,i,h} = v_{t,i,h} \cdot inv\_rms_{t,i} $$$$ score\_weight_{h} = norm\_weight_{h} \cdot proj\_weight_{0,h} $$$$ s_{t,i} = \sum_{h=0}^{H-1} k_{t,i,h} \cdot score\_weight_{h} $$$$ probs_{t,i} = \frac{e^{s_{t,i}}}{\sum_{j=0}^{N} e^{s_{t,j}}} $$$$ hidden\_states_{t,h} = \sum_{i=0}^{N} probs_{t,i} \cdot v_{t,i,h} $$Where:
- $T$ indicates the number of tokens, $N$ indicates the number of blocks in
blockRes, and $H$ indicates the hidden size. - $v_{t,i,h}$ indicates the value after concatenating
blockResandpartialBlock, with the shape of $(T,N+1,H)$. - $inv\_rms_{t,i}$ denotes the forward row-wise normalization coefficient.
- $score\_weight_{h}$ denotes the element-wise product of
normWeightandprojWeight. - $probs_{t,i}$ denotes the forward softmax output probability.
- $hidden\_states_{t,h}$ denotes the forward weighted fusion output.
- $T$ indicates the number of tokens, $N$ indicates the number of blocks in
Function Prototype
Each operator is split into a two-phase API. Call "aclnnBlockAttentionResidualsGetWorkspaceSize" to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call "aclnnBlockAttentionResiduals" to perform the computation.
aclnnStatus aclnnBlockAttentionResidualsGetWorkspaceSize(
const aclTensor *partialBlock,
const aclTensor *blockRes,
const aclTensor *projWeight,
const aclTensor *normWeight,
int64_t validBlockNum,
double normEps,
bool needBackward,
aclTensor *hiddenStates,
aclTensor *invNorm,
aclTensor *probs,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnBlockAttentionResiduals(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnBlockAttentionResidualsGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor partialBlock (aclTensor*) Input Forward input partialBlock, corresponding to the (N+1)th value after concatenation in the formula. - Supports empty tensors, and T can be 0.
- Shape is (T, H).
- T and H must remain consistent with blockRes.
FLOAT16, BFLOAT16, FLOAT32 ND 2 √ blockRes (aclTensor*) Input Forward input block residual, corresponding to the first N values in the formula. - Empty tensors are supported. T can be 0.
- The shape is (T, N, H).
- The data type must remain consistent with partialBlock.
FLOAT16, BFLOAT16, FLOAT32 ND 3 √ projWeight (aclTensor*) Input Linear projection weight for forward. Together with normWeight, it forms score_weight. - Empty tensors are not supported.
- The shape is (H) or (1, H).
- The data type must remain consistent with partialBlock.
FLOAT16, BFLOAT16, FLOAT32 ND 1-2 √ normWeight (aclTensor*) Input Normalization weight for forward. Forms score_weight together with projWeight. - Empty tensors are not supported.
- The shape is (H).
- The data type must remain consistent with partialBlock.
FLOAT16, BFLOAT16, FLOAT32 ND 1 √ validBlockNum (int64_t) Input Reserved attribute. Currently not involved in computation. - Default value: -1.
- Only -1 is supported.
INT64 - - - normEps (double) Optional input Numerical stability parameter for RMS normalization, corresponding to norm_eps in the formula. - Must be greater than 0.
- Default value: 1e-6.
DOUBLE - - - needBackward (bool) Optional input Whether to save invNorm and probs for use in backward computation. - Default value: false.
- If true, invNorm and probs cannot be null pointers.
BOOL - - - hiddenStates (aclTensor*) Output Forward weighted fusion output, corresponding to hidden_states in the formula. - Supports empty tensors, and T can be 0.
- The shape is (T, H).
- The data type must remain consistent with partialBlock.
FLOAT16, BFLOAT16, FLOAT32 ND 2 × invNorm (aclTensor*) Optional output Row-wise normalization coefficient saved during forward propagation, which is inv_rms in the corresponding formula. - A null pointer can be passed when needBackward is false.
- A null pointer is not supported when needBackward is true. The shape is (T, N+1).
FLOAT32 ND 2 × probs (aclTensor*) Optional output Forward softmax output probabilities, i.e., probs in the corresponding formula. - A null pointer can be passed when needBackward is false.
- A null pointer is not supported when needBackward is true. The shape is (T, N+1).
FLOAT32 ND 2 × workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the computation flow of the operator. - - - - - 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, or hiddenStates is a null pointer; invNorm or probs is a null pointer when needBackward is true. ACLNN_ERR_PARAM_INVALID 161002 The data type of partialBlock, blockRes, projWeight, normWeight, hiddenStates, invNorm, or probs is not within the supported range, or the data types of the compute tensors are inconsistent. The shape dimensions of partialBlock, blockRes, projWeight, normWeight, hiddenStates, invNorm, or probs are not within the supported range. validBlockNum is not -1, or normEps is less than or equal to 0. ACLNN_ERR_INNER_CREATE_EXECUTOR 561101 Failed to create aclOpExecutor inside the interface. ACLNN_ERR_INNER_NULLPTR 561103 A null pointer is returned inside the interface during contiguous processing, operator output creation, or output copy node creation. ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API internally calls the NPU runtime API.
aclnnBlockAttentionResiduals
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Workspace size allocated on the Device, obtained by calling the first-phase API aclnnBlockAttentionResidualsGetWorkspaceSize. executor Input op executor, including 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:
- aclnnBlockAttentionResiduals defaults to a deterministic implementation.
Batch consistency:
- aclnnBlockAttentionResiduals defaults to a Batch-consistent implementation.
Specification constraints:
- T is greater than or equal to 0, H is greater than or equal to 1, and N is in the range of 1-100.
- partialBlock, blockRes, projWeight, normWeight, and hiddenStates must have the same data type. FLOAT16, BFLOAT16, and FLOAT32 are supported. invNorm and probs support only FLOAT32.
- The shape must meet the following requirements: partialBlock is (T, H), blockRes is (T, N, H), projWeight is (H) or (1, H), normWeight is (H), and hiddenStates is (T, H). When needBackward is true, invNorm and probs are (T, N+1).
- validBlockNum is a reserved attribute. The default value is -1, and it does not participate in the computation currently. Only -1 can be passed in.
- normEps must be greater than 0. The default value is 1e-6.
- Input tensors support non-contiguous tensors; the computation is performed after the interface-internal conversion to Contiguous. Output tensors do not support non-contiguous tensors.
- Only the platform system-reserved workspace is used; no additional user-side workspace is requested.
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 <cstdint>
#include "acl/acl.h"
#include "aclnnop/aclnn_block_attention_residuals.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 dim : shape) {
shapeSize *= dim;
}
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;
}
int CreateAclTensor(
const std::vector<uint16_t>& hostData, const std::vector<int64_t>& shape,
void** deviceAddr, aclTensor** tensor)
{
auto size = GetShapeSize(shape) * sizeof(uint16_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);
*tensor = aclCreateTensor(
shape.data(), shape.size(), aclDataType::ACL_BF16, nullptr, 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 = 2;
const int64_t N = 4;
const int64_t H = 64;
std::vector<int64_t> partialBlockShape = {T, H};
std::vector<int64_t> blockShape = {T, N, H};
std::vector<int64_t> projShape = {1, H};
std::vector<int64_t> normShape = {H};
std::vector<int64_t> hiddenShape = {T, H};
std::vector<uint16_t> partialBlockData(GetShapeSize(partialBlockShape), 0x3C00);
std::vector<uint16_t> blockData(GetShapeSize(blockShape), 0x3C00);
std::vector<uint16_t> projData(GetShapeSize(projShape), 0x3C00);
std::vector<uint16_t> normData(GetShapeSize(normShape), 0x3C00);
std::vector<uint16_t> hiddenData(GetShapeSize(hiddenShape), 0);
void* partialBlockDev = nullptr;
void* blockDev = nullptr;
void* projDev = nullptr;
void* normDev = nullptr;
void* hiddenDev = nullptr;
aclTensor* partialBlockTensor = nullptr;
aclTensor* blockTensor = nullptr;
aclTensor* projTensor = nullptr;
aclTensor* normTensor = nullptr;
aclTensor* hiddenTensor = nullptr;
ret = CreateAclTensor(partialBlockData, partialBlockShape, &partialBlockDev, &partialBlockTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(blockData, blockShape, &blockDev, &blockTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(projData, projShape, &projDev, &projTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(normData, normShape, &normDev, &normTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(hiddenData, hiddenShape, &hiddenDev, &hiddenTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
ret = aclnnBlockAttentionResidualsGetWorkspaceSize(
partialBlockTensor, blockTensor, projTensor, normTensor, -1, 1e-6, false,
hiddenTensor, nullptr, nullptr, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockAttentionResidualsGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
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);
}
ret = aclnnBlockAttentionResiduals(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockAttentionResiduals 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("BlockAttentionResiduals example ran successfully!\n");
if (workspaceAddr != nullptr) {
aclrtFree(workspaceAddr);
}
aclDestroyTensor(partialBlockTensor);
aclDestroyTensor(blockTensor);
aclDestroyTensor(projTensor);
aclDestroyTensor(normTensor);
aclDestroyTensor(hiddenTensor);
aclrtFree(partialBlockDev);
aclrtFree(blockDev);
aclrtFree(projDev);
aclrtFree(normDev);
aclrtFree(hiddenDev);
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}