aclnnBlockAttnResUpdate
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Not supported
Atlas A2 products : Not supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description:
Phase two of the two-phase historical residual attention computation for Attention Residuals: accumulates
deltaintopartialBlockRefin place and computes the RMSNorm score of the updated residual; then computes the outputhwith the softmax statisticsnumerator,logitMax, andexpSum(corresponding to O, M, and L, respectively) returned by the first-phase APIblock_attn_res_prepare, and writes the updated residual back topartialBlockRefin place.Formula:
Let
Tdenote the number of tokens andDdenote the hidden size. The main computation process is as follows:- Update the current
partialBlockRef:$$ p[t,d] = partialBlockRef[t,d] + \operatorname{FP32}(delta[t,d]) $$ - Compute the RMSNorm denominator and the current score:$$ r[t] = \sqrt{\frac{1}{D}\sum_{d=0}^{D-1}p[t,d]^2 + eps} $$$$ score[t] = \frac{\sum_{d=0}^{D-1}p[t,d] \times pseudoQuery[d]}{r[t]} $$
- Merge the current score with the historical online softmax states:$$ m[t] = \max(logitMax[t], score[t]) $$$$ alpha[t] = \exp(logitMax[t] - m[t]), \qquad beta[t] = \exp(score[t] - m[t]) $$$$ ell[t] = expSum[t] \times alpha[t] + beta[t] $$$$ updatedNumerator[t,d] = numerator[t,d] \times alpha[t] + p[t,d] \times beta[t] $$
- Generate the output:$$ partialBlockRef[t,d] \leftarrow p[t,d] $$$$ h[t,d] = \operatorname{BF16}\left(\frac{updatedNumerator[t,d]}{ell[t]}\right) $$
- Update the current
Function Prototype
Each operator uses a two-phase API. Call
aclnnBlockAttnResUpdateGetWorkspaceSize first to obtain the workspace size and executor, then call
aclnnBlockAttnResUpdate to perform the computation.
aclnnStatus aclnnBlockAttnResUpdateGetWorkspaceSize(
aclTensor *partialBlockRef,
const aclTensor *delta,
const aclTensor *pseudoQuery,
const aclTensor *numerator,
const aclTensor *logitMax,
const aclTensor *expSum,
double eps,
aclTensor *h,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnBlockAttnResUpdate(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnBlockAttnResUpdateGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dim (shape) Non-contiguous Tensor partialBlockRef(aclTensor*) Input/Output Currently accumulated partialBlockRef. - Required.
- Data type: FLOAT.
- Both the raw format and storage format support only ND.
- Must be a contiguous tensor.
T >= 0,0 <= D <= 8192.- Empty tensors are supported.
FLOAT ND [T, D] × delta(const aclTensor*) Input delta to be accumulated. - Required.
- Data type: BFLOAT16.
- Only ND is supported for both the raw format and storage format.
- Must be a contiguous tensor.
- The shape must be the same as that of partialBlockRef.
- Empty tensors are supported.
BFLOAT16 ND [T, D] × pseudoQuery(const aclTensor*) Input pseudoQuery used to compute the logit of the current partial block. - Required.
- Data type: FLOAT.
- Only ND is supported for both the raw format and storage format.
- Must be a contiguous tensor.
- The length must be equal to the D of partialBlockRef.
- Empty tensors are supported.
FLOAT ND [D] × numerator(const aclTensor*) Input Historical online softmax weighted sum output by block_attn_res_prepare. - Required.
- Data type: FLOAT.
- Only ND is supported for both the raw format and storage format.
- Must be a contiguous tensor.
- The shape must be the same as partialBlockRef.
- Empty tensors are supported.
FLOAT ND [T, D] × logitMax(const aclTensor*) Input Historical maximum logit output by block_attn_res_prepare. - Required.
- Data type: FLOAT.
- Only ND is supported for both the raw format and the storage format.
- Must be a contiguous tensor.
- The length must equal the T of partialBlockRef.
- Empty tensors are supported.
FLOAT ND [T] × expSum(const aclTensor*) Input Accumulated historical softmax denominator output by block_attn_res_prepare. - Required.
- Data type: FLOAT.
- Only ND is supported for both the raw format and the storage format.
- Must be a contiguous tensor.
- The length must be equal to the T of partialBlockRef.
- Empty tensors are supported.
FLOAT ND [T] × eps(double) Input RMSNorm numerical stability term. - Required.
- Must be a finite positive number.
- - - - h(aclTensor*) Output Result of the current layer. - Required.
- Supports BFLOAT16 data type.
- Only ND is supported for both the raw format and the storage format.
- Must be a contiguous tensor.
- The shape must be the same as that of partialBlockRef.
- Returns an empty tensor if the input is an empty tensor.
BFLOAT16 ND [T, D] × workspaceSize(uint64_t*) Output Returns the workspace size to be allocated on the device. - Required.
- - - - executor(aclOpExecutor**) Output Returns an executor containing the operator computation flow. - Required.
- - - - 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 partialBlockRef,delta,pseudoQuery,numerator,logitMax,expSum,h,workspaceSize, orexecutoris null.ACLNN_ERR_PARAM_INVALID 161002 The input or output dtype, raw or storage format, dimension, or shape relationship does not meet the constraints. T < 0, orDis not in the range[0, 8192].In a non-empty use case, T * Dexceeds the range representable byint64_t.Any input or output tensor is a non-contiguous tensor. epsis not a finite positive number.ACLNN_ERR_RUNTIME_ERROR 361001 The product model is not within the supported range.
aclnnBlockAttnResUpdate
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device. Obtained by the first-phase API aclnnBlockAttnResUpdateGetWorkspaceSize. executor Input Executor of the op, which contains the computation flow of the operator. stream Input Stream in which the task is executed. Return Value
aclnnStatus: Return status code. For details, see aclnn return codes.
Constraints
- Deterministic computation:
- aclnnBlockAttnResUpdate defaults to a deterministic implementation.
- All Tensor inputs support empty Tensors, but the shape relationships between them must still be satisfied. A Tensor cannot be set to empty on its own.
- In non-empty cases,
T * Dmust not exceed the range representable byint64_t.
Example
The sample code is as follows and is for reference only. For details about compilation and execution, see Compile and Run Samples. The complete sample source code is in test_aclnn_block_attn_res_update.cpp.
/**
* Copyright (c) 2026 Huawei Technologies Co., Ltd.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_block_attn_res_update.h"
#define CHECK_RET(cond, return_expr) \
do { \
if (!(cond)) { \
return_expr; \
} \
} while (0)
#define CHECK_FREE_RET(cond, return_expr) \
do { \
if (!(cond)) { \
Finalize(deviceId, stream); \
return_expr; \
} \
} while (0)
#define LOG_PRINT(message, ...) \
do { \
printf(message, ##__VA_ARGS__); \
} while (0)
constexpr size_t FIRST_ELEMENT_INDEX = 0UL;
int64_t GetShapeSize(const std::vector<int64_t> &shape)
{
int64_t shapeSize = 1;
for (auto dim : shape) {
shapeSize *= dim;
}
return shapeSize;
}
uint16_t FloatToBfloat16(float value)
{
uint32_t bits = 0;
std::memcpy(&bits, &value, sizeof(bits));
const uint32_t roundingBias = 0x7FFFU + ((bits >> 16U) & 1U);
return static_cast<uint16_t>((bits + roundingBias) >> 16U);
}
float Bfloat16ToFloat(uint16_t value)
{
const uint32_t bits = static_cast<uint32_t>(value) << 16U;
float result = 0.0F;
std::memcpy(&result, &bits, sizeof(result));
return result;
}
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 ACL_SUCCESS;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
aclDataType dataType, aclFormat formatType, aclTensor **tensor)
{
const size_t size = static_cast<size_t>(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 = static_cast<int64_t>(shape.size()) - 2; i >= 0; --i) {
strides[i] = shape[i + 1] * strides[i + 1];
}
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, formatType, shape.data(),
shape.size(), *deviceAddr);
CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed - returned nullptr\n");
return ACL_ERROR_FAILURE);
return ACL_SUCCESS;
}
int RunBlockAttnResUpdate(int32_t deviceId, aclrtStream &stream)
{
// 1. Initialize the Device and Stream.
auto ret = Init(deviceId, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output data.
constexpr int64_t tokenNum = 2;
constexpr int64_t hiddenSize = 64;
const std::vector<int64_t> matrixShape = {tokenNum, hiddenSize};
const std::vector<int64_t> queryShape = {hiddenSize};
const std::vector<int64_t> statsShape = {tokenNum};
std::vector<float> partialBlockRefHostData(GetShapeSize(matrixShape), 0.25F);
std::vector<uint16_t> deltaHostData(GetShapeSize(matrixShape), FloatToBfloat16(0.125F));
std::vector<float> pseudoQueryHostData(GetShapeSize(queryShape), 1.0F / static_cast<float>(hiddenSize));
std::vector<float> numeratorHostData(GetShapeSize(matrixShape), 0.5F);
std::vector<float> logitMaxHostData(GetShapeSize(statsShape), 0.0F);
std::vector<float> expSumHostData(GetShapeSize(statsShape), 1.0F);
std::vector<uint16_t> hHostData(GetShapeSize(matrixShape), 0U);
void *partialBlockRefDeviceAddr = nullptr;
void *deltaDeviceAddr = nullptr;
void *pseudoQueryDeviceAddr = nullptr;
void *numeratorDeviceAddr = nullptr;
void *logitMaxDeviceAddr = nullptr;
void *expSumDeviceAddr = nullptr;
void *hDeviceAddr = nullptr;
aclTensor *partialBlockRef = nullptr;
aclTensor *delta = nullptr;
aclTensor *pseudoQuery = nullptr;
aclTensor *numerator = nullptr;
aclTensor *logitMax = nullptr;
aclTensor *expSum = nullptr;
aclTensor *h = nullptr;
// 3. Create the input and output aclTensors.
ret = CreateAclTensor<float>(partialBlockRefHostData, matrixShape, &partialBlockRefDeviceAddr,
aclDataType::ACL_FLOAT, aclFormat::ACL_FORMAT_ND, &partialBlockRef);
std::unique_ptr<void, aclError (*)(void *)> partialBlockRefDeviceAddrPtr(partialBlockRefDeviceAddr, aclrtFree);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> partialBlockRefTensorPtr(partialBlockRef,
aclDestroyTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor<uint16_t>(deltaHostData, matrixShape, &deltaDeviceAddr, aclDataType::ACL_BF16,
aclFormat::ACL_FORMAT_ND, &delta);
std::unique_ptr<void, aclError (*)(void *)> deltaDeviceAddrPtr(deltaDeviceAddr, aclrtFree);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> deltaTensorPtr(delta, aclDestroyTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor<float>(pseudoQueryHostData, queryShape, &pseudoQueryDeviceAddr, aclDataType::ACL_FLOAT,
aclFormat::ACL_FORMAT_ND, &pseudoQuery);
std::unique_ptr<void, aclError (*)(void *)> pseudoQueryDeviceAddrPtr(pseudoQueryDeviceAddr, aclrtFree);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> pseudoQueryTensorPtr(pseudoQuery, aclDestroyTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor<float>(numeratorHostData, matrixShape, &numeratorDeviceAddr, aclDataType::ACL_FLOAT,
aclFormat::ACL_FORMAT_ND, &numerator);
std::unique_ptr<void, aclError (*)(void *)> numeratorDeviceAddrPtr(numeratorDeviceAddr, aclrtFree);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> numeratorTensorPtr(numerator, aclDestroyTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor<float>(logitMaxHostData, statsShape, &logitMaxDeviceAddr, aclDataType::ACL_FLOAT,
aclFormat::ACL_FORMAT_ND, &logitMax);
std::unique_ptr<void, aclError (*)(void *)> logitMaxDeviceAddrPtr(logitMaxDeviceAddr, aclrtFree);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> logitMaxTensorPtr(logitMax, aclDestroyTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor<float>(expSumHostData, statsShape, &expSumDeviceAddr, aclDataType::ACL_FLOAT,
aclFormat::ACL_FORMAT_ND, &expSum);
std::unique_ptr<void, aclError (*)(void *)> expSumDeviceAddrPtr(expSumDeviceAddr, aclrtFree);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> expSumTensorPtr(expSum, aclDestroyTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor<uint16_t>(hHostData, matrixShape, &hDeviceAddr, aclDataType::ACL_BF16,
aclFormat::ACL_FORMAT_ND, &h);
std::unique_ptr<void, aclError (*)(void *)> hDeviceAddrPtr(hDeviceAddr, aclrtFree);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> hTensorPtr(h, aclDestroyTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
constexpr double eps = 1.0e-6;
uint64_t workspaceSize = 0;
aclOpExecutor *executor = nullptr;
void *workspaceAddr = nullptr;
// 4. Call the first-phase API to obtain the workspace size and executor.
ret = aclnnBlockAttnResUpdateGetWorkspaceSize(partialBlockRef, delta, pseudoQuery, numerator, logitMax, expSum,
eps, h, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnBlockAttnResUpdateGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtr(nullptr, aclrtFree);
if (workspaceSize > 0) {
// Allocate the device-side workspace based on the size returned by the first-phase API.
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);
workspaceAddrPtr.reset(workspaceAddr);
}
// 5. Call the second-phase API to execute the operator.
ret = aclnnBlockAttnResUpdate(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockAttnResUpdate failed. ERROR: %d\n", ret); return ret);
// 6. Synchronize and wait for the task to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 7. Copy the in-place update result and output result back to the host.
const size_t partialBlockRefSize = partialBlockRefHostData.size() * sizeof(float);
ret = aclrtMemcpy(partialBlockRefHostData.data(), partialBlockRefSize, partialBlockRefDeviceAddr,
partialBlockRefSize,
ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy partialBlockRef to host failed. ERROR: %d\n", ret); return ret);
const size_t hSize = hHostData.size() * sizeof(uint16_t);
ret = aclrtMemcpy(hHostData.data(), hSize, hDeviceAddr, hSize, ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy h to host failed. ERROR: %d\n", ret); return ret);
LOG_PRINT("partialBlockRef[0] after in-place update: %.6f\n", partialBlockRefHostData[FIRST_ELEMENT_INDEX]);
LOG_PRINT("h[0]: %.6f\n", Bfloat16ToFloat(hHostData[FIRST_ELEMENT_INDEX]));
LOG_PRINT("block_attn_res_update example execute success.\n");
return ACL_SUCCESS;
}
int main()
{
int32_t deviceId = 0;
aclrtStream stream = nullptr;
auto ret = RunBlockAttnResUpdate(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("RunBlockAttnResUpdate failed. ERROR: %d\n", ret); return ret);
// 8. Release the device and stream resources.
Finalize(deviceId, stream);
return ACL_SUCCESS;
}