aclnnGenericBlockSparseAttentionMetadata
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: Generates the
metadataOptionalrequired for theaclnnGenericBlockSparseAttentioncomputation. - The output
metadataOptionalmust be used as themetadataOptionalinput of the primary operatoraclnnGenericBlockSparseAttentionand must be regenerated before each call to the primary operator. metadataOptionalis opaque data. Callers must not parse or modify its content.
Function Prototype
Each operator uses a two-phase API. Call aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize first to obtain the workspace size and the executor that contains the operator computation process. Then call aclnnGenericBlockSparseAttentionMetadata to execute the computation.
aclnnStatus aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize(
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,
const char *layoutQ,
const char *layoutKv,
int64_t layoutSparsePattern,
int64_t maskType,
int64_t quantType,
int64_t softmaxPrecision,
int64_t winLeft,
int64_t winRight,
int64_t residualBlockMode,
bool isConsistentTopK,
const aclTensor *metadataOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnGenericBlockSparseAttentionMetadata(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize
Parameters
See Baseline Description for the meaning of shape variables in the table.
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor sparseBlockIdx Input Array of sparse block indices, specifying the KV block indices selected for each Q block. Values must be valid KV block indices (partitioned by the cu storage length). Invalid positions can be filled with -1, and valid values must be within the first sparseBlockCount positions. For details, see Layout Correspondence. INT32 ND [numKeyValueHeads, totalQBlocks, maxSparseBlockCount] × sparseBlockCount Input Number of KV blocks actually selected for each Q block. For details, see Layout Correspondence Description. INT32 ND [numKeyValueHeads, totalQBlocks] × cuSeqLengthsQOptional Input Describes the query sequence length of each batch, stored as prefix sums. Optional input for variable-length sequence use cases. - Required when layoutQ is TND.
- When layoutQ is BNSD/BSND: if this input is passed in, the operator processes data based on the actual sequence lengths specified by this input; if nullptr is passed in, the operator processes data based on S in the shape of query (not currently supported).
- Elements are prefix sums: the 0th element is 0, the last element equals totalQTokens, and each subsequent element must be ≥ the preceding element; differences between adjacent elements yield the storage length qStorageLen_i of each batch, and Σ qStorageLen_i = totalQTokens must be satisfied.
INT64 ND (B+1,) × cuSeqLengthsKvOptional Input Describes the key/value sequence length of each batch, stored as a prefix sum. Optional input for variable-length sequence use cases. - Must be passed when layoutKv is TND.
- Do not pass it when layoutKv is not TND (must be nullptr). Currently, only PA_BBND is supported.
- When layoutKv is BNSD/BSND: if this input is passed, the operator processes data based on the actual sequence lengths specified by this input; if nullptr is passed, data is processed based on S in the key/value shape (currently not supported).
- The elements are prefix sums: the 0th element is 0, the last element equals the sum of KV storage lengths of all batches, and each subsequent element must be ≥ the preceding element.
INT64 ND (B+1,) × sequsedQOptional Input Actual sequence length of the query in each batch. - If the actual sequence length is not specified, pass in nullptr, indicating that the storage length is the same as that obtained by differencing cuSeqLengthsQOptional.
- When passed in, the shape is (B,), and each element must be ≥0 and ≤ the cu storage length of the corresponding batch. For the dual-length semantics when coexisting with cu, see Other Constraints.
INT32 ND (B,) × sequsedKvOptional Input Actual sequence lengths of kv in each batch. - Mandatory when layoutKv is PA_BBND. The shape is (B,), and each element must be ≥ 0.
- When layoutKv is TND: pass nullptr if the actual length is not specified, which indicates that the storage length is the same as that obtained by differencing cuSeqLengthsKvOptional; if specified, the shape is (B,) and each element must be ≥ 0 and ≤ the cu storage length of the corresponding batch. For the dual-length semantics when coexisting with cu, see Other Constraints.
INT32 ND (B,) × maxQSeqLen Input Maximum Sequence Length of the Query in the main operator. Must be greater than 0 and consistent with the main operator and length-type inputs. For details, see Other Constraints. INT64 - - - maxKvSeqLen Input Maximum Sequence Length of the Key/Value of the main operator. Must be greater than 0 and consistent with the main operator and length-type inputs. For details, see Other Constraints. INT64 - - - numQHeads Input Number of Query heads for the main operator. Must be greater than 0 and consistent with the main operator. For the relationship between the numbers of Q/KV heads, see Other constraints. INT64 - - - numKvHeads Input Number of Key/Value heads in the primary operator. Must be greater than 0 and consistent with the primary operator. For the Q/KV head count relationship, see Other Constraints. INT64 - - - headDim Input Feature dimension of each head of Query, Key, and Value of the main operator. Currently, only 128 is supported, and it must be the same as that of the main operator. INT64 - - - blockShape Input Represents the shape array of sparse blocks. Contains two elements [blockShapeX, blockShapeY].
blockShapeX supports any value and must not exceed the value range of int64.
blockShapeY supports any value aligned to 16 and must not exceed the value range of int64.
For additional constraints when quantization is enabled, see Quantization.
Currently, only blockShape=[1,128] is supported.INT64 - - - layoutQ Input Represents the data layout format of the input query. The target supports "TND", "BNSD", and "BSND". For details, see layout mapping. Currently, only "TND" is supported. String - - - layoutKv Input Represents the data layout format of the input key and value. The target supports "TND", "BNSD", "BSND", "PA_BBND", and "PA_BNBD". For details, see layout correspondence. Currently, only "PA_BBND" is supported. String - - - layoutSparsePattern Input Represents the data layout format of the input sparseBlockIdx and sparseBlockCount. Currently, only "4" is supported. For details, see layout correspondence. INT64 - - - maskType Input Indicates the mask type in the attention computation. Value range: 0-5. For details, see Mask Description.
Currently, only 1 (causal mask) is supported.INT64 - - - quantType Input Represents the quantization method used. Value: 0-5. For the complete configuration, see Quantization-Related Description:
Currently available: 0; 5 is selectable on Ascend 950. Values 1-4 will fail validation.INT64 - - - softmaxPrecision Input Precision level used for Softmax computation. Controls the data type used by operations in the online softmax phase and the rescale phase. Value: 0 or 1: - 0: Both online softmax and rescale use fp32. Suitable for use cases requiring high computation precision.
- 1: Mixed precision. online softmax uses fp16/bf16 (same as attentionOut), and rescale uses fp32. Numerical overflow may occur in the online softmax phase.
INT64 - - - winLeft Input Specifies the number of tokens that the sliding window needs to include before the current token in sliding window attention use cases. Used for sliding window attention; must be -1 when the feature is disabled, and must be used together with maskType. See Mask Description. Currently, only -1 is supported. INT64 - - - winRight Input In sliding window attention use cases, the number of tokens the sliding window needs to include backward. Used for sliding window attention; must be -1 when sliding window attention is disabled and must be used with maskType. See Mask. Currently, only -1 is supported. INT64 - - - residualBlockMode Input Indicates the state of the trailing incomplete blocks after the KV sequence is sparsified in units of blockShapeY. Currently, only 0 or 1 is supported. 0 indicates that whether the trailing incomplete blocks participate in the computation is determined by the value passed in by sparseBlockIdx. 1 indicates that the trailing incomplete blocks always participate in the computation but are never included in sparseBlockIdx. INT64 - - - isConsistentTopK Input Whether the maximum number of KV blocks selected by each Q block is the same within the same batch and head when the preceding operator performs sparse block selection. Only 0 or 1 is supported. 0 indicates inconsistency, and 1 indicates consistency. BOOL - - - metadataOptional Output Core division result generated by the AICPU operator. Required. The caller must pre-allocate an INT32 Device tensor of shape (1024,). The content is in opaque format and must not be parsed, modified, or reused across different inputs and attributes. INT32 ND (1024,) × workspaceSize Output Returns the size of the workspace to be allocated on the Device. Currently returns 0. - - - - executor Output Returns the op executor, which contains the operator computation flow. - - - - - Return Value
aclnnStatus: Return status code. For details, see aclnn return code.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Error Code Error Code Description ACLNN_ERR_PARAM_INVALID 161002 Required tensors are not passed in, or the tensor type, shape, layout, blockShape, head count relationship, maskType, quantType, softmaxPrecision, window attributes, etc. do not meet the current constraints. ACLNN_ERR_INNER_CREATE_EXECUTOR 561101 The API fails to create aclOpExecutor internally. ACLNN_ERR_INNER_NULLPTR 561103 workspaceSize or executor is null, or a null pointer exception occurs when the API internally executes Contiguous or registers AICPU tasks.
aclnnGenericBlockSparseAttentionMetadata
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. The current workspaceSize is 0, so nullptr can be passed. workspaceSize Input Size of the workspace allocated on the device, obtained by the first-phase API aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize. executor Input Op executor, which contains the operator computation flow. stream Input Specifies the Stream for task execution. Return Value
Returns an aclnnStatus status code. For details, see aclnn Error Codes.
Constraints
Baseline Description
| Name | Description |
|---|---|
| B | Batch Size, which indicates the batch size of input samples. |
| numQHeads | Head Num of the query of the main operator. |
| numKvHeads | Head Num of the key/value of the main operator. |
| headDim | Head Dim of the query, key, and value of the main operator. |
| qStorageLen_i | Query storage length of the i-th batch, obtained by differencing adjacent elements of cuSeqLengthsQOptional. |
| totalQBlocks | Total number of Q blocks after chunking by storage length, that is, $\sum_i \mathrm{ceilDiv}(qStorageLen_i, blockShapeX)$ |
| maxSparseBlockCount | Last dimension of sparseBlockIdx, which must be no less than the maximum of all elements in sparseBlockCount. |
Other Constraints
- This API must be used together with
aclnnGenericBlockSparseAttention. Shared tensors and attributes must be exactly the same as those of the subsequently called primary operator, andmetadataOptionalmust be regenerated before each call to the primary operator. For the complete constraints of the primary operator, see aclnnGenericBlockSparseAttention. - Currently, only
layoutQ="TND",layoutKv="PA_BBND",headDim=128,blockShape=[1, 128],maskType=1, andwinLeft=winRight=-1are supported. - The shape of
sparseBlockIdxis[numKvHeads, totalQBlocks, maxSparseBlockCount], and the shape ofsparseBlockCountis[numKvHeads, totalQBlocks].maxSparseBlockCountmust be greater than 0, not greater than 256, and not less than the maximum value of all elements insparseBlockCount. cuSeqLengthsQOptionalmust be passed in currently;sequsedQOptionalcan be nullptr. When sequsedQ is passed in, each element must be within the range[0, corresponding batch storage length]. Core splitting accumulates by actual length, while sparse block partitioning is still calculated based on the storage length described by the cu prefix sum.- When layoutKv is PA_BBND,
sequsedKvOptionalmust be passed in andcuSeqLengthsKvOptionalmust not be passed in. When layoutKv is TND,sequsedKvOptionalcan be used together withcuSeqLengthsKvOptional, and the dual-length semantics are the same as those on the Q side. numQHeads >= numKvHeadsandnumQHeads % numKvHeads == 0must be satisfied, andgroupSize = numQHeads / numKvHeadsmust not exceed 128.- The output
metadataOptionalis fixed to INT32 with a shape of(1024,), and must not be parsed, modified, or reused across different inputs and attributes.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include "acl/acl.h"
#include "aclnnop/aclnn_generic_block_sparse_attention_metadata.h"
aclnnStatus RunMetadata(const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount,
const aclTensor *cuSeqLengthsQOptional, const aclTensor *sequsedKvOptional,
aclTensor *metadataOptional, aclrtStream stream)
{
const int64_t blockShapeData[] = {1, 128};
aclIntArray *blockShape = aclCreateIntArray(blockShapeData, 2);
if (blockShape == nullptr) {
return ACL_ERROR_BAD_ALLOC;
}
uint64_t workspaceSize = 0;
aclOpExecutor *executor = nullptr;
aclnnStatus ret = aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize(
sparseBlockIdx, sparseBlockCount, cuSeqLengthsQOptional, nullptr, nullptr, sequsedKvOptional, 16, 2048,
32, 8, 128, blockShape, "TND", "PA_BBND", 4, 1, 0, 0, -1, -1, 0, 0, metadataOptional, &workspaceSize,
&executor);
aclDestroyIntArray(blockShape);
if (ret != ACL_SUCCESS) {
return ret;
}
void *workspace = nullptr;
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
if (ret != ACL_SUCCESS) {
return ret;
}
}
ret = aclnnGenericBlockSparseAttentionMetadata(workspace, workspaceSize, executor, stream);
if (ret == ACL_SUCCESS) {
ret = aclrtSynchronizeStream(stream);
}
if (workspace != nullptr) {
aclrtFree(workspace);
}
return ret;
}