aclnnGenericBlockSparseAttention

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: GenericBlockSparseAttention performs sparse attention computation. It supports block sparse mode with arbitrary granularity along the S axis. sparseBlockIdx specifies each Q block's selected KV blocks, and sparseBlockCount specifies the number of KV blocks retained for each Q block, enabling efficient sparse attention computation. Call aclnnGenericBlockSparseAttentionMetadata to generate metadata first.

  • Formula: Sparse block size: $blockShapeX \times blockShapeY$

    $$ attentionOut = Softmax(scaleValue \cdot query \cdot key_{sparse}^{T} + atten\_mask) \cdot value_{sparse} $$

    The input layout is specified by layoutQ and layoutKv. Currently only supports layoutQ="TND" and layoutKv="PA_BBND".

Function Prototype

Each operator uses a two-phase API. Call the "aclnnGenericBlockSparseAttentionGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the operator computation process. Then call the "aclnnGenericBlockSparseAttention" API to perform the computation.

aclnnStatus aclnnGenericBlockSparseAttentionGetWorkspaceSize(
  const aclTensor   *query,
  const aclTensor   *key,
  const aclTensor   *value,
  const aclTensor   *sparseBlockIdx,
  const aclTensor   *sparseBlockCount,
  const aclTensor   *metadataOptional,
  const aclTensor   *attenMaskOptional,
  const aclTensor   *qDequantScaleOptional,
  const aclTensor   *kDequantScaleOptional,
  const aclTensor   *vDequantScaleOptional,
  const aclTensor   *pQuantScaleOptional,
  const aclTensor   *cuSeqLengthsQOptional,
  const aclTensor   *cuSeqLengthsKvOptional,
  const aclTensor   *sequsedQOptional,
  const aclTensor   *sequsedKvOptional,
  const aclTensor   *blockTableOptional,
  const aclIntArray *blockShape,
  char              *layoutQ,
  char              *layoutKv,
  int64_t            layoutSparsePattern,
  double             scaleValue,
  int64_t            maskType,
  int64_t            quantType,
  double             dstTypeMax,
  int64_t            softmaxPrecision,
  int64_t            winLeft,
  int64_t            winRight,
  int64_t            returnSoftmaxlse,
  int64_t            residualBlockMode,
  bool               isConsistentTopK,
  aclTensor         *attentionOut,
  aclTensor         *softmaxLseOptional,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnGenericBlockSparseAttention(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  aclrtStream       stream)

aclnnGenericBlockSparseAttentionGetWorkspaceSize

  • 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
    query Input Query in the formula. Currently, only layoutQ="TND" is supported. For the shapes of other layouts, see Layout Correspondence Description. FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT4_E2M1FN, HIFLOAT8 ND [totalQTokens, headNum, headDim] ×
    key Input Key in the formula. Can be used as the original Key or Paged KV Cache. Currently only supports layoutKv="PA_BBND". For other layouts and the shape of the original KV, see layout correspondence description and Paged Attention description; for non-contiguous dim0, see Other Constraints. FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT4_E2M1FN, HIFLOAT8 ND [numBlocks, blockSize, numKeyValueHeads, headDim] √
    value Input The value in the formula. Can be used as the original Value input or Paged KV Cache input. The shape is consistent with that of key. Currently only supports layoutKv="PA_BBND". FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT4_E2M1FN, HIFLOAT8 ND Consistent with key √
    sparseBlockIdx Input Sparse block index array, specifying the KV block index selected by each Q block. The value must be a valid KV block index (blocks are divided by the storage length of cu); invalid positions can be filled with -1, and valid values must be within the first sparseBlockCount positions. For detailed reference, see Layout Correspondence Description. INT32 ND [numKeyValueHeads, totalQBlocks, maxKvBlockCount] ×
    sparseBlockCount Input Number of KV blocks actually selected for each Q block. See Layout Correspondence Description for details. INT32 ND [numKeyValueHeads, totalQBlocks] ×
    metadataOptional Input Core partitioning result of the AICPU operator aclnnGenericBlockSparseAttentionMetadata. Must be passed in. Generated by aclnnGenericBlockSparseAttentionMetadata and must be regenerated on each call. INT32 ND (1024,) ×
    attenMaskOptional Input The atten_mask in the formula. atten_mask is superimposed on the sparse pattern. See Mask Description. Currently not supported. nullptr must be passed in. BOOL ND 2 ×
    qDequantScaleOptional Input Dequantization scaling factor of the query. See Quantization-Related Description. Currently, only quantType=0/5 scenarios can pass nullptr; quantType=1-4 is currently not supported, and nullptr must be passed in. FLOAT32, FLOAT8_E8M0 ND x ×
    kDequantScaleOptional Input Dequantization scaling factor of key. See Details in Quantization-Related Description. Currently, only quantType=0/5 scenarios can pass nullptr; quantType=1-4 is currently not supported, and nullptr must be passed in. FLOAT32, FLOAT8_E8M0 ND x ×
    vDequantScaleOptional Input Dequantization scaling factor of value. See Quantization-Related Description for details. Currently, nullptr can be passed only in scenarios where quantType=0/5; quantType=1-4 is currently not supported, and nullptr must be passed in. FLOAT32, FLOAT8_E8M0 ND x ×
    pQuantScaleOptional Input Quantization coefficients required by the result matrix P of online-softmax in non-mx quantization mode. See Quantization-Related Description for details. Currently, nullptr must be passed in. FLOAT32 ND x x
    cuSeqLengthsQOptional Input Describes the query sequence length of each Batch, stored as prefix sums. Optional input, used for variable-length sequence use cases.
    • Must be passed in when layoutQ is TND.
    • When layoutQ is BNSD/BSND: if passed in, the operator processes it based on the actual sequence length specified by this input; if nullptr is passed in, the S in the shape of query is used (currently not supported).
    • Elements are prefix sums: the 0th element is 0, the last element equals totalQTokens, and each element must be ≥ the preceding element; the storage length qStorageLen_i of each batch is obtained by difference of adjacent elements, and Σ qStorageLen_i = totalQTokens must be satisfied.
    INT64 ND (B+1,) ×
    cuSeqLengthsKvOptional Input Describes the key/value sequence length of each batch, stored in the form of prefix sums. Optional input, used for variable-length sequence use cases.
    • Must be passed in when layoutKv is TND.
    • Not passed in when layoutKv is not TND (must be nullptr). Currently, only PA_BBND is supported.
    • When layoutKv is BNSD/BSND: if passed in, the operator processes it based on the actual sequence length specified by this input; if nullptr is passed in, the S in the shape of key/value is used (currently not supported).
    • Elements are prefix sums: the 0th element is 0, the last element equals the sum of the KV storage lengths of all batches, and each element must be ≥ the preceding element.
    INT64 ND (B+1,) ×
    sequsedQOptional Input Actual sequence length of query in each batch.
    • If the actual length is not specified, pass in nullptr, indicating that the storage length is the same as that obtained by difference from cuSeqLengthsQOptional.
    • If passed in, the shape is (B,). Each element must be ≥0 and ≤ the storage length of cu for the corresponding batch. For the dual-length semantics when coexisting with cu, see Other Constraints.
    INT32 ND (B,) ×
    sequsedKvOptional Input Actual sequence length of kv in each batch.
    • Must be passed in when layoutKv is PA_BBND. The shape is (B,), and each element must be ≥ 0.
    • When layoutKv is TND: if the actual length is not specified, nullptr can be passed in, indicating the same storage length as that obtained by difference from cuSeqLengthsKvOptional. If 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,) ×
    blockTableOptional Input Block table for PagedAttention. If this input is configured, PagedAttention is used. Currently, it must be passed in, and layoutKv must be PA_BBND. See Paged Attention Related Description. INT32 ND (B, maxNumBlocksPerBatch) ×
    blockShape Input Represents the sparse block shape array. Contains two elements: [blockShapeX, blockShapeY].
    blockShapeX supports any value within the int64 representation range.
    blockShapeY supports any value aligned to 16 and within the int64 representation range.
    For additional constraints when quantization is enabled, see Quantization-Related Description.
    Currently, only blockShape=[1,128] is supported.
    INT64 - - -
    layoutQ Input Represents the data layout format of the input query. Target-supported values: "TND", "BNSD", "BSND". See Layout Correspondence Description. Currently, only "TND" is supported. String - - -
    layoutKv Input Represents the data layout of input key and value. Supported targets are "TND", "BNSD", "BSND", "PA_BBND", and "PA_BNBD". See Layout Correspondence Description. Currently, only "PA_BBND" is supported. String - - -
    layoutSparsePattern Input Represents the data layout of input sparseBlockIdx and sparseBlockCount. Currently, only "4" is supported. For details, see Layout Correspondence Description. INT64 - - -
    scaleValue Input In the formula, scale represents the scaling factor. Generally set to D^-0.5; if 0 is passed in, the operator processes it as 1/√D. DOUBLE - - -
    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 range 0-5. For the complete configurations, see Quantization-Related Description:
    Currently available: 0; 5 is optional on Ascend 950. If a value of 1-4 is passed in, the check fails.
    INT64 - - -
    dstTypeMax Input Custom quantization scale passed in during MXFP4 CX quantization.
    • Custom scales are not supported in the current version. 0.0 must be passed in.
    double - - -
    softmaxPrecision Input Precision level for Softmax computation. Controls the data type used for computations in the online softmax and rescale phases. Value: 0 or 1:
    • 0: Both online softmax and rescale use fp32. Suitable for use cases requiring high computational 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.
    Chip constraints: Ascend 950 only supports 1; on Atlas A2/A3, 0 or 1 can be configured for FLOAT16, and only 0 for BFLOAT16; the FP8 path only supports 1.
    INT64 - - -
    winLeft Input In sliding window attention use cases, the number of tokens that the sliding window needs to include forward. Used for sliding window attention. Must be -1 when disabled, and must be used with maskType. See Mask Description. Currently, only -1 is supported. INT64 - - -
    winRight Input In sliding window attention use cases, the number of tokens that the sliding window needs to include backward. Used for sliding window attention; must be -1 when not enabled and must be used together with maskType. See Mask Description. Currently only supports -1. INT64 - - -
    returnSoftmaxlse Input Flag indicating whether softmaxLse output is enabled. Currently only supports 0
    • 0: Indicates that softmaxLse is not output, and nullptr must be passed in for softmaxLseOptional.
    INT64 - - -
    residualBlockMode Input Indicates the state of the trailing block after the KV sequence is sparsified in units of blockShapeY. Currently, only 0 or 1 is supported. For 0, whether the trailing block participates in the computation is determined by the value passed in via sparseBlockIdx. For 1, the trailing incomplete block must participate in the computation but must not be included in sparseBlockIdx. INT64 - - -
    isConsistentTopK Input Whether the maximum number of KV blocks selected by each Q block is consistent within the same batch and the same head when the preceding operator performs sparse block selection. Only 0 or 1 is supported. 0 indicates inconsistency, and 1 indicates consistency. BOOL - -
    attentionOut Output attentionOut in the formula. Data type and shape are consistent with query. Currently, only layoutQ="TND" is supported. FLOAT16, BFLOAT16 (specified by this tensor when the input is FP8) ND Consistent with query √
    softmaxLseOptional Output Intermediate log-sum-exp result of the Softmax computation. Currently not supported; returnSoftmaxlse must be set to 0, and nullptr must be passed in. FLOAT ND 3 √
    workspaceSize Output Returns the workspace size required for Device side application. - - - - -
    executor Output Returns the op executor, including the operator computation process. - - - - -
  • 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:

    Return Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 Mandatory pointers such as query/key/value/sparseBlockIdx/sparseBlockCount/attentionOut are null.
    ACLNN_ERR_PARAM_INVALID 161002 Parameters such as layout, maskType, blockShape, softmaxPrecision, quantType, returnSoftmaxlse, layoutSparsePattern, residualBlockMode, and isConsistentTopK do not match the constraints.
    ACLNN_ERR_INNER_NULLPTR 561103 The metadata is null or Contiguous/InferShape fails (for example, unsupported layout or missing blockTable).

aclnnGenericBlockSparseAttention

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address of the Device side application.
    workspaceSize Input Size of the Device side application workspace, obtained by calling the first-phase API aclnnGenericBlockSparseAttentionGetWorkspaceSize.
    executor Input Op executor containing the operator computation flow.
    stream Input Stream that executes tasks.
  • Return Value

    Returns aclnnStatus status codes. For details, see aclnn Return Code.

Constraints

Baseline Description

Common fields in the documentation constraints are defined as follows:

NameMeaning
BBatch Size, the batch size of input samples.
SSequence Length, sequence length.
HHead Size, size of the hidden layer.
NHead Num, number of heads.
DHead Dim, head dimension, where D=H/N.
TSum of sequence lengths of all batches.
totalQTokensT of the query.
totalKTokensT of the key.
totalVTokensT of the value.
headNumN of the query.
numKeyValueHeadsN of key/value.
headDimD
batchB
maxQSeqLengthS of the query in BNSD/BSND format.
maxKvSeqLengthS of key/value in BNSD/BSND format.
numBlocksNumber of physical pages of the Paged KV Cache.
blockSizeNumber of tokens each page holds.
maxNumBlocksPerBatchSecond dimension of blockTable, which must be ≥ ceilDiv(maxKvSeqLength, blockSize).
qStorageLen_iStorage length of each batch obtained by difference of the prefix sum of cuSeqLengthsQ.
totalQBlocksTotal number of Q blocks after chunking by storage length, i.e., $\sum_i \mathrm{ceilDiv}(qStorageLen_i, blockShapeX)$
totalKBlocksTotal number of KV blocks after chunking by storage length, i.e., $\sum_i \mathrm{ceilDiv}(kvStorageLen_i, blockShapeY)$
maxKvBlockCountLast dimension of sparseBlockIdx, which must be no less than the maximum of all elements in sparseBlockCount. The current upper limit is 256.
blockShapeX / blockShapeYSize of sparse blocks in the Q and KV directions.

Layout Correspondence Description

layoutQ layoutKv Description
TND TND Used for original KV input, in use cases where seqlen of each batch is concatenated.
PA_BBND Used for Paged KV Cache input, with data arranged as [numBlocks, blockSize, numKeyValueHeads, headDim].
PA_BNBD Used for Paged KV Cache input, with data arranged as [numBlocks, numKeyValueHeads, blockSize, headDim].
BSND BSND Used for original KV input.
PA_BBND Used for Paged KV Cache input. Data is arranged in the [numBlocks, blockSize, numKeyValueHeads, headDim] layout.
PA_BNBD Used for Paged KV Cache input. Data is arranged in the [numBlocks, numKeyValueHeads, blockSize, headDim] layout.
BNSD BNSD Used for original KV input.
PA_BBND Used for Paged KV Cache input. Data is arranged in the [numBlocks, blockSize, numKeyValueHeads, headDim] layout.
PA_BNBD Used for Paged KV Cache input, with data laid out in [numBlocks, numKeyValueHeads, blockSize, headDim].

Currently supported combination: layoutQ="TND" + layoutKv="PA_BBND". Other layoutQ/layoutKv combinations are currently not supported.

The shapes of query and attentionOut are determined by layoutQ:

layoutQ shape Currently Supported
TND [totalQTokens, headNum, headDim] √
BNSD [batch, headNum, maxQSeqLength, headDim] ×
BSND [batch, maxQSeqLength, headNum, headDim] ×

The shapes of sparseBlockIdx and sparseBlockCount are determined by layoutSparsePattern. Currently, layoutSparsePattern only supports the value 4.

layoutSparsePattern sparseBlockIdx sparseBlockCount Description
0 [batch, numKeyValueHeads, maxQBlockCount, maxKvBlockCount] [batch, numKeyValueHeads, maxQBlockCount]
  • qHeads in the same Group share sparsePattern.
  • Indicates which KV blocks are selected by each Q block.
1 [batch, numKeyValueHeads, maxKvBlockCount, maxQBlockCount] [batch, numKeyValueHeads, maxKvBlockCount]
  • qHeads in the same Group share sparsePattern.
  • Indicates which Q blocks are selected by each KV block.
2 [batch, headNum, maxQBlockCount, maxKvBlockCount] [batch, headNum, maxQBlockCount]
  • qHeads in the same Group have independent sparsePattern.
  • Indicates which KV blocks are selected by each Q block.
3 [batch, headNum, maxKvBlockCount, maxQBlockCount] [batch, headNum, maxKvBlockCount]
  • qHeads in the same Group have independent sparsePatterns
  • Indicates the Q blocks selected by each KV block
4 [numKeyValueHeads, totalQBlocks, maxKvBlockCount] [numKeyValueHeads, totalQBlocks]
  • qHeads in the same Group share the sparsePattern
  • Indicates the KV blocks selected by each Q block
5 [numKeyValueHeads, totalKBlocks, maxQBlockCount] [numKeyValueHeads, totalKBlocks]
  • qHeads in the same Group share sparsePattern.
  • Indicates which Q blocks are selected by each KV block.
6 [headNum, totalQBlocks, maxKvBlockCount] [headNum, totalQBlocks]
  • Each qHead in the same Group has an independent sparsePattern.
  • Indicates which KV blocks are selected by each Q block.
7 [headNum, totalKBlocks, maxQBlockCount] [headNum, totalKBlocks]
  • Each qHead in the same Group has an independent sparsePattern.
  • Indicates which Q blocks are selected by each KV block.

The shapes of key and value are determined by layoutKv and whether Paged Cache is enabled. See Paged Attention Related Description.

blockTable kvLayout Key/Value
Non-empty, with shape [batch, maxNumBlocksPerBatch], indicating that paged cache is enabled. PA_BBND [numBlocks, blockSize, numKeyValueHeads, headDim]
PA_BNBD [numBlocks, numKeyValueHeads, blockSize, headDim]
Empty, indicating that paged cache is disabled and the operator receives the original KV input. TND [totalKTokens, numKeyValueHeads, headDim]
BSND [batch, maxKvSeqLength, numKeyValueHeads, headDim]
BNSD [batch, numKeyValueHeads, maxKvSeqLength, headDim]

Currently, a non-empty blockTable must be passed in, and layoutKv must be PA_BBND. blockTable set to nullptr (original KV) and PA_BNBD are currently not supported.

The following quantization configurations are described by the Ascend 950 (A5) generation; quantType=0 is Currently Available, and quantType=5 is Optional on Ascend 950.

quantType QKV Data Type Symmetric/Asymmetric Dynamic/Static P Quantization Quantization Granularity Quantization Parameter Shape Quantization Parameter dType
0 Non-quantization. QKV is directly used as input for computation. - - - qDequantScaleOptional(not passed)
kDequantScaleOptional(not passed)
vDequantScaleOptional(not passed)
pQuantScaleOptional(not passed)
-
1 FLOAT8_E4M3 Symmetric Static perGroup. QKV are all grouped along the S dimension, and the group size must be the same as the sparse block size;
Specifically, when KV is a paged cache, blockSize must be an integer multiple of blockShapeY.
qDequantScaleOptional(required):
  • TND: [batch*ceilDiv(qSeqLength, blockShapeX), headNum, 1]
  • BNSD: [batch, headNum, ceilDiv(maxQSeqLength, blockShapeX), 1]
  • BSND: [batch, ceilDiv(maxQSeqLength, blockShapeX), headNum, 1]
kDequantScaleOptional(required):
  • TND: [batch*ceilDiv(qSeqLength, blockShapeY), kvHeadNum, 1]
  • BNSD: [batch, kvHeadNum, ceilDiv(maxKvSeqLength, blockShapeY), 1]
  • BSND: [batch, ceilDiv(maxKvSeqLength, blockShapeY), kvHeadNum, 1]
  • PA_BBND: [batch, ceilDiv(blockSize, blockShapeY), kvHeadNum, 1]
  • PA_BNBD: [batch, kvHeadNum, ceilDiv(blockSize, blockShapeY), 1]
vDequantScaleOptional(required):
  • TND: [batch*ceilDiv(qSeqLength, blockShapeY), kvHeadNum, 1]
  • BNSD: [batch, kvHeadNum, ceilDiv(maxKvSeqLength, blockShapeY), 1]
  • BSND: [batch, ceilDiv(maxKvSeqLength, blockShapeY), kvHeadNum, 1]
  • PA_BBND: [batch, ceilDiv(blockSize, blockShapeY), kvHeadNum, 1]
  • PA_BNBD: [batch, kvHeadNum, ceilDiv(blockSize, blockShapeY), 1]
pQuantScaleOptional(optional):
  • When passed in, contains only a single element, used by users to control the static quantization scaling factor of P: [1].
  • nullptr: The operator defaults the static quantization scaling factor of P to 448.0.
FLOAT32
2 Dynamic micro scaling. QKV are grouped along the matrix multiplication accumulation axis with a fixed group size of 32;
Specifically, when KV is a paged cache, blockSize must be an integer multiple of 64.
qDequantScaleOptional(required):
  • TND: [totalQTokens, headNum, ceilDiv(headDim, 64), 2]
  • BNSD: [batch, headNum, maxQSeqLength, ceilDiv(headDim, 64), 2]
  • BSND: [batch, maxQSeqLength, headNum, ceilDiv(headDim, 64), 2]
kDequantScaleOptional(required):
  • TND: [totalKTokens, kvHeadNum, ceilDiv(headDim, 64), 2]
  • BNSD: [batch, kvHeadNum, maxKvSeqLength, ceilDiv(headDim, 64), 2]
  • BSND: [batch, maxKvSeqLength, kvHeadNum, ceilDiv(headDim, 64), 2]
  • PA_BBND: [batch, blockSize, kvHeadNum, ceilDiv(headDim, 64), 2]
  • PA_BNBD: [batch, kvHeadNum, blockSize, ceilDiv(headDim, 64), 2]
vDequantScaleOptional(required):
  • TND: [batch*ceilDiv(kvSeqLength, 64), kvHeadNum, headDim, 2]
  • BNSD: [batch, kvHeadNum, ceilDiv(maxKvSeqLength, 64), headDim, 2]
  • BSND: [batch, ceilDiv(maxKvSeqLength, 64), kvHeadNum, headDim, 2]
  • PA_BBND: [batch, ceilDiv(blockSize, 64), kvHeadNum, headDim, 2]
  • PA_BNBD: [batch, kvHeadNum, ceilDiv(blockSize, 64), headDim, 2]
FLOAT8_E4M3
3 FLOAT4_E2M1 Dynamic OCP
4 Dynamic CX
5 FLOAT8_E4M3 Symmetric Static Quantization coefficients are not passed in; instead, P is directly cast to fp8 in the operator. qDequantScaleOptional(not passed in)
kDequantScaleOptional(not passed in)
vDequantScaleOptional(not passed in)
pQuantScaleOptional(not passed in)
FLOAT32

Currently, quantType=0 is available; quantType=5 is optional on Ascend 950. quantType=1-4 is currently not supported.

Mask Description

maskType Meaning attentionMaskOptional winLeft/winRight
0 No mask is added. Not passed in -1/-1
1 causal mask Do not pass attenMaskOptional (built-in causal); plan a BOOL [2048,2048] lower triangle. -1/-1
2 window mask Plan: BOOL [2048,2048] lower triangle, used together with winLeft/winRight. Number of tokens the window actually includes for forward/backward attention.
3-5 Various specialized masks Mask description to be added later. -1/-1

Currently only supports maskType=1 (causal is built in the operator, attenMaskOptional must be nullptr, and winLeft/winRight are -1). maskType 0/2/3-5 is currently not supported.

Other Constraints

  • Deterministic computation: aclnnGenericBlockSparseAttention defaults to a deterministic implementation.
  • Before calling this API, run aclnnGenericBlockSparseAttentionMetadata to generate metadataOptional; the metadata must match the current inputs/attributes and must be regenerated for each call.
  • The headDim(D) of query/key/value currently only supports 128; the KV page blockSize currently only supports 128 and must be equal to blockShapeY.
  • For TND: totalQBlocks is blocked by the storage length obtained by differencing cuSeqLengthsQ, i.e., $\sum_i \mathrm{ceilDiv}(qStorageLen_i, blockShapeX)$; both sparse blocking and QKV addressing use this storage length and are not re-split by seqused.
  • When layoutKv is PA_BBND, sequsedKvOptional must be passed in, and cuSeqLengthsKvOptional must not be passed.
  • When seqused and the corresponding cu prefix sum are passed in together (on the Q side, and on the KV side when layoutKv is TND): the core splitting/task space is accumulated based on the actual valid length (seqused) of each batch; the seqused element of each batch must be ≤ the corresponding cu storage length and must be exactly the same as that on the Metadata side.
  • The data types of the input query, key, and value must be consistent.
  • Under PA_BBND, only dim0 (physical page axis) of key/value can be non-contiguous; blockSize×numKeyValueHeads×headDim within a page must be contiguous; stride0 must be ≥ blockSize×numKeyValueHeads×headDim and aligned to numKeyValueHeads×headDim.

Example

The following sample code is for reference only. For details about compiling and running, see Compile and Run Samples.

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <numeric>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_generic_block_sparse_attention.h"
#include "aclnnop/aclnn_generic_block_sparse_attention_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)

namespace {

int64_t GetShapeSize(const std::vector<int64_t>& shape)
{
  int64_t shapeSize = 1;
  for (auto i : shape) {
    shapeSize *= i;
  }
  return shapeSize;
}

uint16_t FloatToFp16(float f)
{
  uint32_t bits;
  std::memcpy(&bits, &f, sizeof(bits));
  uint32_t sign = (bits >> 31) & 0x1u;
  int32_t exp = static_cast<int32_t>((bits >> 23) & 0xffu) - 127 + 15;
  uint32_t mant = (bits >> 13) & 0x3ffu;
  if (exp <= 0) {
    return static_cast<uint16_t>(sign << 15);
  }
  if (exp >= 31) {
    return static_cast<uint16_t>((sign << 15) | 0x7c00u);
  }
  return static_cast<uint16_t>((sign << 15) | (static_cast<uint32_t>(exp) << 10) | mant);
}

float Fp16ToFloat(uint16_t h)
{
  uint32_t sign = (h >> 15) & 0x1u;
  uint32_t exp = (h >> 10) & 0x1fu;
  uint32_t mant = h & 0x3ffu;
  uint32_t f;
  if (exp == 0) {
    f = (sign << 31) | (mant << 13);
  } else if (exp == 31) {
    f = (sign << 31) | 0x7f800000u | (mant << 13);
  } else {
    f = (sign << 31) | ((exp + 127u - 15u) << 23) | (mant << 13);
  }
  float result;
  std::memcpy(&result, &f, sizeof(result));
  return result;
}

void PrintOutResult(const std::vector<int64_t>& shape, void** deviceAddr)
{
  auto size = GetShapeSize(shape);
  std::vector<uint16_t> resultData(size, 0);
  auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
                         size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
  for (int64_t i = 0; i < size && i < 10; i++) {
    LOG_PRINT("result[%ld] is: %f\n", i, Fp16ToFloat(resultData[i]));
  }
}

int Init(int32_t deviceId, aclrtContext* context, 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 = aclrtCreateContext(context, deviceId);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSetCurrentContext(*context);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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);
  if (size > 0) {
    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);
  } else {
    *deviceAddr = nullptr;
  }

  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;
}

std::vector<uint16_t> MakeFp16Data(int64_t size, float value)
{
  std::vector<uint16_t> data(static_cast<size_t>(size), FloatToFp16(value));
  return data;
}

}  // namespace

int main()
{
  // 1. (boilerplate) Initialize device/stream. For details, see the acl API manual.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtContext context = nullptr;
  aclrtStream stream = nullptr;
  auto ret = Init(deviceId, &context, &stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // Regular path smoke case: TND query + PA_BBND KV
  int64_t B = 1;
  int64_t S1 = 4;
  int64_t S2 = 256;
  int64_t N1 = 4;
  int64_t N2 = 1;
  int64_t D = 128;
  int64_t topK = 2;
  int64_t blockSize = 128;
  int64_t blockShapeX = 1;
  double scaleValue = 1.0 / sqrt(static_cast<double>(D));

  int64_t T = B * S1;
  int64_t maxBlocks = (S2 + blockSize - 1) / blockSize;
  int64_t totalQBlocks = T;  // blockShapeX == 1

  // 2. Construct inputs and outputs as required by the API definition.
  std::vector<int64_t> qShape = {T, N1, D};
  std::vector<int64_t> kvShape = {maxBlocks, blockSize, N2, D};
  std::vector<int64_t> sparseIdxShape = {N2, totalQBlocks, topK};
  std::vector<int64_t> sparseCountShape = {N2, totalQBlocks};
  std::vector<int64_t> blockTableShape = {B, maxBlocks};
  std::vector<int64_t> cuSeqQShape = {B + 1};
  std::vector<int64_t> sequsedKvShape = {B};
  std::vector<int64_t> metadataShape = {1024};
  std::vector<int64_t> attnOutShape = {T, N1, D};

  void* qDeviceAddr = nullptr;
  void* kDeviceAddr = nullptr;
  void* vDeviceAddr = nullptr;
  void* sparseIdxDeviceAddr = nullptr;
  void* sparseCountDeviceAddr = nullptr;
  void* metadataDeviceAddr = nullptr;
  void* cuSeqQDeviceAddr = nullptr;
  void* sequsedKvDeviceAddr = nullptr;
  void* blockTableDeviceAddr = nullptr;
  void* attnOutDeviceAddr = nullptr;

  aclTensor* q = nullptr;
  aclTensor* k = nullptr;
  aclTensor* v = nullptr;
  aclTensor* sparseIdx = nullptr;
  aclTensor* sparseCount = nullptr;
  aclTensor* metadata = nullptr;
  aclTensor* cuSeqQ = nullptr;
  aclTensor* sequsedKv = nullptr;
  aclTensor* blockTable = nullptr;
  aclTensor* attnOut = nullptr;

  int64_t qSize = GetShapeSize(qShape);
  int64_t kvSize = GetShapeSize(kvShape);
  int64_t sparseIdxSize = GetShapeSize(sparseIdxShape);
  int64_t sparseCountSize = GetShapeSize(sparseCountShape);
  int64_t blockTableSize = GetShapeSize(blockTableShape);
  int64_t attnOutSize = GetShapeSize(attnOutShape);

  std::vector<uint16_t> qHostData = MakeFp16Data(qSize, 1.0f);
  std::vector<uint16_t> kHostData = MakeFp16Data(kvSize, 1.0f);
  std::vector<uint16_t> vHostData = MakeFp16Data(kvSize, 1.0f);
  std::vector<int32_t> sparseIdxHostData(sparseIdxSize, -1);
  std::vector<int32_t> sparseCountHostData(sparseCountSize, 0);
  std::vector<int32_t> blockTableHostData(blockTableSize);
  std::iota(blockTableHostData.begin(), blockTableHostData.end(), 0);
  std::vector<int64_t> cuSeqQHostData = {0, S1};
  std::vector<int32_t> sequsedKvHostData = {static_cast<int32_t>(S2)};
  std::vector<int32_t> metadataHostData(1024, 0);
  std::vector<uint16_t> attnOutHostData = MakeFp16Data(attnOutSize, 0.0f);

  // Causal-like sparse window: keep up to topK trailing KV blocks per Q token.
  int64_t history = S2 - S1;
  for (int64_t qBlock = 0; qBlock < totalQBlocks; qBlock++) {
    int64_t visible = history + qBlock + 1;
    int64_t lastKvBlock = std::min(maxBlocks - 1, (visible - 1) / blockSize);
    int64_t count = std::min(topK, lastKvBlock + 1);
    int64_t start = lastKvBlock - count + 1;
    for (int64_t i = 0; i < count; i++) {
      sparseIdxHostData[qBlock * topK + i] = static_cast<int32_t>(start + i);
    }
    sparseCountHostData[qBlock] = static_cast<int32_t>(count);
  }

  ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(kHostData, kvShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(vHostData, kvShape, &vDeviceAddr, aclDataType::ACL_FLOAT16, &v);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(sparseIdxHostData, sparseIdxShape, &sparseIdxDeviceAddr, aclDataType::ACL_INT32, &sparseIdx);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(sparseCountHostData, sparseCountShape, &sparseCountDeviceAddr, aclDataType::ACL_INT32,
                        &sparseCount);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(metadataHostData, metadataShape, &metadataDeviceAddr, aclDataType::ACL_INT32, &metadata);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cuSeqQHostData, cuSeqQShape, &cuSeqQDeviceAddr, aclDataType::ACL_INT64, &cuSeqQ);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(sequsedKvHostData, sequsedKvShape, &sequsedKvDeviceAddr, aclDataType::ACL_INT32, &sequsedKv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(blockTableHostData, blockTableShape, &blockTableDeviceAddr, aclDataType::ACL_INT32,
                        &blockTable);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(attnOutHostData, attnOutShape, &attnOutDeviceAddr, aclDataType::ACL_FLOAT16, &attnOut);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  const int64_t blockShapeData[] = {blockShapeX, blockSize};
  aclIntArray* blockShape = aclCreateIntArray(blockShapeData, 2);
  CHECK_RET(blockShape != nullptr, LOG_PRINT("aclCreateIntArray failed\n"); return -1);

  char layoutQ[] = "TND";
  char layoutKv[] = "PA_BBND";

  // 3. Call Metadata first, and then call the main operator.
  uint64_t metadataWorkspaceSize = 0;
  aclOpExecutor* metadataExecutor = nullptr;
  ret = aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize(
      sparseIdx, sparseCount, cuSeqQ, nullptr, nullptr, sequsedKv, S1, S2, N1, N2, D, blockShape, layoutQ, layoutKv, 4, 1,
      0, 1, -1, -1, 0, 0, metadata, &metadataWorkspaceSize, &metadataExecutor);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize failed. ERROR: %d\n", ret);
            return ret);

  void* metadataWorkspaceAddr = nullptr;
  if (metadataWorkspaceSize > 0) {
    ret = aclrtMalloc(&metadataWorkspaceAddr, metadataWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate metadata workspace failed. ERROR: %d\n", ret); return ret);
  }

  ret = aclnnGenericBlockSparseAttentionMetadata(metadataWorkspaceAddr, metadataWorkspaceSize, metadataExecutor,
                                                 stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGenericBlockSparseAttentionMetadata failed. ERROR: %d\n", ret);
            return ret);

  // 4. (boilerplate) Wait synchronously for the task execution to complete.
  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream after metadata failed. ERROR: %d\n", ret);
            return ret);

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor = nullptr;
  ret = aclnnGenericBlockSparseAttentionGetWorkspaceSize(
      q, k, v, sparseIdx, sparseCount, metadata, nullptr, nullptr, nullptr, nullptr, nullptr, cuSeqQ, nullptr, nullptr,
      sequsedKv, blockTable, blockShape, layoutQ, layoutKv, 4, scaleValue, 1, 0, 0.0, 1, -1, -1, 0, 0, 0, attnOut, nullptr,
      &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnGenericBlockSparseAttentionGetWorkspaceSize 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 = aclnnGenericBlockSparseAttention(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGenericBlockSparseAttention 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);

  // 5. Obtain the output value and copy the result from the device side to the host side. Modify it as required by the API definition.
  PrintOutResult(attnOutShape, &attnOutDeviceAddr);

  // 6. Release aclTensor. Modify it as required by the API definition.
  aclDestroyIntArray(blockShape);
  aclDestroyTensor(q);
  aclDestroyTensor(k);
  aclDestroyTensor(v);
  aclDestroyTensor(sparseIdx);
  aclDestroyTensor(sparseCount);
  aclDestroyTensor(metadata);
  aclDestroyTensor(cuSeqQ);
  aclDestroyTensor(sequsedKv);
  aclDestroyTensor(blockTable);
  aclDestroyTensor(attnOut);

  // 7. Release device resources.
  aclrtFree(qDeviceAddr);
  aclrtFree(kDeviceAddr);
  aclrtFree(vDeviceAddr);
  aclrtFree(sparseIdxDeviceAddr);
  aclrtFree(sparseCountDeviceAddr);
  aclrtFree(metadataDeviceAddr);
  aclrtFree(cuSeqQDeviceAddr);
  aclrtFree(sequsedKvDeviceAddr);
  aclrtFree(blockTableDeviceAddr);
  aclrtFree(attnOutDeviceAddr);
  if (metadataWorkspaceSize > 0) {
    aclrtFree(metadataWorkspaceAddr);
  }
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtDestroyContext(context);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}