lightning_indexer
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
lightning_indexer_metadataAPI generates a task list, which contains the indexes of the batch, head, and Q and K chunks at the start and end points of the Attention computation task on each AI Core. The list is used by the subsequentlightning_indexeroperator.The
lightning_indexerAPI obtains the top-k positions for each token through a series of operations. The main computation process is as follows:- Multiply the input parameter
q($Q_{index}\in\R^{g\times d}$) corresponding to a token by the given contextk($K_{index}\in\R^{S_{k}\times d}$) to obtain the correlation. - Filter invalid negative correlation signals through the activation function $ReLU$ to obtain the correlation score vector between the current token and all preceding tokens.
- After being multiplied by the weight coefficient
w($W$), the top $Top-k$ index values are selected along the g dimension to obtain the output $sparseIndices$, and the corresponding $sparseValues$ are output as the input to Attention.
- Multiply the input parameter
Formula:
$$ Top-k \left\{ \left[ 1 \left] \mathop{{}}\nolimits_{{1 \times \text{ }g}}\text{@} \left[ \left( W\text{@} \left[ 1 \left] \mathop{{}}\nolimits_{{1\text{ } \times \text{ }S\mathop{{}}\nolimits_{{k}}}} \left) \text{ } \odot \text{ }ReLU \left( Q\mathop{{}}\nolimits_{{index}}\text{@}K\mathop{{}}\nolimits_{{T}}^{{index}} \left) \left] \right\} \right. \right. \right. \right. \right. \right. \right. \right. \right. \right. $$
Prototype
Before calling the lightning_indexer API, call the prerequisite API lightning_indexer_metadata to complete the load balancing computation of lightning_indexer.
cann_ops_transformer.lightning_indexer_metadata(
num_heads_q,
num_heads_k,
head_dim,
topk,
*,
cu_seqlens_q=None,
cu_seqlens_k=None,
seqused_q=None,
seqused_k=None,
cmp_residual_k=None,
batch_size=0,
max_seqlen_q=-1,
max_seqlen_k=-1,
layout_q="BSND",
layout_k="BSND",
mask_mode=0,
cmp_ratio=1
) -> Tensorcann_ops_transformer.lightning_indexer(
q,
k,
w,
topk,
*,
cu_seqlens_q=None,
cu_seqlens_k=None,
seqused_q=None,
seqused_k=None,
cmp_residual_k=None,
block_table=None,
output_idx_offset=None,
metadata=None,
max_seqlen_q=-1,
layout_q="BSND",
layout_k="BSND",
mask_mode=0,
cmp_ratio=1,
return_value=0
) -> (Tensor, Tensor)Parameters
NOTE:
- The dimensions of parameters q, k, and w are described as follows: b (batch Size) indicates the batch size of input samples, q_s indicates the sequence length of the q input samples, k_s indicates the sequence length of the k input samples, q_n indicates the number of q heads, k_n indicates the number of k heads, d (head dim) indicates the dimension of the attention head, q_t indicates the cumulative sum of the sequence lengths of the q input samples, and k_t indicates the cumulative sum of the sequence lengths of the k input samples. The value of d in parameter q equals that in parameter k. Currently, only 128 is supported.
lightning_indexer_metadata
| Name | Type | Required/Optional | Description | Data Type | Dimension (Shape) |
|---|---|---|---|---|---|
| num_heads_q | int | Required | Number of heads for q. | int64 | - |
| num_heads_k | int | Required | Number of heads for k. Currently only supports 1. | int64 | - |
| head_dim | int | Required | Dimension of the attention head. Currently only supports 128. | int64 | - |
| topk | int | Required | Number of Key token indexes retained for each q token. Currently, values in [1, 8192] are supported. | int64 | - |
| cu_seqlens_q | Tensor | Optional | Cumulative prefix sum of the valid Sequence Length of q in each batch. Must be passed only when layout_q is TND. The first value is fixed to 0. The data format is ND. Non-contiguous tensors are supported. | int32 | (b+1, ) |
| cu_seqlens_k | Tensor | Optional | Cumulative prefix sum of the valid Sequence Length of k in each batch. Must be passed only when layout_k is TND. The first value is fixed to 0. The data format is ND. Non-contiguous tensors are supported. | int32 | (b+1, ) |
| seqused_q | Tensor | Optional | Sequence Length of q actually participating in the computation in each batch. The data format is ND. Non-contiguous tensors are supported. | int32 | (b, ) |
| seqused_k | Tensor | Optional | Sequence Length of k actually participating in the computation in each batch. The data format is ND. Non-contiguous tensors are supported. | int32 | (b, ) |
| cmp_residual_k | Tensor | Optional | Remainder of the pre-compression Sequence Length of cmp_kv divided by cmp_ratio in each batch. Used together with cmp_ratio to compute the mask and load of the cmp_kv part. Required when cmp_ratio is not 1 and mask_mode is 3. Data format: ND. Non-contiguous tensors are supported. | int32 | (b, ) |
| batch_size | int | Optional | Number of batches. The default value is 0. | int64 | - |
| max_seqlen_q | int | Optional | Maximum Sequence Length of q. -1 indicates any possible length. The default value is -1. | int64 | - |
| max_seqlen_k | int | Optional | Maximum Sequence Length of k. -1 indicates any possible length. The default value is -1. | int64 | - |
| layout_q | str | Optional | Layout of q. Supports BSND and TND. The default value is BSND. | string | - |
| layout_k | str | Optional | Layout of k. Supports BSND, TND, and PA_BBND. The default value is BSND. | string | - |
| mask_mode | int | Optional | Sparse mode. 0 indicates No mask, and 3 indicates rightDownCausal mode. The default value is 0. | int64 | - |
| cmp_ratio | int | Optional | Compression ratio of k. Value range: [1, 128]. The default value is 1, indicating no compression. | int64 | - |
lightning_indexer
| Name | Type | Required/Optional | Description | Data Type | Dimension (Shape) |
|---|---|---|---|---|---|
| q | Tensor | Required | Input Q in the formula. Empty tensors are not supported. Data format: ND. | bfloat16, float16 | shape is (b,q_s,q_n,d) when layout_q is BSND; shape is (q_t,q_n,d) when layout_q is TND |
| k | Tensor | Required | Input K in the formula. Empty tensors are not supported. Data format: ND. Non-contiguous tensors are supported (only axis 0 supports non-contiguity in the PA_BBND use case). | bfloat16, float16 | shape is (b,k_s,k_n,d) when layout_k is BSND; shape is (k_t,k_n,d) when layout_k is TND; shape is (block_num,block_size,k_n,d) when layout_k is PA_BBND |
| w | Tensor | Required | Input W in the formula. Empty tensors are not supported. Data format: ND. | float | shape is (b,q_s,q_n) when layout_q is BSND; shape is (q_t,q_n) when layout_q is TND |
| topk | int | Required | Number of Key token indices to retain in the topK phase. Value range: [1, 8192]. | int64 | - |
| cu_seqlens_q | Tensor | Optional | Cumulative sum of the number of valid q tokens in the current and preceding batches. Required only when layout_q is TND. The first value is fixed to 0. Data format: ND. | int32 | (b+1,) |
| cu_seqlens_k | Tensor | Optional | Cumulative sum of the number of valid k tokens in the current and preceding batches. Required only when layout_k is TND. The first value is fixed to 0. Data format: ND. | int32 | (b+1,) |
| seqused_q | Tensor | Optional | Actual used length of q in different batches. Data format: ND. | int32 | (b,) |
| seqused_k | Tensor | Optional | Actual used length of k in different batches. Data format: ND. | int32 | (b,) |
| cmp_residual_k | Tensor | Optional | Remainder of dividing the number of k tokens before compression by cmp_ratio. Required when mask_mode is 3 and cmp_ratio is not 1. Data format: ND. | int32 | (b,) |
| block_table | Tensor | Optional | Block mapping table used for KV storage in PageAttention. Empty tensors are not supported. Data format: ND. | int32 | (b, k_s_max/block_size) |
| output_idx_offset | Tensor | Optional | Offset to add to the output indices of the topK result. The value must be greater than or equal to 0, and the topK index plus the offset must not exceed the maximum value of int32. Data format: ND. | int32 | shape is (b,q_s,k_n) when layout_q is BSND; shape is (q_t,k_n) when layout_q is TND |
| metadata | Tensor | Optional | Core splitting information obtained from lightning_indexer_metadata, including the number of used cores, block size, and the start point of the data processed by each core. Empty tensors are not supported. Data format: ND. | int32 | (1024,) |
| max_seqlen_q | int | Optional | Maximum sequence length of q. -1 indicates any possible length. Default value is -1. | int64 | - |
| layout_q | str | Optional | Data layout format of input q. Supports BSND and TND. Default value is BSND. | string | - |
| layout_k | str | Optional | Data layout format of input k. Supports BSND, TND, and PA_BBND. Default value is BSND. | string | - |
| mask_mode | int | Optional | Mask mode. 0 indicates the defaultMask mode, and 3 indicates the rightDownCausal mode. Default value is 0. | int64 | - |
| cmp_ratio | int | Optional | Used for sparse computation, indicating the compression ratio of k. Value range: 1-128. Default value: 1. | int64 | - |
| return_value | int | Optional | Whether to return the Values corresponding to Indices. 0 indicates no return, and 1 indicates return. Default value: 0. | int64 | - |
Return Values
lightning_indexer_metadata
| Name | Type | Required/Optional | Description | Data Type | Dimension (Shape) |
|---|---|---|---|---|---|
| metadata | Tensor | Required | Index of batch, head, and Q and K chunking for the Attention computation task of each AIcore. The data format is ND, and non-contiguous tensors are not supported. | int32 | (1024,) |
lightning_indexer
| Name | Type | Required/Optional | Description | Data Type | Dimension (Shape) |
|---|---|---|---|---|---|
| sparse_indices | Tensor | Required | Indices output in the formula. Empty tensors are not supported. Invalid parts are filled with -1. The data format is ND. | int32 | (b,q_s,k_n,topk) when layout_q is BSND; (q_t,k_n,topk) when layout_q is TND |
| sparse_values | Tensor | conditional output | Values output corresponding to Indices in the formula. When return_value is 1, corresponding values are output; when return_value is 0, an empty tensor with shape [0] is output. Invalid parts are filled with -inf. The data format is ND. | float | (b,q_s,k_n,topk) when layout_q is BSND; (q_t,k_n,topk) when layout_q is TND; (0,) when return_value is 0 |
Constraints
- This API supports use in inference scenarios.
- This API can be called in single-operator mode and TorchAir (aclgraph) graph mode.
- The lightning_indexer_metadata API must be used together with the lightning_indexer operator.
- b (batch) indicates the batch size of input samples.
- The values of cu_seqlens_q and cu_seqlens_k must be the cumulative number of valid tokens in the current batch and all preceding batches. The first element must be 0, and each subsequent element must be greater than or equal to the previous element.
- The values of seqused_q and seqused_k indicate the number of valid tokens in each batch.
- cmp_residual_k must satisfy cmp_residual_k[i] < cmp_ratio.
- For details about mask modes indicated by mask_mode, see sparse_mode parameter description.
- pa_kv_cache supports non-contiguity on axis 0; pa_block_size supports values in [16, 1024] and must be a multiple of 16.
- The data types of parameters q and k must be the same.
- Sorting NaN values in the TopK sorting process of this API is undefined behavior.
- When layout_q is BSND, passing cu_seqlens_q is not supported; when layout_k is BSND or PA_BBND, passing cu_seqlens_k is not supported.
- When cmp_ratio > 1 and mask_mode = 3, cmp_residual_k must be passed; in other cases, do not pass it.
- Invalid parts of sparse_indices are filled with -1; invalid parts of sparse_values are filled with -inf.
Atlas A3 products andAtlas A2 products :- The value range of topk currently supports only [1, 2048], as well as 3072, 4096, 5120, 6144, 7168, and 8192.
- The lightning_indexer API currently does not support seqused_q, output_idx_offset, or max_seqlen_q. Passing in these parameters is not recommended.
- num_heads_q = 1~64, q_n = 1~64 are supported.
- layout_k supports BSND, TND, and PA_BBND; when layout_k is not PA_BBND, layout_q must be the same as layout_k.
- seqused_k must be passed in when layout_k is PA_BBND and is optional when layout_k is BSND or TND.
- cmp_ratio supports [1, 128].
- The return_value function is supported. 0 indicates that the corresponding value is not returned, and 1 indicates that sparse_values of the FLOAT32 type is returned.
Ascend 950PR&950DT products :- topk currently only supports a value range of [1, 8192].
- num_heads_q = 1~64, q_n = 1~64 are supported.
- cmp_ratio supports [1, 128].
- When output_idx_offset is passed, index offsets greater than or equal to 0 are supported. In addition, the following constraint must be satisfied: after the passed index offset is added, the resulting sparseIndice value must not exceed the maximum value of INT32.
- When layout_q is TND, cu_seqlens_q must be passed. If seqused_q is also passed, ensure that the q length of each batch passed by seqused_q does not exceed the q sequence length of each batch calculated based on cu_seqlens_q. When the q sequence length seqlen1 of a batch passed by seqused_q is less than the q length seqlen2 calculated based on cu_seqlens_q, TND Padding is enabled, and the sparse_indices and sparse_values of the q output in the batch for the part corresponding to the difference between seqlen2 and seqlen1 are all set to invalid values. In some long-sequence use cases, if the invalid data to be padded is too large, the aicore execution may time out due to hardware limitations. The amount of data to be padded can be calculated as (seqlen2 - seqlen1) * topk. It is recommended to control this data amount within 400 million.
- The parameter metadata must be passed, and its shape is (1024,).
Feature Parameter Group
| Feature Parameter Group | Parameter Field Names |
|---|---|
| Common Parameter Group | q、k、w、metadata、output_idx_offset、topk、layout_q、layout_k、sparse_indices、sparse_values |
| Mask Parameter Group | mask_mode |
| SeqLens Parameter Group | cu_seqlens_q、cu_seqlens_k、seqused_q、seqused_k、max_seqlen_q |
| sparse compression parameter group | cmp_ratio、cmp_residual_k |
| Paged Attention Parameter Group | block_table |
Baseline Information
Common Parameter Group
Handling of empty input parameters:
- An empty tensor refers to a required input or output with a shape size of 0, that is, any axis is 0.
- Use cases that trigger an empty tensor are all intercepted and an error is reported.
Validation of q, k, sparse_indices, and sparse_values
| Parameter | Single-Parameter Check | Existence Check | Consistency Check | Feature Cross-Check |
|---|---|---|---|---|
| q |
|
Required. |
|
Axis check:
|
| k |
|
|||
| sparse_indices |
|
|||
| sparse_values |
|
Layout matching relationship table:
| layout_q | layout_k | layout_out |
|---|---|---|
| BSND | |
BSND |
| TND | |
TND |
Metadata validation
| Parameter | Single-Parameter Check | Existence Check | Consistency Check | Feature Cross-Check |
|---|---|---|---|---|
| metadata |
|
Optional parameter | None | If passed in, the value must be consistent with the result generated by lightning_indexer_v2_metadata. |
mask_mode parameter description:
- mask_mode=0, full computation mode (default value)
- mask_mode=3, Causal mode
| Parameter | Single-Parameter Check | Existence Check |
|---|---|---|
| mask_mode |
|
Optional input. If this parameter is not passed, the default value is 0. |
SeqLengths parameter group
| Parameter | Single-Parameter Check | Existence Check | Consistency Check | Feature Cross-Check |
|---|---|---|---|---|
| seqused_q |
|
Optional parameters | None | None |
| seqused_k | ||||
| cu_seqlens_q |
|
|
||
| cu_seqlens_k |
|
|
||
| max_seqlen_q |
|
|
Paged Attention Parameter Group
Paged Attention is enabled when block_table is not empty.
| Parameter | Single-Parameter Validation | Existence Validation | Consistency Validation | Feature Cross-Validation |
|---|---|---|---|---|
| block_table |
|
Optional parameter | None |
|
Deterministic Computation
Deterministic computation is supported by default.
Example
Single-operator mode call:
import torch import torch_npu import numpy as np from cann_ops_transformer.ops import lightning_indexer, lightning_indexer_metadata B = 2 S1 = 64 S2 = 130 N1 = 16 N2 = 1 D = 128 topk = 32 cmp_ratio = 4 # Compute the compressed S2 length and remainder. S2_compressed = S2 // cmp_ratio res_k = S2 % cmp_ratio # Construct the input. q = torch.randn(B, S1, N1, D, dtype=torch.float16).npu() k = torch.randn(B, S2_compressed, N2, D, dtype=torch.float16).npu() w = torch.randn(B, S1, N1, dtype=torch.float32).npu() cmp_residual_k = torch.tensor([res_k] * B, dtype=torch.int32).npu() # Generate metadata. metadata = lightning_indexer_metadata( num_heads_q=N1, num_heads_k=N2, head_dim=D, topk=topk, cmp_residual_k=cmp_residual_k, batch_size=B, max_seqlen_q=S1, max_seqlen_k=S2_compressed, layout_q="BSND", layout_k="BSND", mask_mode=3, cmp_ratio=cmp_ratio ) # Execute lightning_indexer. sparse_indices, sparse_values = lightning_indexer( q, k, w, topk, cmp_residual_k=cmp_residual_k, metadata=metadata, max_seqlen_q=-1, layout_q="BSND", layout_k="BSND", mask_mode=3, cmp_ratio=cmp_ratio, return_value=0 ) print(f"sparse_indices shape: {sparse_indices.shape}")Call in TorchAir (aclgraph) graph mode:
import torch import torch_npu import numpy as np import torchair from cann_ops_transformer.ops import lightning_indexer, lightning_indexer_metadata B = 2 S1 = 64 S2 = 130 N1 = 16 N2 = 1 D = 128 topk = 32 cmp_ratio = 4 S2_compressed = S2 // cmp_ratio res_k = S2 % cmp_ratio q = torch.randn(B, S1, N1, D, dtype=torch.float16).npu() k = torch.randn(B, S2_compressed, N2, D, dtype=torch.float16).npu() w = torch.randn(B, S1, N1, dtype=torch.float32).npu() cmp_residual_k = torch.tensor([res_k] * B, dtype=torch.int32).npu() class LightningIndexerNetwork(torch.nn.Module): def __init__(self): super(LightningIndexerNetwork, self).__init__() def forward(self, q, k, w, cmp_residual_k): metadata = torch.ops.cann_ops_transformer.lightning_indexer_metadata( num_heads_q=N1, num_heads_k=N2, head_dim=D, topk=topk, cmp_residual_k=cmp_residual_k, batch_size=B, max_seqlen_q=S1, max_seqlen_k=S2_compressed, layout_q="BSND", layout_k="BSND", mask_mode=3, cmp_ratio=cmp_ratio ) return torch.ops.cann_ops_transformer.lightning_indexer( q, k, w, topk, cmp_residual_k=cmp_residual_k, metadata=metadata, max_seqlen_q=-1, layout_q="BSND", layout_k="BSND", mask_mode=3, cmp_ratio=cmp_ratio, return_value=1 ) from torchair.configs.compiler_config import CompilerConfig config = CompilerConfig() config.mode = "reduce-overhead" npu_backend = torchair.get_npu_backend(compiler_config=config) torch._dynamo.reset() npu_mode = torch.compile(LightningIndexerNetwork(), fullgraph=True, backend=npu_backend, dynamic=False) sparse_indices, sparse_values = npu_mode(q, k, w, cmp_residual_k) print(f"sparse_indices shape: {sparse_indices.shape}")