flash_attn
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Not supported
Atlas A2 products : Not supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description:
flash_attnis acann_ops_transformerextension API based onTorchNPU. It calls theFlashAttnoperator to perform non-quantized attention computation with shared KV (Key and Value use the same input), unifying training and inference.flash_attn_metadatais the metadata generation API offlash_attn, used to generate metadata before the main operator executes. The metadata records the task splitting results of AICore/AIVCore. The main operator can optionally pass in this metadata to optimize scheduling. The typical call flow is as follows:- Prepare inputs such as
q,k, andv. - Call
flash_attn_metadatato generatemetadata. - Call
flash_attnand pass themetadataobtained in the previous step to the main operator.
- Prepare inputs such as
Formula:
self-attention builds an attention model using the relationships within the input samples. The principle is: assume an input sample sequence $x$ of length $n$, where each element of $x$ is a $d$-dimensional vector. Each $d$-dimensional vector can be regarded as a token embedding. The sequence is transformed through 3 weight matrices to obtain 3 matrices of dimension $n \times d$.
The self-attention formula is generally defined as follows, where $Q$, $K$, and $V$ are important property elements of the input sample, obtained by spatially transforming the input sample and unifiable into a single feature space. "Attention" in the formula and operator name is an abbreviation of "self-attention".
$$ Attention(Q,K,V)=Score(Q,K)V $$In this operator, the Score function adopts the Softmax function. The self-attention computation formula is:
$$ Attention(Q,K,V)=Softmax(\frac{QK^T}{\sqrt{d}})V $$The product of $Q$ and $K^T$ represents the attention of the input $x$. To prevent this value from becoming excessively large, it is usually divided by $\sqrt{d}$ for scaling, and each row is normalized by softmax. The result is then multiplied by $V$ to obtain an $n \times d$ matrix.
After sink is added, the calculation logic is as follows. The softmax_max and softmax_sum calculation parts are mainly modified.
$$ S = \frac{QK^T}{\sqrt{d}} $$$$ m = max(sink, max(S)) $$$$ Attention = \frac{e^{S - m} \times V}{\sum e^{S-m} + e^{sink - m}} $$After return_softmax_lse is enabled, the return value softmax_lse is calculated as follows:
$$ S = \frac{QK^T}{\sqrt{d}} $$$$ softmax\_max = max(S) $$$$ softmax\_lse = log{\sum e^{S-softmax\_max}} + softmax\_max $$
The q, k, and v data layout formats can be interpreted from multiple dimensions: B (Batch) indicates input sample batch size batch_size, S (Seq-Length) indicates input sample sequence length, H (Hidden-Size) indicates the size of the hidden layer, N (Head-Num) indicates the number of heads, and D (Head-Dim) indicates the size of headdim, the smallest unit of the hidden layer, where D=H/N. Q_T indicates the cumulative sum of sequence lengths of all query Batch input samples, and KV_T indicates the cumulative sum of sequence lengths of all k and v Batch input samples. Q_S indicates seqlen_q, Q_N indicates nheads_q, KV_S indicates seqlen_kv, and KV_N indicates nheads_kv.
Prototype
Before calling the flash_attn API, call the prerequisite API flash_attn_metadata first to complete the load balancing computation of flash_attn.
cann_ops_transformer.flash_attn_metadata(
num_heads_q,
num_heads_kv,
head_dim,
*,
cu_seqlens_q=None,
cu_seqlens_kv=None,
seqused_q=None,
seqused_kv=None,
batch_size=None,
max_seqlen_q=None,
max_seqlen_kv=None,
mask_mode=None,
win_left=None,
win_right=None,
layout_q=None,
layout_kv=None,
layout_out=None
) -> Tensorcann_ops_transformer.flash_attn(
q,
k,
v,
block_table=None,
cu_seqlens_q=None,
cu_seqlens_kv=None,
seqused_q=None,
seqused_kv=None,
sinks=None,
metadata=None,
softmax_scale=1.0,
mask_mode=0,
attn_mask=None,
win_left=-1,
win_right=-1,
max_seqlen_q=-1,
max_seqlen_kv=-1,
layout_q="BSND",
layout_kv="BSND",
layout_out="BSND",
return_softmax_lse=False
) -> (Tensor, Tensor)Parameters
flash_attn_metadata
| Name | Type | Required/Optional | Description | Data Type | Data Format | Dimensions |
|---|---|---|---|---|---|---|
| num_heads_q | int | Required | Number of Query heads. | int32 | - | - |
| num_heads_kv | int | Required | Number of Key/Value heads. | int32 | - | - |
| head_dim | int | Required | Dimension of each attention head. | int32 | - | - |
| cu_seqlens_q | Tensor | Optional | Cumulative sequence length, used to process variable-length sequences. The first element must be 0 | int32 | ND | (B+1,) |
| cu_seqlens_kv | Tensor | Optional | Cumulative sequence length, used to process variable-length sequences. The first element must be 0 | int32 | ND | (B+1,) |
| seqused_q | Tensor | Optional | Specifies the actual sequence length used in each batch to truncate redundant computation. | int32 | ND | (B,) |
| seqused_kv | Tensor | Optional | Specifies the actual sequence length used in each batch to truncate redundant computation. | int32 | ND | (B,) |
| batch_size | int | Optional | Batch size. Derived from cu_seqlens_q or seqused_q if not passed. The default value is None. | int32 | - | - |
| max_seqlen_q | int | Optional | Upper limit of the sequence length of query q. | int32 | - | - |
| max_seqlen_kv | int | Optional | Upper limit of the sequence length of key k and value v. | int32 | - | - |
| mask_mode | int | Optional | Mask mode. | int32 | - | - |
| win_left | int | Optional | Left boundary of the window. | int32 | - | - |
| win_right | int | Optional | Right boundary of the window. | int32 | - | - |
| layout_q | string | Optional | Defines the layout format of the input q tensor. | string | - | - |
| layout_kv | string | Optional | Defines the layout format of the input k and v tensors. | string | - | - |
| layout_out | string | Optional | Defines the layout format of the output tensor. | string | - | - |
flash_attn
| Name | Type | Required/Optional | Description | Data Type | Data Format | Dimension |
|---|---|---|---|---|---|---|
| q | Tensor | Required | q in the formula | bfloat16/float16 | ND |
|
| k | Tensor | Required | k in the formula | bfloat16/float16 | ND |
|
| v | Tensor | Required | v in the formula | bfloat16/float16 | ND |
|
| block_table | Tensor | Optional | Block index mapping in block-wise attention computation. | int32 | ND | (B, max_num_blocks_per_seq) |
| cu_seqlens_q | Tensor | Optional | Cumulative sequence length, used to process variable-length sequences. The first element must be 0 | int32 | ND | (B+1,) |
| cu_seqlens_kv | Tensor | Optional | Cumulative sequence length, used to process variable-length sequences. The first element must be 0 | int32 | ND | (B+1,) |
| seqused_q | Tensor | Optional | Specifies the actual sequence length used in each batch to truncate redundant computation. | int32 | ND | (B,) |
| seqused_kv | Tensor | Optional | Specifies the actual sequence length used in each batch to truncate redundant computation. | int32 | ND | (B,) |
| sinks | Tensor | Optional | Attention sink parameter used to improve the numerical stability of self-attention computation. | float32 | ND | (Q_N,) |
| metadata | Tensor | Optional | Task splitting result generated by flash_attn_metadata. Passing it in optimizes scheduling. | int32 | ND | (max_schedule_size,) |
| softmax_scale | float | Optional | Scaling factor that can be explicitly set to override the default computation. | float32 | - | - |
| mask_mode | int | Optional | Mask mode. | int32 | - | - |
| attn_mask | Tensor | Optional | Mask matrix. | int8 | ND | (2048, 2048) |
| win_left | int | Optional | Left boundary of the window. | int32 | - | - |
| win_right | int | Optional | Right boundary of the window. | int32 | - | - |
| max_seqlen_q | int | Optional | Upper limit of the sequence length of query q. | int32 | - | - |
| max_seqlen_kv | int | Optional | Upper limit of the sequence length of key k and value v. | int32 | - | - |
| layout_q | string | Optional | Defines the layout format of the input q tensor. | string | - | - |
| layout_kv | string | Optional | Defines the layout format of the input k and v tensors. | string | - | - |
| layout_out | string | Optional | Defines the layout format of the output tensor. | string | - | - |
| return_softmax_lse | bool | Optional | Whether to obtain the LSE result of softmax. | bool | - | - |
Return Values
flash_attn_metadata
| Name | Type | Required/Optional | Description | Data Type | Data Format | Dimensions |
|---|---|---|---|---|---|---|
| metadata | Tensor | Required | Task splitting data of flash_attn. | int32 | ND | Shape is dynamically calculated based on batch_size and num_heads_kv. |
flash_attn
| Name | Type | Required/Optional | Description | Data Type | Data Format | Dimension |
|---|---|---|---|---|---|---|
| attn_out | Tensor | Required | Computation output of flash_attn. | bfloat16/float16 | ND |
|
| softmax_lse | Tensor | Optional | LSE result of softmax. | float32 | ND |
|
NOTE
- attn_out: Constraint: The D dimension of this output parameter must be the same as the D of value, and the other dimensions must be consistent with the shape of the input query.
- softmax_lse: If return_softmax_lse is True, the output is generally a Tensor with shape (B, Q_N, Q_S), or a Tensor with shape (Q_N, Q_T) when input_q is TND. If return_softmax_lse is False, the output is a Tensor with shape [1] and a value of 0.
Constraints
- Parameters cu_seqlens_q, cu_seqlens_kv, seqused_q, seqused_kv, block_table, and attn_mask are tensors. Since the operator cannot obtain the specific values of tensors in the Tiling phase, the tiling side does not validate the values, and users must ensure correctness. If invalid values are passed for the preceding parameters, undefined behavior occurs (such as precision issues and program crashes caused by invalid memory access).
- The input parameters of flash_attn_metadata and flash_attn must be consistent when the APIs are called. Since the operator is called in two phases through two APIs, the operator cannot validate the consistency itself, and you must ensure correctness. If inconsistent parameters are passed in, undefined behavior occurs, such as precision issues or program crashes caused by invalid memory access.
Feature Parameter Group
| Feature Parameter Group | Parameter Field Name | Field Grouping | Field Type |
|---|---|---|---|
| Common Parameter Group | q | INPUT | Tensor |
| k | INPUT | Tensor | |
| v | INPUT | Tensor | |
| metadata | INPUT(OPTIONAL) | Tensor | |
| softmax_scale | ATTR(OPTIONAL) | float | |
| layout_q | ATTR(OPTIONAL) | string | |
| layout_kv | ATTR(OPTIONAL) | string | |
| layout_out | ATTR(OPTIONAL) | string | |
| attn_out | OUTPUT | Tensor | |
| Mask Parameter Group | mask_mode | ATTR(OPTIONAL) | int |
| win_left | ATTR(OPTIONAL) | int | |
| win_right | ATTR(OPTIONAL) | int | |
| attn_mask | INPUT(OPTIONAL) | Tensor | |
| SeqLens Parameter Group | cu_seqlens_q | INPUT(OPTIONAL) | Tensor |
| cu_seqlens_kv | INPUT(OPTIONAL) | Tensor | |
| seqused_q | INPUT(OPTIONAL) | Tensor | |
| seqused_kv | INPUT(OPTIONAL) | Tensor | |
| max_seqlen_q | ATTR(OPTIONAL) | int | |
| max_seqlen_kv | ATTR(OPTIONAL) | int | |
| Paged Attention Parameter Group | block_table | INPUT(OPTIONAL) | Tensor |
| Sinks Parameter Group | sinks | INPUT(OPTIONAL) | Tensor |
| SoftmaxLSE Parameter Group | return_softmax_lse | ATTR(OPTIONAL) | bool |
| softmax_lse | OUTPUT | Tensor |
Baseline Information
Common fields in the documentation constraints are defined as follows:
| Name | Meaning |
|---|---|
| B | Batch, indicating the batch size of input samples. |
| Q_N | Number of heads of the input q tensor, corresponding to N in the q shape. |
| KV_N | Number of heads of the input k/v tensor, corresponding to N in the k/v shape. |
| Q_S | Sequence length of the input q tensor, corresponding to S in the q shape. |
| KV_S | Sequence length of the input k/v tensor, corresponding to S in the k/v shape. |
| Q_T | Cumulative sum of sequence lengths of all batches in the input q tensor. |
| KV_T | Cumulative sum of sequence lengths of all batches in the input k/v tensor. |
| D | Minimum hidden layer unit size (headdim) of the input q/k/v tensors and the output attn_out. |
Parameter Group Constraints
Common Parameter Group
Handling of empty input parameters:
- An empty tensor indicates that the shape size of a required input or output is 0, that is, at least one axis is 0.
- Use cases that trigger an empty tensor are all intercepted and an error is reported.
Validation of q, k, v, and attn_out:
Parameter Single-Parameter Validation Existence Validation Consistency Validation Feature Cross Validation q - tensor_type supports bfloat16 and float16.
- BNSD -> (B, N_Q, S_Q, D)
- BSND -> (B, S_Q, N_Q, D)
- TND -> (T_Q, N_Q, D)
Must exist. - The data types of q, k, v, and attn_out must be the same.
- The shapes of k and v must be the same.
- For layout validation rules, see the layout matching relationship table.
Axis validation: - 65536 > B > 0
- Q_T > 0
- KV_T > 0
- Q_N > 0
- KV_N > 0
- Q_S > 0
- KV_S > 0
- D supports 64, 128, and 256.
- The D dimension of q must be equal to that of k/v.
- Q_N % KV_N == 0 and Q_N / KV_N > 0
k - tensor_type supports bfloat16 and float16.
- BNSD -> (B, N_KV, S_KV, D)
- BSND -> (B, S_KV, N_KV, D)
- TND -> (T_KV, N_KV, D)
- PA_BBND -> (num_blocks, block_size, KV_N, D)
- PA_BNBD -> (num_blocks, KV_N, block_size, D)
- PA_NZ -> (num_blocks, KV_N, D//16, block_size, 16)
- 1024 >= block_size >= 16 and block_size % 16 == 0
- Non-contiguous tensor constraints:
- BNSD/BSND/TND: k/v must be contiguous. Passing a non-contiguous tensor causes an error.
- PA_BBND: only dim0 can be non-contiguous.
- PA_BNBD/PA_NZ: dim0 or dim1 can be non-contiguous.
- Note: the stride of each dimension of a non-contiguous tensor cannot be 0. Otherwise, an error is reported.
v attn_out - data_type supports bfloat16 and float16.
- shape supports 3 or 4 dimensions.
Layout matching relationship table:
layout_q layout_kv layout_out layout_softmax_lse BNSD - BNSD
- PA_BBND
- PA_BNBD
- PA_NZ
- BNSD
- BSND
(B, Q_N, Q_S) BSND - BSND
- PA_BBND
- PA_BNBD
- PA_NZ
BSND (B, Q_N, Q_S) TND - TND
- PA_BBND
- PA_BNBD
- PA_NZ
TND (Q_N, Q_T) metadata validation:
Parameter Single-Parameter Validation Existence Validation Consistency Validation Feature Cross Validation metadata - tensor_type only supports int32.
- shape is dynamically calculated by flash_attn_metadata.
- Currently, omission is not supported; if this parameter is not passed in, an interception alarm is issued.
Optional parameter None If passed in, the value must be consistent with the result generated by flash_attn_metadata.
Mask Parameter Group
mask_mode parameter description
- mask_mode=0, full computation mode (default)
- mask_mode=3, Causal mode
- mask_mode=4, Window mode
| Parameter | Single-Parameter Validation | Existence Validation | Consistency Validation | Feature Cross-Validation |
|---|---|---|---|---|
| mask_mode |
|
Optional input. If this parameter is not passed in, the default value is 0. |
|
|
| attn_mask |
|
None | ||
| win_left |
|
|||
| win_right |
SeqLengths parameter group
| Parameter | Single-Parameter Validation | Existence Validation | Consistency Validation | Feature Cross-Validation |
|---|---|---|---|---|
| seqused_q |
|
Optional parameter | None | None |
| seqused_kv | ||||
| cu_seqlens_q |
|
|
||
| cu_seqlens_kv | ||||
| max_seqlen_q |
|
|
|
|
| max_seqlen_kv |
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 |
|
Sinks Parameter Group
| Parameter | Single-Parameter Validation | Existence Validation | Consistency Validation | Feature Cross-Validation |
|---|---|---|---|---|
| sinks |
|
Optional parameter | None | Currently not supported. |
SoftmaxLSE Parameter Group
| Parameter | Single-Parameter Validation | Existence Validation | Consistency Validation | Feature Cross-Validation |
|---|---|---|---|---|
| return_softmax_lse |
|
Optional attribute. The default value is False. |
|
None |
| softmax_lse |
|
None | None |
Example
Example of calling flash_attn_metadata + flash_attn (BSND)
import torch import torch_npu import cann_ops_transformer torch_npu.npu.set_device(0) dtype = torch.bfloat16 B = 2 S = 16 Q_N = 8 KV_N = 2 D = 128 q = torch.randn(B, S, Q_N, D, dtype=dtype, device="npu") k = torch.randn(B, S, KV_N, D, dtype=dtype, device="npu") v = torch.randn(B, S, KV_N, D, dtype=dtype, device="npu") metadata = cann_ops_transformer.ops.flash_attn_metadata( Q_N, KV_N, D, batch_size=B, max_seqlen_q=S, max_seqlen_kv=S, mask_mode=0, win_left=-1, win_right=-1, layout_q="BSND", layout_kv="BSND", layout_out="BSND", ) attn_out, softmax_lse = cann_ops_transformer.ops.flash_attn( q, k, v, metadata=metadata, softmax_scale=1.0 / (D ** 0.5), mask_mode=0, win_left=-1, win_right=-1, layout_q="BSND", layout_kv="BSND", layout_out="BSND", return_softmax_lse=False, ) torch_npu.npu.synchronize() assert attn_out.shape == q.shape assert attn_out.dtype == q.dtype assert torch.isfinite(attn_out.float()).all().item()