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_metadata API 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 subsequent lightning_indexer operator.

    The lightning_indexer API obtains the top-k positions for each token through a series of operations. The main computation process is as follows:

    1. Multiply the input parameter q ($Q_{index}\in\R^{g\times d}$) corresponding to a token by the given context k ($K_{index}\in\R^{S_{k}\times d}$) to obtain the correlation.
    2. Filter invalid negative correlation signals through the activation function $ReLU$ to obtain the correlation score vector between the current token and all preceding tokens.
    3. 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.
  • 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
) -> Tensor
cann_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

NameTypeRequired/OptionalDescriptionData TypeDimension (Shape)
num_heads_qintRequiredNumber of heads for q.int64-
num_heads_kintRequiredNumber of heads for k. Currently only supports 1.int64-
head_dimintRequiredDimension of the attention head. Currently only supports 128.int64-
topkintRequiredNumber of Key token indexes retained for each q token. Currently, values in [1, 8192] are supported.int64-
cu_seqlens_qTensorOptionalCumulative 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_kTensorOptionalCumulative 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_qTensorOptionalSequence Length of q actually participating in the computation in each batch. The data format is ND. Non-contiguous tensors are supported.int32(b, )
seqused_kTensorOptionalSequence 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_kTensorOptionalRemainder 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_sizeintOptionalNumber of batches. The default value is 0.int64-
max_seqlen_qintOptionalMaximum Sequence Length of q. -1 indicates any possible length. The default value is -1.int64-
max_seqlen_kintOptionalMaximum Sequence Length of k. -1 indicates any possible length. The default value is -1.int64-
layout_qstrOptionalLayout of q. Supports BSND and TND. The default value is BSND.string-
layout_kstrOptionalLayout of k. Supports BSND, TND, and PA_BBND. The default value is BSND.string-
mask_modeintOptionalSparse mode. 0 indicates No mask, and 3 indicates rightDownCausal mode. The default value is 0.int64-
cmp_ratiointOptionalCompression ratio of k. Value range: [1, 128]. The default value is 1, indicating no compression.int64-

lightning_indexer

NameTypeRequired/OptionalDescriptionData TypeDimension (Shape)
qTensorRequiredInput Q in the formula. Empty tensors are not supported. Data format: ND.bfloat16, float16shape is (b,q_s,q_n,d) when layout_q is BSND; shape is (q_t,q_n,d) when layout_q is TND
kTensorRequiredInput 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, float16shape 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
wTensorRequiredInput W in the formula. Empty tensors are not supported. Data format: ND.floatshape is (b,q_s,q_n) when layout_q is BSND; shape is (q_t,q_n) when layout_q is TND
topkintRequiredNumber of Key token indices to retain in the topK phase. Value range: [1, 8192].int64-
cu_seqlens_qTensorOptionalCumulative 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_kTensorOptionalCumulative 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_qTensorOptionalActual used length of q in different batches. Data format: ND.int32(b,)
seqused_kTensorOptionalActual used length of k in different batches. Data format: ND.int32(b,)
cmp_residual_kTensorOptionalRemainder 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_tableTensorOptionalBlock 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_offsetTensorOptionalOffset 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.int32shape is (b,q_s,k_n) when layout_q is BSND; shape is (q_t,k_n) when layout_q is TND
metadataTensorOptionalCore 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_qintOptionalMaximum sequence length of q. -1 indicates any possible length. Default value is -1.int64-
layout_qstrOptionalData layout format of input q. Supports BSND and TND. Default value is BSND.string-
layout_kstrOptionalData layout format of input k. Supports BSND, TND, and PA_BBND. Default value is BSND.string-
mask_modeintOptionalMask mode. 0 indicates the defaultMask mode, and 3 indicates the rightDownCausal mode. Default value is 0.int64-
cmp_ratiointOptionalUsed for sparse computation, indicating the compression ratio of k. Value range: 1-128. Default value: 1.int64-
return_valueintOptionalWhether to return the Values corresponding to Indices. 0 indicates no return, and 1 indicates return. Default value: 0.int64-

Return Values

lightning_indexer_metadata

NameTypeRequired/OptionalDescriptionData TypeDimension (Shape)
metadataTensorRequiredIndex 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

NameTypeRequired/OptionalDescriptionData TypeDimension (Shape)
sparse_indicesTensorRequiredIndices 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_valuesTensorconditional outputValues 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 and Atlas 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 GroupParameter Field Names
Common Parameter Groupq、k、w、metadata、output_idx_offset、topk、layout_q、layout_k、sparse_indices、sparse_values
Mask Parameter Groupmask_mode
SeqLens Parameter Groupcu_seqlens_q、cu_seqlens_k、seqused_q、seqused_k、max_seqlen_q
sparse compression parameter groupcmp_ratio、cmp_residual_k
Paged Attention Parameter Groupblock_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
  • tensor_type supports BFLOAT16 and FLOAT16.
  • BSND -> (b, q_s, q_n, d)
  • TND -> (q_t, q_n, d)
Required.
  • q and k must have the same data type.
  • For layout check rules, see the layout matching table.
Axis check:
  • 65536 > b > 0
  • q_t > 0
  • k_t > 0
  • q_n > 0
  • k_n = 1
  • q_s > 0
  • k_s > 0
  • d = 128
k
  • tensor_type supports BFLOAT16 and FLOAT16.
  • BSND -> (b, k_s, k_n, d)
  • TND -> (k_t, k_n, d)
  • PA_BBND -> (num_blocks, block_size, k_n, d)
  • 1024 >= block_size >= 16 and block_size % 16 == 0
sparse_indices
  • tensor_type supports INT32.
  • If layout_q is BSND, the shape of sparse_indices is (b, q_s, k_n, topk).
  • If layout_q is TND, the shape of sparse_indices is (q_t, k_n, topk).
sparse_values
  • tensor_type supports FLOAT32.
  • When layout_q is BSND, the shape of sparse_indices is (b, q_s, k_n, topk).
  • When layout_q is TND, the shape of sparse_indices is (q_t, k_n, topk).

Layout matching relationship table:

layout_q layout_k layout_out
BSND
  • BSND
  • PA_BBND
  • BSND
    TND
  • TND
  • PA_BBND
  • TND

    Metadata validation

    Parameter Single-Parameter Check Existence Check Consistency Check Feature Cross-Check
    metadata
    • tensor_type supports only INT32.
    • The shape is dynamically computed by lightning_indexer_v2_metadata.
    • Currently, this parameter is required. Otherwise, an interception alarm is reported.
    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
    • data_type supports INT.
    • Only 0 and 3 are supported; the default value is 0.
    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
    • tensor_type supports INT32.
    • tensor_shape is (b,).
    • Only non-negative integers are supported.
    • Values in seqused_q must be less than or equal to q_s.
    • Values in seqused_k must be less than or equal to k_s.
    Optional parameters None None
    seqused_k
    cu_seqlens_q
    • tensor_type supports INT32.
    • tensor_shape is (b+1,).
    • Values must be non-negative integers.
    • Values must be in non-decreasing order (each greater than or equal to the previous one). The first element must be 0 and the last element must be q_t.
    • Required when layout_q is TND.
    • Not supported when layout_q is not TND.
    cu_seqlens_k
    • tensor_type supports INT32.
    • tensor_shape is (b+1,).
    • Values must be non-negative integers.
    • Values must be non-decreasing (each value greater than or equal to the previous one), with the first element being 0 and the last element equal to k_t.
    • Required when layout_k is TND.
    • Not supported when layout_k is not TND.
    max_seqlen_q
    • data_type supports INT.
    • Not effective currently; only -1 is supported.
    • Default value: -1.
    • Not effective currently; only -1 can be passed in.

    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
    • tensor_type supports only INT32.
    • tensor_shape is (b, max_num_blocks_per_seq).
    • Values must be positive integers.
    Optional parameter None
    • When PagedAttention is enabled, seqused_k must be passed in.
    • When PagedAttention is enabled, block_table must not be empty.

    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}")