aclnnMixedQuantSparseFlashMla
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:
The
aclnnMixedQuantSparseFlashMlaoperator performs MLA (Multi-head Latent Attention) attention computation in quantization and sparsity use cases. This API supports the following three computation modes:- SWA (Sliding Window Attention): Only
oriKvOptionalis passed in to perform sliding window attention on the original KV. - CSA (Compressed Sparse Attention):
oriKvOptional,cmpKvOptional, andcmpSparseIndicesOptionalare passed in together to perform attention on both the original KV window and the compressed KV selected by topK. - HCA (Heavily Compressed Attention): Pass in both
oriKvOptionalandcmpKvOptional. Compute attention jointly over the original KV window and the continuous compressed KV segments.
Atlas A2 products andAtlas A3 products support TurboQuant TQ4, which is enabled through the existing quantization mode parameterquantMode=3and supports only the CSA path. The DeepSeek V4 framework currently enables this capability only for C4-compressed KV. The API name, number and order of parameters, declaration types, default values, return values, and aclnn two-phase API call form remain unchanged.Ascend 950PR&950DT products use the existingquantMode=1andquantMode=2quantization modes.For the KV data type, storage layout, and codebook conventions of TurboQuant TQ4, see the description of the
quantModeparameter. Compared with 1024 bytes for 512-dimensional BFLOAT16, the payload of a single quantized token is reduced by about 74.8% (about 3.97x compression). For the entire KV cache, the benefit must also account for the non-quantized portions, physical page strides, and alignment overhead, and cannot be directly estimated using this ratio.aclnnMixedQuantSparseFlashMlaMetadatais the core split information ofaclnnMixedQuantSparseFlashMlaand is generated before the main operator is executed. In the current version, this metadata must be passed in for the main operator. The typical call procedure is as follows:This API is not recommended for standalone use. Use it together with the aclnnMixedQuantSparseFlashMlaMetadata API to form a complete workflow.
- Prepare the corresponding inputs based on the use case.
- Call
aclnnMixedQuantSparseFlashMlaMetadatato generatemetadataas an input parameter ofaclnnMixedQuantSparseFlashMla. - Call
aclnnMixedQuantSparseFlashMlato generate the computation result.
- SWA (Sliding Window Attention): Only
Formula:
$$ O = \text{softmax}(Q \cdot \tilde{K}^T \cdot \text{softmax\_scale}) \cdot \tilde{V} $$Among them, $\tilde{K} = \tilde{V}$ (shared KV), and $\tilde{K}$ is concatenated from the original KV within the sliding window and the compressed KV within the causal boundary. The specific KV range actually participating in the computation is determined by the template mode and the mask parameter:
Sliding window part (oriKv): For the $i_{S1}$-th Query token, its causal diagonal position is $\text{oriThreshold} = S2_{act} - S1_{act} + i_{S1} + 1$, and the window range is $[\max(\text{oriThreshold} - \text{oriWinLeft} - 1, 0), \text{oriThreshold} + \text{oriWinRight})$.
Compressed KV part (cmpKv): The causal boundary threshold is $\text{cmpThreshold} = \lfloor \frac{\text{oriThreshold}}{\text{cmpRatio}} \rfloor$. In the HCA use case, the continuous compressed KV within $[0, \text{cmpThreshold})$ is taken; in the CSA use case, blocks are collected from the compressed KV on demand via TopK indices, and only blocks with $\text{beginIdx} < \text{cmpThreshold}$ are retained.
The attention computation adopts Online Softmax (Flash Attention V2). The S2 direction is iterated in chunks of 512, and sinks serves as the initial maximum value of the softmax for each row:
$$ \text{rowMax}^{(0)} = \text{sinks}[g], \quad \text{rowSum}^{(0)} = 1.0, \quad O^{(0)} = 0 $$$$ S^{(t)} = Q \cdot K_{tile}^{(t)T} \cdot \text{softmaxScale} $$$$ \text{rowMax}^{(t+1)} = \max(\text{rowMax}^{(t)}, \max(S^{(t)}, \text{dim}=-1)) $$$$ \text{rowSum}^{(t+1)} = \exp(\text{rowMax}^{(t)} - \text{rowMax}^{(t+1)}) \cdot \text{rowSum}^{(t)} + \sum \exp(S^{(t)} - \text{rowMax}^{(t+1)}) $$$$ O^{(t+1)} = \exp(\text{rowMax}^{(t)} - \text{rowMax}^{(t+1)}) \cdot O^{(t)} + \exp(S^{(t)} - \text{rowMax}^{(t+1)}) \cdot V_{tile}^{(t)} $$$$ O_{final} = O^{(T_{s2})} / \text{rowSum}^{(T_{s2})} $$Symbol Description
Symbol Meaning $Q$ Query input, shape [G, D] (single row). $K_{tile}^{t}$ KV data of the t-th S2 tile, where K=V (shared KV). $S_t$ Scaled QK attention scores of the t-th tile. $P_t$ Softmax probabilities of the t-th tile. $O_t$ Accumulated output after the t-th tile. $softmaxScale$ Scale factor, usually the reciprocal of the square root of each attention head dimension. $B$ Batch Size $S1$/$S1_{act}$ Query sequence length/actual valid length. $S2$/$S2_{act}$ Original KV sequence length/actual valid length. $N1$ Number of Query heads. $N2$ Number of KV heads. $G$ GQA grouping ratio, $G=N1/N2$ $D$ Dimension of each attention head. $sinks$ Attention sinks, shape [N1]. $cmpRatio$ Compression ratio of cmpKv, used to convert the mask on the cmp side to the KV length before compression.
Function Prototype
Each operator uses a two-phase API. Call the aclnnMixedQuantSparseFlashMlaGetWorkspaceSize API first to obtain the workspace size required for the computation and the executor that contains the operator computation process. Then call the aclnnMixedQuantSparseFlashMla API to perform the actual computation.
aclnnStatus aclnnMixedQuantSparseFlashMlaGetWorkspaceSize(
const aclTensor *q,
const aclTensor *oriKvOptional,
const aclTensor *cmpKvOptional,
const aclTensor *oriSparseIndicesOptional,
const aclTensor *cmpSparseIndicesOptional,
const aclTensor *oriBlockTableOptional,
const aclTensor *cmpBlockTableOptional,
const aclTensor *cuSeqlensQOptional,
const aclTensor *cuSeqlensOriKvOptional,
const aclTensor *cuSeqlensCmpKvOptional,
const aclTensor *sequsedQOptional,
const aclTensor *sequsedOriKvOptional,
const aclTensor *sequsedCmpKvOptional,
const aclTensor *cmpResidualKvOptional,
const aclTensor *oriTopkLengthOptional,
const aclTensor *cmpTopkLengthOptional,
const aclTensor *sinksOptional,
const aclTensor *metadataOptional,
int64_t quantMode,
int64_t ropeHeadDim,
double softmaxScale,
int64_t cmpRatio,
int64_t oriMaskMode,
int64_t cmpMaskMode,
int64_t oriWinLeft,
int64_t oriWinRight,
const char *layoutQOptional,
const char *layoutKvOptional,
int64_t topkValueMode,
bool returnSoftmaxLse,
const aclTensor *attnOut,
const aclTensor *softmaxLseOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMixedQuantSparseFlashMla(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMixedQuantSparseFlashMlaGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor q (aclTensor*) Input Query input tensor. Empty tensors are not supported. qN supports 1-128; D supports 512 only. BFLOAT16 ND - When layoutQOptional is BSND: (b, qS, qN, qD)
- When layoutQOptional is TND: (qT, qN, qD)
× oriKvOptional (aclTensor*) Input Original KV input tensor. Key and Value share the same data. Must be passed in. See quantMode for the data type and KV storage layout. See quantMode ND - If layoutKvOptional is PA_BBND: (oriKvBlockNums, oriKvBlockSize, kvN, kvD), where oriKvBlockSize supports 1 to 1024
- If layoutKvOptional is BSND: (b, oriKvS, kvN, kvD)
- If layoutKvOptional is TND: (oriKvT, kvN, kvD)
√ cmpKvOptional (aclTensor*) Input Compressed KV input tensor. Key and Value share the same data. Must be passed in for CSA/HCA use cases, and not passed in for SWA use cases. See quantMode for the data type and KV storage layout. See quantMode ND - When layoutKvOptional is PA_BBND: (cmpKvBlockNums, cmpKvBlockSize, kvN, kvD). cmpKvBlockSize supports 1 to 1024.
- When layoutKvOptional is BSND: (b, cmpKvS, kvN, kvD)
- When layoutKvOptional is TND: (cmpKvT, kvN, kvD)
√ oriSparseIndicesOptional (aclTensor*) Input Represents the index for discrete retrieval from oriKvCache. Optional input. Invalid positions are filled with -1, and the rest are non-negative integers. INT32 ND - When layoutQOptional is BSND: (b, qS, kvN, oriKvK)
- When layoutQOptional is TND: (qT, kvN, oriKvK)
× cmpSparseIndicesOptional (aclTensor*) Input Represents the TopK indices for discrete selection of cmpKvCache. Must be passed in for the sparse use case of cmpKvOptional, and not passed in otherwise. Invalid positions are filled with -1, and others are non-negative integers. INT32 ND - If layoutQOptional is BSND: (b, qS, kvN, cmpKvK)
- If layoutQOptional is TND: (qT, kvN, cmpKvK)
× oriBlockTableOptional (aclTensor*) Input Block mapping table used for oriKvCache storage in PageAttention. Must be passed in when layoutKvOptional is PA_BBND. The length of the second dimension must be greater than or equal to the number of blocks corresponding to the largest S2 in all batches. INT32 ND (b, Ceil(oriKvSMax/oriKvBlockSize)) × cmpBlockTableOptional (aclTensor*) Input Block mapping table used for cmpKvCache storage in PageAttention. Must be passed in when cmpKvOptional is passed in and layoutKvOptional is PA_BBND. INT32 ND (b, Ceil(cmpKvSMax/cmpKvBlockSize)) × cuSeqlensQOptional (aclTensor*) Input Represents the number of valid tokens of q in different batches (in prefix sum form). Must be passed in when layoutQOptional is TND. Each element represents the total number of tokens in the current batch and all previous batches. INT32 ND (b+1,) × cuSeqlensOriKvOptional (aclTensor*) Input Indicates the number of valid tokens of oriKv in different batches (prefix sum form). Must be passed in when layoutKvOptional is TND. INT32 ND (b+1,) × cuSeqlensCmpKvOptional (aclTensor*) Input Indicates the number of valid cmpKv tokens in different batches (prefix sum form). Must be passed in when layoutKvOptional is TND and cmpKvOptional exists. INT32 ND (b+1,) × sequsedQOptional (aclTensor*) Input Indicates the number of tokens of q that actually participate in computation in each batch. layoutQOptional is optional and used to specify the valid length of q for each batch. INT32 ND (b,) × sequsedOriKvOptional(aclTensor*) Input Indicates the number of tokens of oriKv that actually participate in computation in each batch. Must be passed in when layoutKvOptional is PA_BBND and oriTopkLengthOptional is not passed in; optional when layoutKvOptional is BSND, used to specify the valid length of oriKv for each batch; when layoutKvOptional is TND, cuSeqlensOriKvOptional is used to indicate the sequence boundaries. INT32 ND (b,) × sequsedCmpKvOptional (aclTensor*) Input Indicates the number of cmpKv tokens that actually participate in the computation in different batches. Optional input. If passed in, the shape must be (B,). It is used as the logical valid length of cmp for each batch and takes precedence over the cmpKvOptional shape, cuSeqlensCmpKvOptional, or the PA block table deduction. INT32 ND (b,) × cmpResidualKvOptional (aclTensor*) Input Compressed KV residual, used to restore the KV length before compression for the mask on the cmp side. Optional input. If passed in, the shape must be (B,). For the b-th batch, the KV length before compression is restored as cmpLen * cmpRatio + cmpResidualKvOptional[b]. This input must be passed in when cmpMaskMode is 3 and cmpRatio is not 1; it cannot be passed in when cmpMaskMode is 0 or cmpRatio is 1. INT32 ND (b,) × oriTopkLengthOptional (aclTensor*) Input Identifies the length of oriSparseIndicesOptional that actually participates in the computation. Must be passed in when oriMaskMode=0 and oriSparseIndicesOptional is passed in; not supported in other use cases. INT32 ND - If layoutQOptional is BSND: (b, qS, kvN)
- If layoutQOptional is TND: (qT, kvN)
× cmpTopkLengthOptional (aclTensor*) Input Indicates the actual length of cmpSparseIndicesOptional that participates in the computation. Must be passed in when cmpMaskMode=0 and cmpSparseIndicesOptional is passed in; not supported in other use cases. INT32 ND - If layoutQOptional is BSND: (b, qS, kvN)
- If layoutQOptional is TND: (qT, kvN)
× sinksOptional (aclTensor*) Input Indicates independent learnable virtual offsets set for each attention head to maintain stability in long-text inference. Must be passed in. FLOAT32 ND (qN,) × metadataOptional(aclTensor*) Input Kernel information of the AICPU operator aclnnMixedQuantSparseFlashMlaMetadata. Must be passed in. Generated by the aclnnMixedQuantSparseFlashMlaMetadata operator. INT32 ND (1024,) × quantMode (int64_t) Input Indicates the quantization mode. Indicates the quantization mode. Values 1, 2, and 3 are supported, and Q is not quantized. - quantMode=1: q uses BFLOAT16. The nope part of oriKvOptional and cmpKvOptional uses per-token-group quantization, with groupSize=64. Each token is concatenated in the order of rope (64 BFLOAT16 values), nope (448 FLOAT8_E4M3FN values), scale (7 BFLOAT16 values), and pad (18 bytes), and kvD=608.
- quantMode=2: q uses BFLOAT16. The nope part of oriKvOptional and cmpKvOptional uses per-token-group quantization, with groupSize=64. Each token contains nope (448 FLOAT8_E4M3FN values), rope (64 BFLOAT16 values), scale (7 FLOAT8_E8M0 values), and pad (1 byte), and kvD=584. Only layoutKvOptional=PA_BBND is supported, and data within a block is organized as blockSize*(nope+rope)+blockSize*(scale+pad).
- When quantMode=1 or quantMode=2, oriKvOptional and cmpKvOptional support using UINT8 or FLOAT8_E4M3FN as the single-byte storage view, with the underlying byte content unchanged. The actual type of each field is as described above.
- quantMode=3: indicates the TurboQuant path fused with TQ4 dequantization, which only supports the CSA use case. q uses FLOAT16 or BFLOAT16. oriKvOptional remains non-quantized, has the same data type as q, and has kvD=512. cmpKvOptional uses UINT8 to store TQ4 data. The 512-dimensional data of each token is encoded into 256 bytes of 4-bit codebook indices, followed by a 2-byte FLOAT16 per-token scale, totaling 258 bytes, and kvD=258. Both KV paths use the PA_BBND layout, with shapes (blockNum, blockSize, 1, 512) and (blockNum, blockSize, 1, 258) respectively. The codebook is consistent with the convention at the TurboQuant quantization side, and no additional external codebook or scale parameter is introduced.
- - - - ropeHeadDim (int64_t) Input Specifies the dimension of the rope head. Only 64 is supported. - - - - softmaxScale (double) Input Scaling coefficient, corresponding to softmaxScale in the formula. The recommended value is 1/√D, where D is the dimension of each attention head. - - - - cmpRatio (int64_t) Input Compression ratio of cmpKv relative to the KV length before compression, used to restore the pre-compression KV length used by the cmp-side mask. cmpRatio supports 1-128. If cmpKv is not passed in, only the default value 1 is supported. - - - - oriMaskMode (int64_t) Input Mask mode for the computation of q and oriKv. Supported:
0: No mask.
3: rightDownCausal mode.
4: sliding window mode.- - - - cmpMaskMode (int64_t) Input Mask mode of the q and cmpKv computation. Supported values:
0: No mask.
3: rightDownCausal mode. Only the default value 0 is supported if cmpKv is not passed in.- - - - oriWinLeft (int64_t) Input Indicates the number of historical tokens that q attends to in the computation of q and oriKvOptional. Supports -1 or non-negative values. -1 indicates infinity, meaning all tokens participate in the computation. - - - - oriWinRight (int64_t) Input Indicates the number of future tokens that q computes in the computation of q and oriKvOptional. Supports -1 or non-negative numbers, where -1 indicates infinity, meaning all tokens participate in the computation. - - - - layoutQOptional (char*) Input Specifies the data layout format of input q. Supports "BSND" and "TND". - - - - layoutKvOptional(char*) Input Specifies the data layout format of the inputs oriKvOptional and cmpKvOptional. Supports "PA_BBND", "BSND", and "TND". - - - - topkValueMode (int64_t) Input Mode of topk index value retrieval. Currently, only 1 is supported. - - - - returnSoftmaxLse (bool) Input Whether to return softmaxLse. Supports true or false. - - - - attnOut (aclTensor*) Output Attention computation output. - BFLOAT16 ND Same shape as q. × softmaxLseOptional (aclTensor*) Output Log-sum-exp result of softmax. If returnSoftmaxLse is false, a placeholder tensor is returned; if returnSoftmaxLse is true, the log-sum-exp result of softmax is returned. FLOAT32 ND - If layoutQOptional is BSND: (b, kvN, qS, qN/kvN)
- If layoutQOptional is TND: (kvN, qT, qN/kvN)
- If returnSoftmaxLse is false: placeholder tensor
× workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the computation flow of the operator. - - - - - Common Field Descriptions
| Name | Meaning |
|---|---|
| b | Batch size of input samples. |
| qS | Sequence length of input q. |
| oriKvS | Sequence length of input oriKvOptional. |
| cmpKvS | Sequence length of input cmpKvOptional. |
| qN | Number of heads of input q. |
| kvN | Number of heads of input oriKvOptional/cmpKvOptional. |
| qD | Dimension of the attention head of input q. |
| kvD | Dimension of the attention head of input oriKvOptional/cmpKvOptional. |
| qT | Cumulative sum of sequence lengths of all batches in input q. |
| oriKvT | Accumulated sum of sequence lengths of all batches in input oriKvOptional. |
| cmpKvT | Accumulated sum of sequence lengths of all batches in input cmpKvOptional. |
| oriKvK | Number of tokens selected by topK in input oriSparseIndicesOptional. |
| cmpKvK | Number of tokens selected by topK in input cmpSparseIndicesOptional. |
| oriKvSMax | Maximum sequence length of input oriKvOptional. |
| cmpKvSMax | Maximum sequence length of input cmpKvOptional. |
| oriKvBlockSize | Block size of input oriKvOptional in the PagedAttention use case. |
| cmpKvBlockSize | Block size of input cmpKvOptional in the PagedAttention use case. |
| oriKvBlockNums | Number of blocks of input oriKvOptional in the PagedAttention use case. |
| cmpKvBlockNums | Number of blocks of input cmpKvOptional in the PagedAttention use case. |
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 The passed-in parameter is a required input, output, or required attribute and is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, or attribute value of the input variable is not within the supported range.
aclnnMixedQuantSparseFlashMla
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device side. workspaceSize Input Workspace size allocated on the Device side. It is obtained by the first-phase API aclnnMixedQuantSparseFlashMlaGetWorkspaceSize. executor Input Executor of the operator, containing the operator computation flow. stream Input Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation
- aclnnMixedQuantSparseFlashMla defaults to a deterministic implementation. The same input yields the same result across multiple calls.
Usage constraints
- Inputs such as cuSeqlensQOptional, cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, sequsedOriKvOptional, sequsedCmpKvOptional, cmpResidualKvOptional, oriBlockTableOptional, and cmpBlockTableOptional are tensors. The operator cannot obtain the actual values of tensors during the Tiling phase, so tiling does not validate the values. You must ensure correctness. If invalid values are passed to these parameters, undefined behavior occurs (such as precision issues and program crashes caused by illegal memory access).
- The input parameters of aclnnMixedQuantSparseFlashMlaMetadata and aclnnMixedQuantSparseFlashMla must be consistent when called. Since the operator is called in two phases through two APIs, the operator cannot perform this check itself, and correctness must be ensured by users. If the parameters passed to the APIs are inconsistent, undefined behavior occurs (such as accuracy issues or program crashes caused by illegal memory access).
- oriTopkLengthOptional and cmpTopkLengthOptional indicate the actual lengths of ori/cmp sparseIndices participating in the computation. If a value is greater than the size of the last dimension of sparseIndicesOptional, the excess part is truncated to that size. When sequsedQOptional is passed in, the values of topkLength corresponding to the valid part must be greater than or equal to 0. When calling aclnnMixedQuantSparseFlashMlaMetadata and aclnnMixedQuantSparseFlashMla, the size of the last dimension of the corresponding sparseIndicesOptional must be the same.
- When oriMaskMode/cmpMaskMode is 0, oriKvK/cmpKvK must be greater than or equal to the maximum value of oriTopkLengthOptional/cmpTopkLengthOptional.
- cmpResidualKvOptional is used with cmpRatio to restore the KV length before compression. The value of each batch must be less than cmpRatio. This parameter can be passed in only when cmpMaskMode is 3 and cmpRatio is not 1; it cannot be passed in when cmpMaskMode is 0 or cmpRatio is 1.
- attnOut: tensor type, the output in the formula. The data type is BFLOAT16, and the data format is ND. Constraint: The shape of this output parameter must be the same as that of the input parameter q, and the dtype must be the same as that of q.
- When returnSoftmaxLse=False, a tensor with shape [1] and value 0 is returned; when returnSoftmaxLse=True, the FLOAT32 log-sum-exp result is returned.
- cuSeqlensQOptional, cuSeqlensOriKvOptional, and cuSeqlensCmpKvOptional must satisfy the following requirements: the first element is 0 and the sequence is non-decreasing as a whole, that is, each element is not less than its previous element.
- When layoutKvOptional is PA_BBND, oriKvOptional and cmpKvOptional support a non-contiguous axis 0. The stride of each dimension of the non-contiguous tensor cannot be 0. Other non-contiguous cases are not supported.
- For dimensions denoted by the same symbol in the shapes of these parameters, the actual values of the corresponding axes must be consistent.
Product-Specific Constraints
Ascend 950PR&950DT products :- Only
quantMode=1orquantMode=2is supported. For data types and KV storage layouts, see the quantMode description. - The following parameter group constraints apply to the
quantMode=1orquantMode=2use cases.
- Only
Atlas A3 products :- Only the
quantMode=3TurboQuant path is supported. - q and attnOut:
layoutQOptionalis TND; data types are FLOAT16 or BFLOAT16 and must be consistent; qN is a multiple of 4 in the range 4-128, qD is 512, and qT can be 0. - oriKvOptional and cmpKvOptional: Both must be passed in. For data types and KV storage layouts, see the quantMode description. The blockSize of both tensors is a multiple of 16 in the range 16-1024.
- Sparse and PA parameters: cmpSparseIndicesOptional, oriBlockTableOptional, and cmpBlockTableOptional must be passed in; the shape of cmpSparseIndicesOptional is (qT, 1, 512) or (qT, 1, 1024). oriSparseIndicesOptional, oriTopkLengthOptional, and cmpTopkLengthOptional cannot be passed in.
- Sequence parameters: cuSeqlensQOptional and sequsedOriKvOptional must be passed in; cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, and sequsedCmpKvOptional cannot be passed in.
- Mask and compression parameters:
oriMaskMode=4,cmpMaskMode=3,oriWinLeft>=0, andoriWinRight=0;cmpRatioonly supports 4 or 128; cmpResidualKvOptional is not supported.
- Only the
Atlas A2 products :- Only the TurboQuant path with
quantMode=3is supported. - q and attnOut:
layoutQOptionalis TND; the data type is FLOAT16 or BFLOAT16 and must be consistent; qN is a multiple of 4 in the range 4-128, qD is 512, and qT can be 0. - oriKvOptional and cmpKvOptional: both must be passed in. For data types and the KV storage layout, see the description of quantMode. The blockSize of both is a multiple of 16 in the range 16-1024.
- Sparse and PA parameters: cmpSparseIndicesOptional, oriBlockTableOptional, and cmpBlockTableOptional must be passed in; the shape of cmpSparseIndicesOptional is (qT, 1, 512) or (qT, 1, 1024). oriSparseIndicesOptional, oriTopkLengthOptional, and cmpTopkLengthOptional are not supported.
- Sequence parameters: cuSeqlensQOptional and sequsedOriKvOptional must be passed in; cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, and sequsedCmpKvOptional are not supported.
- Mask and compression parameters:
oriMaskMode=4,cmpMaskMode=3,oriWinLeft>=0, andoriWinRight=0;cmpRatioonly supports 4 or 128; cmpResidualKvOptional is not supported.
- Only the TurboQuant path with
TurboQuant Parameter Constraints
The following constraints apply to quantMode=3 on the quantMode=3.
| Parameter | quantMode=3 Constraints |
|---|---|
quantMode | 3 |
q, attnOut | FLOAT16 or BFLOAT16, with the same type and shape; TND layout, with shape (qT, qN, 512); qN is a multiple of 4 in range 4-128, and qT can be 0. |
oriKvOptional | Must be passed in; see the quantMode description for the data type, layout, and shape. |
cmpKvOptional | Must be passed in; see the quantMode description for the data type, layout, and shape. |
layoutQOptional, layoutKvOptional | TND and PA_BBND respectively; the blockSize of both KV paths is a multiple of 16 in range 16-1024, and the stride on axis 0 must cover a complete physical block. |
cmpSparseIndicesOptional | Must be passed in as INT32, with shape (qT, 1, 512) or (qT, 1, 1024); invalid positions are filled with -1. |
oriBlockTableOptional, cmpBlockTableOptional, cuSeqlensQOptional, sequsedOriKvOptional | All must be passed in, with the original INT32 type and parameter meanings retained. |
oriSparseIndicesOptional, oriTopkLengthOptional, cmpTopkLengthOptional, cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, sequsedCmpKvOptional, cmpResidualKvOptional | Not supported; the original optional parameter positions are retained. |
oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight | 4, 3, a non-negative value, and 0 respectively. |
cmpRatio, ropeHeadDim, topkValueMode | Support 4 or 128, 64, and 1 respectively; the supported compression ratio range of the operator does not mean that the framework quantizes all compressed KV. |
metadataOptional | Must be passed in; generated by the preceding Metadata API with the same quantMode=3 and the same input attributes; INT32, with shape (1024,). |
sinksOptional and Softmax LSE continue to use the original parameters and return form.
For the quantMode=1 and quantMode=2 remain unchanged.
Feature Parameter Group
| Feature Parameter Group | Parameter Field Names |
|---|---|
| Common Parameter Group | q, quantMode, oriKvOptional, cmpKvOptional, metadataOptional, ropeHeadDim, softmaxScale, layoutQOptional, layoutKvOptional, attnOut |
| Mask Parameter Group | oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight |
| SeqLens Parameter Group | cuSeqlensQOptional, cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, sequsedOriKvOptional, sequsedCmpKvOptional |
| sparse compression parameter group | cmpRatio, cmpResidualKvOptional, oriSparseIndicesOptional, cmpSparseIndicesOptional, oriTopkLengthOptional, cmpTopkLengthOptional, topkValueMode |
| Paged Attention Parameter Group | oriBlockTableOptional, cmpBlockTableOptional |
| Sinks Parameter Group | sinksOptional |
| SoftmaxLse Parameter Group | returnSoftmaxLse, softmaxLseOptional |
Computation Modes
| Name | Parameters Required for Typical Use Cases | Parameters Required for Fully Sparse Use Cases |
|---|---|---|
| SWA | oriKvOptional | oriKvOptional, oriSparseIndicesOptional |
| HCA | oriKvOptional, cmpKvOptional | - |
| CSA | oriKvOptional, cmpKvOptional, cmpSparseIndicesOptional | oriKvOptional, oriSparseIndicesOptional, cmpKvOptional, cmpSparseIndicesOptional |
Parameter Group Constraints
Common Parameter Group
Handling of empty input parameters:
- An empty tensor is a required input, or an input or output required in a specific use case, whose shape size is 0, that is, any axis is 0.
- Use cases that trigger an empty tensor are all intercepted and an error is reported.
Checks on q, oriKvOptional, cmpKvOptional, and attnOut
| Parameter | Single-Parameter Check | Existence Check | Consistency Check | Feature cross-check |
|---|---|---|---|---|
| q |
|
Must be passed in. |
|
Axis check:
|
| oriKvOptional |
|
Required in the current version. | ||
| attnOut |
|
must be passed in | ||
| cmpKvOptional |
|
optional input |
| layoutQOptional | layoutKvOptional |
|---|---|
| BSND | |
| TND | |
metadataOptional Validation
| Parameter | Single-parameter check | Existence check | Consistency check | Feature cross-check |
|---|---|---|---|---|
| metadataOptional |
|
Required in the current version. | None | When passed in, the value must be consistent with the result generated by aclnnMixedQuantSparseFlashMlaMetadata. |
Mask Parameter Group
- oriMaskMode/cmpMaskMode=0, full computation mode (default value)
- oriMaskMode/cmpMaskMode=3, Causal mode
- oriMaskMode=4, SlidingWindow mode
| Parameter | Single-Parameter Check | Existence Check | Consistency Check | Feature Cross-Check |
|---|---|---|---|---|
| oriMaskMode |
|
Optional. If not passed, the default value is 0. |
|
|
| cmpMaskMode |
|
Optional. If not passed, the default value is 0 |
|
|
| oriWinLeft/oriWinRight |
|
Optional. If not passed, the default value is -1 |
|
|
SeqLens Parameter Group
| Parameter | Single-Parameter Check | Existence Check | Consistency Check | Feature Cross-Check |
|---|---|---|---|---|
| sequsedQOptional |
|
None | None | None |
| sequsedOriKvOptional |
|
|
None | None |
| sequsedCmpKvOptional |
|
|
None | None |
| cuSeqlensQOptional |
|
|
None | None |
| cuSeqlensOriKvOptional |
|
|
None | None |
| cuSeqlensCmpKvOptional |
|
|
None | None |
sparse compression parameter group
| Parameter | Single-Parameter Check | Existence Check | Consistency Check | Feature Cross-Check |
|---|---|---|---|---|
| cmpRatio |
|
|
None |
|
| cmpResidualKvOptional |
|
|
|
None |
| oriSparseIndicesOptional |
|
|
|
None |
| cmpSparseIndicesOptional |
|
|
|
None |
| oriTopkLengthOptional |
|
|
|
|
| cmpTopkLengthOptional |
|
|
|
None |
| topkValueMode |
|
Optional attribute, default value is 1. | None | None |
Paged Attention Parameter Group
Paged Attention is enabled when layoutKvOptional is PA_BBND.
| Parameter | Single-Parameter Check | Existence Check | Consistency Check | Feature Cross-Check |
|---|---|---|---|---|
| oriBlockTableOptional |
|
Optional | None |
|
| cmpBlockTableOptional |
|
|
None |
|
Sinks Parameter Group
| Parameter | Single-Parameter Check | Existence Check | Consistency Check | Feature Cross-Check |
|---|---|---|---|---|
| sinksOptional |
|
Required in the current version | None | None |
SoftmaxLse Parameter Group
| Parameter | single-parameter check | existence check | consistency check | feature cross-check |
|---|---|---|---|---|
| returnSoftmaxLse |
|
Optional, default value is false |
|
None |
| softmaxLseOptional |
|
None | None |
Example
The sample code is as follows, for reference only. For details about compilation and execution, see Compile and Run Samples.
/**
* Copyright (c) 2026 Huawei Technologies Co., Ltd.
* This file is a part of the CANN Open Software.
* Licensed under CANN Open Software License Agreement Version 1.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.
*/
/*!
* \file test_aclnn_mixed_quant_sparse_flash_mla.cpp
* \brief
*/
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_mixed_quant_sparse_flash_mla.h"
#include "aclnnop/aclnn_mixed_quant_sparse_flash_mla_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 FloatToBf16(float f)
{
uint32_t bits;
std::memcpy(&bits, &f, sizeof(bits));
uint32_t lsb = (bits >> 16) & 1u;
uint32_t roundingBias = 0x7fffu + lsb;
bits += roundingBias;
return static_cast<uint16_t>(bits >> 16);
}
float Bf16ToFloat(uint16_t h)
{
uint32_t bits = static_cast<uint32_t>(h) << 16;
float result;
std::memcpy(&result, &bits, 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, Bf16ToFloat(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> MakeBf16Data(int64_t size, float value)
{
std::vector<uint16_t> data(static_cast<size_t>(size), FloatToBf16(value));
return data;
}
std::vector<uint8_t> MakeFp8Data(int64_t size, uint8_t value)
{
std::vector<uint8_t> data(static_cast<size_t>(size), value);
return data;
}
} // namespace
int main()
{
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);
int64_t B = 1;
int64_t S1 = 1;
int64_t S2 = 1024;
int64_t N1 = 64;
int64_t N2 = 1;
int64_t D = 512;
int64_t K = 512;
int64_t oriBlockSize = 128;
int64_t cmpBlockSize = 128;
int64_t s2Act = 1024;
int64_t cmpRatio = 4;
int64_t oriWinLeft = 127;
int64_t oriWinRight = 0;
int64_t oriMaskMode = 4;
int64_t cmpMaskMode = 3;
int64_t quantMode = 1;
int64_t ropeHeadDim = 64;
int64_t tileSize = 64;
double softmaxScale = 1.0 / sqrt(static_cast<double>(D));
int64_t nopeHeadDim = D - ropeHeadDim;
int64_t quantScaleHeadDim = (nopeHeadDim + tileSize - 1) / tileSize;
int64_t kvD = nopeHeadDim + ropeHeadDim * 2 + quantScaleHeadDim * 2 + 18;
int64_t T1 = B * S1;
int64_t cmpKvLen = s2Act / cmpRatio;
int64_t oriBlockNum = ((s2Act + oriBlockSize - 1) / oriBlockSize) * B;
int64_t cmpBlockNum = ((cmpKvLen + cmpBlockSize - 1) / cmpBlockSize) * B;
std::vector<int64_t> qShape = {T1, N1, D};
std::vector<int64_t> oriKvShape = {oriBlockNum, oriBlockSize, N2, kvD};
std::vector<int64_t> cmpKvShape = {cmpBlockNum, cmpBlockSize, N2, kvD};
std::vector<int64_t> cmpSparseIndicesShape = {T1, N2, K};
std::vector<int64_t> oriBlockTableShape = {B, (s2Act + oriBlockSize - 1) / oriBlockSize};
std::vector<int64_t> cmpBlockTableShape = {B, (cmpKvLen + cmpBlockSize - 1) / cmpBlockSize};
std::vector<int64_t> cuSeqLensQShape = {B + 1};
std::vector<int64_t> seqUsedOriKvShape = {B};
std::vector<int64_t> seqUsedCmpKvShape = {B};
std::vector<int64_t> cmpResidualKvShape = {B};
std::vector<int64_t> sinksShape = {N1};
std::vector<int64_t> metadataShape = {1024};
std::vector<int64_t> attnOutShape = {T1, N1, D};
std::vector<int64_t> softmaxLseShape = {T1, N1, 1};
std::vector<int64_t> emptyShape = {0};
void* qDeviceAddr = nullptr;
void* oriKvDeviceAddr = nullptr;
void* cmpKvDeviceAddr = nullptr;
void* cmpSparseIndicesDeviceAddr = nullptr;
void* oriBlockTableDeviceAddr = nullptr;
void* cmpBlockTableDeviceAddr = nullptr;
void* cuSeqLensQDeviceAddr = nullptr;
void* cuSeqLensOriKvDeviceAddr = nullptr;
void* cuSeqLensCmpKvDeviceAddr = nullptr;
void* seqUsedQDeviceAddr = nullptr;
void* seqUsedOriKvDeviceAddr = nullptr;
void* seqUsedCmpKvDeviceAddr = nullptr;
void* cmpResidualKvDeviceAddr = nullptr;
void* sinksDeviceAddr = nullptr;
void* metadataDeviceAddr = nullptr;
void* attnOutDeviceAddr = nullptr;
void* softmaxLseDeviceAddr = nullptr;
aclTensor* q = nullptr;
aclTensor* oriKv = nullptr;
aclTensor* cmpKv = nullptr;
aclTensor* cmpSparseIndices = nullptr;
aclTensor* oriBlockTable = nullptr;
aclTensor* cmpBlockTable = nullptr;
aclTensor* cuSeqLensQ = nullptr;
aclTensor* cuSeqLensOriKv = nullptr;
aclTensor* cuSeqLensCmpKv = nullptr;
aclTensor* seqUsedQ = nullptr;
aclTensor* seqUsedOriKv = nullptr;
aclTensor* seqUsedCmpKv = nullptr;
aclTensor* cmpResidualKv = nullptr;
aclTensor* sinks = nullptr;
aclTensor* metadata = nullptr;
aclTensor* attnOut = nullptr;
aclTensor* softmaxLse = nullptr;
int64_t qSize = GetShapeSize(qShape);
int64_t oriKvSize = GetShapeSize(oriKvShape);
int64_t cmpKvSize = GetShapeSize(cmpKvShape);
int64_t cmpSparseIndicesSize = GetShapeSize(cmpSparseIndicesShape);
int64_t oriBlockTableSize = GetShapeSize(oriBlockTableShape);
int64_t cmpBlockTableSize = GetShapeSize(cmpBlockTableShape);
int64_t attnOutSize = GetShapeSize(attnOutShape);
int64_t softmaxLseSize = GetShapeSize(softmaxLseShape);
std::vector<uint16_t> qHostData = MakeBf16Data(qSize, 1.0f);
std::vector<uint8_t> oriKvHostData = MakeFp8Data(oriKvSize, 0x38);
std::vector<uint8_t> cmpKvHostData = MakeFp8Data(cmpKvSize, 0x38);
std::vector<int32_t> cmpSparseIndicesHostData(cmpSparseIndicesSize);
std::vector<int32_t> oriBlockTableHostData(oriBlockTableSize);
std::iota(oriBlockTableHostData.begin(), oriBlockTableHostData.end(), 0);
std::vector<int32_t> cmpBlockTableHostData(cmpBlockTableSize);
std::iota(cmpBlockTableHostData.begin(), cmpBlockTableHostData.end(), 0);
std::vector<int32_t> cuSeqLensQHostData(B + 1);
for (int64_t i = 0; i <= B; i++) {
cuSeqLensQHostData[i] = static_cast<int32_t>(i * S1);
}
std::vector<int32_t> emptyHostData;
std::vector<int32_t> seqUsedOriKvHostData(B, static_cast<int32_t>(s2Act));
std::vector<int32_t> seqUsedCmpKvHostData(B, static_cast<int32_t>(cmpKvLen));
std::vector<int32_t> cmpResidualKvHostData(B);
for (int64_t i = 0; i < B; i++) {
cmpResidualKvHostData[i] = seqUsedOriKvHostData[i] % static_cast<int32_t>(cmpRatio);
}
std::vector<float> sinksHostData(N1, 1.0f);
std::vector<int32_t> metadataHostData(1024, 0);
std::vector<uint16_t> attnOutHostData = MakeBf16Data(attnOutSize, 0.0f);
std::vector<float> softmaxLseHostData(softmaxLseSize, 0.0f);
std::mt19937 gen(42);
for (int64_t t = 0; t < T1; t++) {
for (int64_t n = 0; n < N2; n++) {
for (int64_t k = 0; k < K; k++) {
cmpSparseIndicesHostData[t * N2 * K + n * K + k] = static_cast<int32_t>(gen() % cmpKvLen);
}
}
}
ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_BF16, &q);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(oriKvHostData, oriKvShape, &oriKvDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &oriKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cmpKvHostData, cmpKvShape, &cmpKvDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &cmpKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cmpSparseIndicesHostData, cmpSparseIndicesShape, &cmpSparseIndicesDeviceAddr,
aclDataType::ACL_INT32, &cmpSparseIndices);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(oriBlockTableHostData, oriBlockTableShape, &oriBlockTableDeviceAddr, aclDataType::ACL_INT32,
&oriBlockTable);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cmpBlockTableHostData, cmpBlockTableShape, &cmpBlockTableDeviceAddr, aclDataType::ACL_INT32,
&cmpBlockTable);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cuSeqLensQHostData, cuSeqLensQShape, &cuSeqLensQDeviceAddr, aclDataType::ACL_INT32, &cuSeqLensQ);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(emptyHostData, emptyShape, &cuSeqLensOriKvDeviceAddr, aclDataType::ACL_INT32, &cuSeqLensOriKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(emptyHostData, emptyShape, &cuSeqLensCmpKvDeviceAddr, aclDataType::ACL_INT32, &cuSeqLensCmpKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(emptyHostData, emptyShape, &seqUsedQDeviceAddr, aclDataType::ACL_INT32, &seqUsedQ);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(seqUsedOriKvHostData, seqUsedOriKvShape, &seqUsedOriKvDeviceAddr, aclDataType::ACL_INT32, &seqUsedOriKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(seqUsedCmpKvHostData, seqUsedCmpKvShape, &seqUsedCmpKvDeviceAddr, aclDataType::ACL_INT32, &seqUsedCmpKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cmpResidualKvHostData, cmpResidualKvShape, &cmpResidualKvDeviceAddr, aclDataType::ACL_INT32, &cmpResidualKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(sinksHostData, sinksShape, &sinksDeviceAddr, aclDataType::ACL_FLOAT, &sinks);
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(attnOutHostData, attnOutShape, &attnOutDeviceAddr, aclDataType::ACL_BF16, &attnOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(softmaxLseHostData, softmaxLseShape, &softmaxLseDeviceAddr, aclDataType::ACL_FLOAT, &softmaxLse);
CHECK_RET(ret == ACL_SUCCESS, return ret);
char layoutQOptional[] = "TND";
char layoutKvOptional[] = "PA_BBND";
uint64_t metadataWorkspaceSize = 0;
aclOpExecutor* metadataExecutor = nullptr;
ret = aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize(
cuSeqLensQ, cuSeqLensOriKv, cuSeqLensCmpKv,
seqUsedQ, seqUsedOriKv, seqUsedCmpKv,
cmpResidualKv, nullptr, nullptr,
N1, N2, D, quantMode, B,
S1, S2, cmpKvLen,
0, K, ropeHeadDim,
cmpRatio, oriMaskMode, cmpMaskMode,
oriWinLeft, oriWinRight,
layoutQOptional, layoutKvOptional,
true, true,
metadata,
&metadataWorkspaceSize, &metadataExecutor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize 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 = aclnnMixedQuantSparseFlashMlaMetadata(metadataWorkspaceAddr, metadataWorkspaceSize, metadataExecutor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMixedQuantSparseFlashMlaMetadata failed. ERROR: %d\n", ret); return ret);
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 = aclnnMixedQuantSparseFlashMlaGetWorkspaceSize(
q, oriKv, cmpKv,
nullptr, cmpSparseIndices,
oriBlockTable, cmpBlockTable,
cuSeqLensQ, nullptr, nullptr,
nullptr, seqUsedOriKv, seqUsedCmpKv,
cmpResidualKv, nullptr, nullptr,
sinks, metadata,
quantMode, ropeHeadDim,
softmaxScale, cmpRatio,
oriMaskMode, cmpMaskMode,
oriWinLeft, oriWinRight,
layoutQOptional, layoutKvOptional,
1, false,
attnOut, softmaxLse,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMixedQuantSparseFlashMlaGetWorkspaceSize 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 = aclnnMixedQuantSparseFlashMla(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMixedQuantSparseFlashMla 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);
PrintOutResult(attnOutShape, &attnOutDeviceAddr);
aclDestroyTensor(q);
aclDestroyTensor(oriKv);
aclDestroyTensor(cmpKv);
aclDestroyTensor(cmpSparseIndices);
aclDestroyTensor(oriBlockTable);
aclDestroyTensor(cmpBlockTable);
aclDestroyTensor(cuSeqLensQ);
aclDestroyTensor(cuSeqLensOriKv);
aclDestroyTensor(cuSeqLensCmpKv);
aclDestroyTensor(seqUsedQ);
aclDestroyTensor(seqUsedOriKv);
aclDestroyTensor(seqUsedCmpKv);
aclDestroyTensor(cmpResidualKv);
aclDestroyTensor(sinks);
aclDestroyTensor(metadata);
aclDestroyTensor(attnOut);
aclDestroyTensor(softmaxLse);
aclrtFree(qDeviceAddr);
aclrtFree(oriKvDeviceAddr);
aclrtFree(cmpKvDeviceAddr);
aclrtFree(cmpSparseIndicesDeviceAddr);
aclrtFree(oriBlockTableDeviceAddr);
aclrtFree(cmpBlockTableDeviceAddr);
if (cuSeqLensQDeviceAddr != nullptr) {
aclrtFree(cuSeqLensQDeviceAddr);
}
if (seqUsedOriKvDeviceAddr != nullptr) {
aclrtFree(seqUsedOriKvDeviceAddr);
}
if (seqUsedCmpKvDeviceAddr != nullptr) {
aclrtFree(seqUsedCmpKvDeviceAddr);
}
if (cmpResidualKvDeviceAddr != nullptr) {
aclrtFree(cmpResidualKvDeviceAddr);
}
aclrtFree(sinksDeviceAddr);
aclrtFree(metadataDeviceAddr);
aclrtFree(attnOutDeviceAddr);
aclrtFree(softmaxLseDeviceAddr);
if (metadataWorkspaceSize > 0) {
aclrtFree(metadataWorkspaceAddr);
}
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}