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_poolis a Key compression operator for the inference use case. The operator performs the K projection and Gate projection on the current input tokens, groupscmp_ratioconsecutive 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 throughstate_cache.Formula:
Compute the K and Gate for each input token:
$$ K = hidden\_states \mathbin{@} wk^T, \qquad G = hidden\_states \mathbin{@} gate\_weight^T $$When both
norm_weightandnorm_biasare provided, along the last dimension of each token perform LayerNorm:$$ K_{norm} = LayerNorm(K, \text{dim}=-1) $$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_cachethroughcache_block_table. The projection results generated by the current call are used to update the corresponding cache positions and participate in pooling. The firstDcolumns ofstate_cachestore K, and the lastDcolumns store Gate. When LayerNorm is enabled, the K written to the cache is the result after LayerNorm.apeparticipates only in the pooling computation and is not written tostate_cache.The
cosandsinparameters are reserved for the RoPE entry. RoPE is not executed in the current version, and both must be simultaneously empty.sequsedis 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,
) -> TensorThe 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
| Name | Type | Required/Optional | Description | Data Type | Dimensions (shape) |
|---|---|---|---|---|---|
| hidden_states | Tensor | Required | Hidden 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, float16 | BSH: [B,S,H]; TH: [T,H] |
| wk | Tensor | Required | K projection weight, corresponding to wk in the formula. The data format is ND. Does not support non-contiguous tensors. | bfloat16, float16 | [D,H] |
| gate_weight | Tensor | Required | Gate projection weight, corresponding to gate_weight in the formula. The data format is ND. Does not support non-contiguous tensors. | bfloat16, float16 | [D,H] |
| ape | Tensor | Required | Position bias, corresponding to ape in the formula. The data format is ND. Does not support non-contiguous tensors. | float32 | [cmp_ratio,D] |
| state_cache | Tensor | Required | Paged 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_table | Tensor | Required | Mapping table from logical blocks to physical cache blocks. The data format is ND. Does not support non-contiguous tensors. | int32 | [B,L] |
| start_pos | Tensor | Required | Start 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_weight | Tensor | Optional | LayerNorm 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_bias | Tensor | Optional | LayerNorm 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] |
| cos | Tensor | Optional | RoPE cosine parameter. Reserved API in the current version. Must be empty. | bfloat16 | Not applicable in the current version |
| sin | Tensor | Optional | RoPE sine parameter. Reserved API in the current version. Must be empty. | bfloat16 | Not applicable in the current version |
| cu_seqlens | Tensor | Optional | Cumulative 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. | int32 | TH: [B+1] |
| seqused | Tensor | Optional | Reserved parameter for valid sequence length. Must be empty in the current version. | int32 | Reserved |
| cmp_ratio | int | Optional | Compression ratio, that is, the number of tokens in each pooling group. Default value is 4. | - | - |
| norm_eps | float | Optional | LayerNorm epsilon. Default value is 1e-6. Must be greater than 0. | - | - |
| rotary_mode | int | Optional | RoPE mode entry. Default value is 1. Only supports 0/1. RoPE is not executed in the current version. | - | - |
Return Values
| Return Value | Return Value Type | Description | Data Type | Dimensions (shape) |
|---|---|---|---|---|
| pooled_key | Tensor | Result of weighted pooling of K by cmp_ratio. | bfloat16, float16 | BSH: [B,Sr,D]; TH: [Tr,D] |
Where:
Bindicates the Batch Size;Sindicates the input sequence length of each Batch in the BSH use case;Tindicates the total number of input tokens of all Batches in the TH use case;Hindicates the hidden size;Dindicates the head dimension of K and Gate, determined bywk.size(0);Lindicates the number of logical blocks incache_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_statesis BSH,cu_seqlensmust be empty; when it is TH, a valid[B+1]prefix sum array must be provided, whose first element is 0, last element isT, and values are monotonically non-decreasing. cmp_ratioonly supports2/4/8/16/32/64/128, and the default value is4.norm_epsmust be greater than 0, and the default value is1e-6.rotary_modeonly supports0/1; RoPE is not executed in the current version.norm_weightandnorm_biasmust be simultaneously provided or empty.cosandsinmust be simultaneously empty; RoPE is not supported in the current version.sequsedmust be empty; in the current version, this parameter is not used to select the tokens involved in the computation.state_cache,cache_block_table, andstart_posmust be provided;state_cachesupports passing the stride of axis 0 through the actual tensor stride.- Supports
B=0orS=0in the BSH use case, andT=0in 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.