key_pool

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: key_pool is a Key compression operator for the inference use case. The operator performs the K projection and Gate projection on the current input tokens, groups cmp_ratio consecutive tokens into one group, computes intra-group weights using the Gate and position bias, and pools the K values within the group into one Key through weighted pooling. The K and Gate states required by incomplete compression groups are saved across calls through state_cache.

  • Formula:

    1. Compute the K and Gate for each input token:

      $$ K = hidden\_states \mathbin{@} wk^T, \qquad G = hidden\_states \mathbin{@} gate\_weight^T $$
    2. When both norm_weight and norm_bias are provided, along the last dimension of each token perform LayerNorm:

      $$ K_{norm} = LayerNorm(K, \text{dim}=-1) $$
    3. For each compression group, compute the Gate weights and perform pooling:

      $$ logits_{q,r} = G_{q,r} + ape_r $$
      $$ weight_{q,:} = softmax(logits_{q,:}) $$
      $$ pooled\_key_{q} = \sum_{r=0}^{cmp\_ratio-1} weight_{q,r} K_{norm,q,r} $$

    Historical tokens are read from state_cache through cache_block_table. The projection results generated by the current call are used to update the corresponding cache positions and participate in pooling. The first D columns of state_cache store K, and the last D columns store Gate. When LayerNorm is enabled, the K written to the cache is the result after LayerNorm. ape participates only in the pooling computation and is not written to state_cache.

    The cos and sin parameters are reserved for the RoPE entry. RoPE is not executed in the current version, and both must be simultaneously empty. seqused is also a reserved parameter and must be empty in the current version.

Prototype

cann_ops_transformer.key_pool(
    hidden_states: Tensor,
    wk: Tensor,
    gate_weight: Tensor,
    ape: Tensor,
    state_cache: Tensor,
    cache_block_table: Tensor,
    start_pos: Tensor,
    *,
    norm_weight: Tensor | None = None,
    norm_bias: Tensor | None = None,
    cos: Tensor | None = None,
    sin: Tensor | None = None,
    cu_seqlens: Tensor | None = None,
    seqused: Tensor | None = None,
    cmp_ratio: int = 4,
    norm_eps: float = 1e-6,
    rotary_mode: int = 1,
) -> Tensor

The underlying Torch operator is registered as:

torch.ops.cann_ops_transformer.key_pool(
    hidden_states: Tensor,
    wk: Tensor,
    gate_weight: Tensor,
    ape: Tensor,
    state_cache: Tensor,
    cache_block_table: Tensor,
    start_pos: Tensor,
    *,
    norm_weight: Tensor | None = None,
    norm_bias: Tensor | None = None,
    cos: Tensor | None = None,
    sin: Tensor | None = None,
    cu_seqlens: Tensor | None = None,
    seqused: Tensor | None = None,
    cmp_ratio: int = 4,
    norm_eps: float = 1e-6,
    rotary_mode: int = 1,
)

state_cache is an in-place update input. The operator returns a pooled_key Tensor.

Parameters

NameTypeRequired/OptionalDescriptionData TypeDimensions (shape)
hidden_statesTensorRequiredHidden states of the current input, corresponding to hidden_states in the formula. The data format is ND. Does not support non-contiguous tensors. Supports both BSH and TH layouts.bfloat16, float16BSH: [B,S,H]; TH: [T,H]
wkTensorRequiredK projection weight, corresponding to wk in the formula. The data format is ND. Does not support non-contiguous tensors.bfloat16, float16[D,H]
gate_weightTensorRequiredGate projection weight, corresponding to gate_weight in the formula. The data format is ND. Does not support non-contiguous tensors.bfloat16, float16[D,H]
apeTensorRequiredPosition bias, corresponding to ape in the formula. The data format is ND. Does not support non-contiguous tensors.float32[cmp_ratio,D]
state_cacheTensorRequiredPaged cache that stores historical K and Gate and is updated in place by the operator. The data format is ND. Non-contiguous axis 0 is supported, and the actual stride of axis 0 is passed in by the underlying API. The first D columns store K, and the last D columns store Gate.float32[block_num,block_size,2*D]
cache_block_tableTensorRequiredMapping table from logical blocks to physical cache blocks. The data format is ND. Does not support non-contiguous tensors.int32[B,L]
start_posTensorRequiredStart position of the current input of each batch in the logical sequence. The data format is ND. Does not support non-contiguous tensors.int32[B]
norm_weightTensorOptionalLayerNorm weight. The data format is ND. Does not support non-contiguous tensors. Must be provided together with norm_bias, or both must be empty.float32[D]
norm_biasTensorOptionalLayerNorm bias. The data format is ND. Does not support non-contiguous tensors. Must be provided together with norm_weight, or both must be empty.float32[D]
cosTensorOptionalRoPE cosine parameter. Reserved API in the current version. Must be empty.bfloat16Not applicable in the current version
sinTensorOptionalRoPE sine parameter. Reserved API in the current version. Must be empty.bfloat16Not applicable in the current version
cu_seqlensTensorOptionalCumulative token boundaries of each batch on the first axis of hidden_states in the TH use case. The data format is ND. Does not support non-contiguous tensors. Must be empty in the BSH use case.int32TH: [B+1]
sequsedTensorOptionalReserved parameter for valid sequence length. Must be empty in the current version.int32Reserved
cmp_ratiointOptionalCompression ratio, that is, the number of tokens in each pooling group. Default value is 4.--
norm_epsfloatOptionalLayerNorm epsilon. Default value is 1e-6. Must be greater than 0.--
rotary_modeintOptionalRoPE mode entry. Default value is 1. Only supports 0/1. RoPE is not executed in the current version.--

Return Values

Return ValueReturn Value TypeDescriptionData TypeDimensions (shape)
pooled_keyTensorResult of weighted pooling of K by cmp_ratio.bfloat16, float16BSH: [B,Sr,D]; TH: [Tr,D]

Where:

  • B indicates the Batch Size;
  • S indicates the input sequence length of each Batch in the BSH use case;
  • T indicates the total number of input tokens of all Batches in the TH use case;
  • H indicates the hidden size;
  • D indicates the head dimension of K and Gate, determined by wk.size(0);
  • L indicates the number of logical blocks in cache_block_table;
  • Sr = ceil(S / cmp_ratio), indicating the output capacity of each Batch in BSH;
  • Tr = min(T, T // cmp_ratio + B), indicating the total output capacity in TH.

The number of valid outputs for each Batch is valid_count, where valid_count = (start_pos + seq_len) // cmp_ratio - start_pos // cmp_ratio. For BSH, seq_len is S; for TH, seq_len is the difference between adjacent cu_seqlens values. For BSH, the valid outputs are located at pooled_key[b, :valid_count[b]]; for TH, the valid outputs are concatenated in Batch order, the start of the b-th Batch is the sum of the valid counts of all preceding Batches, and all valid results occupy the first sum(valid_count) rows of the output. The remaining output rows are uninitialized with undefined values, so callers can only use the valid range. During accuracy verification, the invalid rows can be zeroed in the copy used for comparison, but this zeroing must not be counted in the operator performance.

BSH denotes the Batch-Sequence-Hidden layout, where the shape of hidden_states is [B,S,H]. TH denotes the Token-Hidden layout, where the shape of hidden_states is [T,H], and the token boundaries of each Batch are described by cu_seqlens with the shape [B+1].

Constraints

  • When hidden_states is BSH, cu_seqlens must be empty; when it is TH, a valid [B+1] prefix sum array must be provided, whose first element is 0, last element is T, and values are monotonically non-decreasing.
  • cmp_ratio only supports 2/4/8/16/32/64/128, and the default value is 4.
  • norm_eps must be greater than 0, and the default value is 1e-6.
  • rotary_mode only supports 0/1; RoPE is not executed in the current version.
  • norm_weight and norm_bias must be simultaneously provided or empty.
  • cos and sin must be simultaneously empty; RoPE is not supported in the current version.
  • seqused must be empty; in the current version, this parameter is not used to select the tokens involved in the computation.
  • state_cache, cache_block_table, and start_pos must be provided; state_cache supports passing the stride of axis 0 through the actual tensor stride.
  • Supports B=0 or S=0 in the BSH use case, and T=0 in the TH use case.
  • The current API is used for the NPU inference use case. The input tensor must be on the NPU device.

Example

Single Operator Mode

import torch
import torch_npu
import cann_ops_transformer

B = 1
S = 8
H = 4096
D = 128
cmp_ratio = 4
block_size = 16
device = "npu:0"

hidden_states = torch.randn((B, S, H), dtype=torch.bfloat16, device=device)
wk = torch.randn((D, H), dtype=torch.bfloat16, device=device)
gate_weight = torch.randn((D, H), dtype=torch.bfloat16, device=device)
ape = torch.randn((cmp_ratio, D), dtype=torch.float32, device=device)

block_num = (S + block_size - 1) // block_size
cache_block_table = torch.arange(
    1, B * block_num + 1, dtype=torch.int32, device=device
).reshape(B, block_num)
state_cache = torch.zeros(
    (B * block_num + 1, block_size, 2 * D),
    dtype=torch.float32,
    device=device,
)
start_pos = torch.zeros((B,), dtype=torch.int32, device=device)

pooled_key = cann_ops_transformer.key_pool(
    hidden_states,
    wk,
    gate_weight,
    ape,
    state_cache,
    cache_block_table,
    start_pos,
    cmp_ratio=cmp_ratio,
)
torch.npu.synchronize()
print(pooled_key.shape)

When LayerNorm is enabled, pass both norm_weight and norm_bias:

norm_weight = torch.ones((D,), dtype=torch.float32, device=device)
norm_bias = torch.zeros((D,), dtype=torch.float32, device=device)

pooled_key = cann_ops_transformer.key_pool(
    hidden_states,
    wk,
    gate_weight,
    ape,
    state_cache,
    cache_block_table,
    start_pos,
    norm_weight=norm_weight,
    norm_bias=norm_bias,
    norm_eps=1e-6,
    rotary_mode=1,
    cmp_ratio=cmp_ratio,
)

TorchAir Graph Mode Call (Not Currently Supported)

Currently, key_pool does not provide graph_convert_key_pool.py or the corresponding TorchAir Converter registration. Therefore, calls through the TorchAir graph mode are not currently supported. Use the single-operator mode API above.