aclnnGenericBlockSparseAttentionGradMetadata
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: aclnnGenericBlockSparseAttentionGradMetadata performs partitioning and load balancing for sparse attention based on information such as sparseBlockIdx, sparseBlockCount, and seqlen. It is a preceding AICPU operator of aclnnGenericBlockSparseAttentionGrad. It expands the
(b, n2, j, g)task list in the order of B → N2 → J → G and performs greedy load balancing across AIC cores at the[baseM, baseN] = [128, 128]basic block granularity, outputting metadata for the main Grad operator to consume. - This operator is not recommended for standalone use. It is recommended to use it with aclnnGenericBlockSparseAttentionGrad to form a complete workflow.
where J = ceilDiv(maxKvSeqlen, blockShapeY).
Function Prototype
Each operator uses a two-phase API. Call the "aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnGenericBlockSparseAttentionGradMetadata" API to execute the computation.
aclnnStatus aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize(
const aclTensor *sparseBlockIdx,
const aclTensor *sparseBlockCount,
const aclTensor *cuSeqLengthsQOptional,
const aclTensor *cuSeqLengthsKvOptional,
const aclTensor *sequsedQOptional,
const aclTensor *sequsedKvOptional,
int64_t maxQSeqlen,
int64_t maxKvSeqlen,
int64_t numQHeads,
int64_t numKvHeads,
int64_t headDim,
const aclIntArray *blockShape,
char *layoutQ,
char *layoutKv,
int64_t layoutSparsePattern,
int64_t maskType,
int64_t softmaxPrecision,
int64_t winLeft,
int64_t winRight,
int64_t residualBlockMode,
bool isConsistentTopk,
aclTensor *metadata,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnGenericBlockSparseAttentionGradMetadata(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize
Parameters
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_INNER_CREATE_EXECUTOR 561101 Failed to create aclOpExecutor. ACLNN_ERR_INNER_NULLPTR 561103 workspaceSize or executor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 sparseBlockIdx/sparseBlockCount/metadata is empty or shape/dtype is invalid. cuSeqLengths is not provided when layout is TND; headDim, blockShape, layoutSparsePattern, residualBlockMode, isConsistentTopk, and window are not in the supported range. The J dimension of sparseBlockIdx is inconsistent with ceilDiv(maxKvSeqlen, blockShapeY); the metadata length is insufficient; B×N1×J exceeds the upper limit of task count (1M).
aclnnGenericBlockSparseAttentionGradMetadata
Parameters
Parameter Input/Output Description workspace Input workspace memory address applied on the Device side. workspaceSize Input workspace size applied on the Device side, obtained by the first-phase API aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize. executor Input Executor of the op, containing the operator computation flow. stream Input Specifies the Stream for executing tasks. Return Value
aclnnStatus: Return value. For details, see aclnn return codes.
Constraints
The layoutSparsePattern, residualBlockMode, and isConsistentTopk settings in Grad and GradMetadata calls must be consistent. Currently only layoutSparsePattern=1 and residualBlockMode=0 are supported.
Deterministic computation:
- The output of this operator is deterministic.
Must be used together with aclnnGenericBlockSparseAttentionGrad. This operator must be successfully executed before the main operator is called.
HeadDim is fixed to 128; numQHeads/numKvHeads must be in the range [1, 128], and numQHeads % numKvHeads == 0.
blockShape currently only supports [1, 128]; layoutSparsePattern currently only supports 1; maskType currently only supports 1.
layoutQ and layoutKv must be the same, with the value "TND"/"BNSD"/"BSND"; cuSeqLengthsQOptional/cuSeqLengthsKvOptional are mandatory when the layout is TND.
sequsedQOptional/sequsedKvOptional take effect only for TND; nullptr must be passed for BNSD/BSND, and the actual sequence length is taken from maxQSeqlen/maxKvSeqlen (which must be the same as the S dimension of Q/K).
winLeft and winRight must be -1 when not enabled.
The last dimension maxS1 of sparseBlockIdx must be ≥ maxQSeqlen; J = ceilDiv(maxKvSeqlen, blockShapeY) must be the same as the 3rd dimension of sparseBlockIdx.
The length of metadata must satisfy shape[0] ≥ 80 + B × numQHeads × J × 4; the upper bound of the number of tasks is B × numQHeads × J ≤ 1048576.
Example
The following sample code is for reference only. For details about compilation and execution, refer to Compile and Run Samples.
#include <cmath>
#include <cstdint>
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_generic_block_sparse_attention_grad_metadata.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 n = 1;
for (auto v : shape) {
n *= v;
}
return n;
}
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 = 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, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
int main()
{
int32_t deviceId = 0;
aclrtStream stream = nullptr;
auto ret = Init(deviceId, &stream);
CHECK_RET(ret == ACL_SUCCESS, return ret);
const int64_t B = 1, N1 = 1, N2 = 1, S1 = 128, S2 = 128, D = 128;
const int64_t blockY = 128;
const int64_t J = (S2 + blockY - 1) / blockY;
const int64_t metaSize = 80 + B * N1 * J * 4;
std::vector<int64_t> idxShape = {B, N2, J, S1};
std::vector<int64_t> cntShape = {B, N2, J};
std::vector<int64_t> metaShape = {metaSize};
std::vector<int32_t> idxHost(static_cast<size_t>(GetShapeSize(idxShape)), -1);
std::vector<int32_t> cntHost(static_cast<size_t>(GetShapeSize(cntShape)), 0);
std::vector<int32_t> metaHost(static_cast<size_t>(metaSize), 0);
for (int64_t q = 0; q < S1; ++q) {
idxHost[static_cast<size_t>(q)] = static_cast<int32_t>(q);
}
cntHost[0] = static_cast<int32_t>(S1);
void *idxAddr = nullptr, *cntAddr = nullptr, *metaAddr = nullptr;
aclTensor *idx = nullptr, *cnt = nullptr, *metadata = nullptr;
ret = CreateAclTensor(idxHost, idxShape, &idxAddr, aclDataType::ACL_INT32, &idx);
CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
ret = CreateAclTensor(cntHost, cntShape, &cntAddr, aclDataType::ACL_INT32, &cnt);
CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
ret = CreateAclTensor(metaHost, metaShape, &metaAddr, aclDataType::ACL_INT32, &metadata);
CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
const int64_t blockShapeData[] = {1, blockY};
aclIntArray *blockShape = aclCreateIntArray(blockShapeData, 2);
char layout[] = "BNSD";
uint64_t wsSize = 0;
aclOpExecutor *executor = nullptr;
ret = aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize(
idx, cnt, nullptr, nullptr, nullptr, nullptr, S1, S2, N1, N2, D, blockShape, layout, layout, 1, 1, 0, -1, -1, 0, 0,
metadata, &wsSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
void *ws = nullptr;
if (wsSize > 0) {
ret = aclrtMalloc(&ws, wsSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
}
ret = aclnnGenericBlockSparseAttentionGradMetadata(ws, wsSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
LOG_PRINT("GenericBlockSparseAttentionGradMetadata finished successfully.\n");
aclDestroyIntArray(blockShape);
aclDestroyTensor(idx);
aclDestroyTensor(cnt);
aclDestroyTensor(metadata);
aclrtFree(idxAddr);
aclrtFree(cntAddr);
aclrtFree(metaAddr);
if (wsSize > 0) {
aclrtFree(ws);
}
Finalize(deviceId, stream);
return 0;
}