flash_attn
Applicable Products
Ascend 950PR/Ascend 950DT : SupportedAtlas A3 training products/Atlas A3 inference products : Not SupportedAtlas A2 training products/Atlas A2 inference products : Not SupportedAtlas 200I/500 A2 inference products : Not SupportedAtlas inference products : Not SupportedAtlas training products : Not Supported
Function
Description:
flash_attnis an extension API ofcann_ops_transformerbased onTorchNPU. It calls theFlashAttnoperator to perform non-quantized attention computation with shared KV (Key and Value use the same input), unified for training and inference.flash_attn_metadatais the metadata generation API offlash_attn. It generates metadata before the main operator executes. The metadata records the task splitting results of AICore/AIVCore. The main operator can optionally take 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 themselves. The principle is as follows: assume an input sample sequence of length , where each element of is a -dimensional vector. Each -dimensional vector can be regarded as a token embedding. Transform this sequence through three weight matrices to obtain three matrices of dimension .
The self-attention formula is generally defined as follows, where , , and 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".
In this operator, the Score function uses the Softmax function. The self-attention formula is:
Where the product of and represents the attention of the input . To prevent this value from becoming too large, it is usually divided by for scaling, and each row is normalized by softmax. After multiplying by , a matrix of dimension is obtained.
After adding sink, the computation logic is as follows, mainly modifying the softmax_max and softmax_sum logic computation parts.
After return_softmax_lse is enabled, the returned softmax_lse is calculated as follows:
The q, k, and v data layouts can be interpreted from multiple dimensions. B (Batch) indicates the input sample batch size batch_size. S (Seq-Length) indicates the input sample sequence length. H (Hidden-Size) indicates the hidden layer size. N (Head-Num) indicates the number of heads. D (Head-Dim) indicates the smallest unit size headdim of the hidden layer, satisfying D=H/N. Q_T indicates the cumulative sum of the sequence lengths of all query batch input samples. KV_T indicates the cumulative sum of the 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. KV_N indicates nheads_kv.
Prototype
Before calling the flash_attn API, call the preceding flash_attn_metadata API to complete the load balancing computation for flash_attn.
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
) -> Tensorflash_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
| Parameter | Parameter Type | Optional/Required | Description | Data Type | Data Format | Dimension |
|---|---|---|---|---|---|---|
| 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 for processing variable-length sequences. The first element must be 0. | int32 | ND | (B+1,) |
| cu_seqlens_kv | Tensor | Optional | Cumulative sequence length for processing 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. If not passed, it is deduced from cu_seqlens_q or seqused_q. Default Value: None. | int32 | - | - |
| max_seqlen_q | int | Optional | Specifies the upper limit of the query q sequence length. | int32 | - | - |
| max_seqlen_kv | int | Optional | Specifies the upper limit of the key k and value v sequence length. | 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
| Parameter | Parameter Type | Optional/Required | 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 for block-wise attention computation. | int32 | ND | (B, max_num_blocks_per_seq) |
| cu_seqlens_q | Tensor | Optional | Cumulative sequence length for variable-length sequences. The first element must be 0. | int32 | ND | (B+1,) |
| cu_seqlens_kv | Tensor | Optional | Cumulative sequence length for 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 for improving the numerical stability of self-attention computation. | float32 | ND | (Q_N,) |
| metadata | Tensor | Optional | Task splitting result generated by flash_attn_metadata. Passing it optimizes scheduling. | int32 | ND | (max_schedule_size,) |
| softmax_scale | float | Optional | Explicitly sets the scaling factor, overriding 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 | Specifies the upper limit of the query q sequence length. | int32 | - | - |
| max_seqlen_kv | int | Optional | Specifies the upper limit of the key k and value v sequence length. | 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 Value
flash_attn_metadata
| Parameter | Parameter Type | Optional/Required | Description | Data Type | Data Format | Dimension |
|---|---|---|---|---|---|---|
| metadata | Tensor | Required | Task partitioning data of flash_attn. | int32 | ND | The shape is dynamically calculated based on batch_size and num_heads_kv. |
flash_attn
| Parameter | Parameter Type | Optional/Required | Description | Data Type | Data Format | Dimension |
|---|---|---|---|---|---|---|
| attn_out | Tensor | Required | Output of the flash_attn computation. | bfloat16/float16 | ND |
|
| softmax_lse | Tensor | Optional | LSE result of softmax. | float32 | ND |
|
Note
- attn_out: Tensor type, the output in the formula. Supported data types: float16 and bfloat16. Supported data format: ND. Constraint: the D dimension of this output parameter must be consistent with the D dimension of value, and the other dimensions must be consistent with the shape of the input query.
- softmax_lse: Tensor type. In the ring attention algorithm, the result of query multiplied by key first takes max to obtain softmax_max. The result of query multiplied by key subtracts softmax_max, then takes exp, and finally takes sum to obtain softmax_sum. Finally, log is taken on softmax_sum, and softmax_max is added to obtain the result. Supported data type: float32. When return_softmax_lse is True, the output is generally a Tensor of shape (B, Q_N, Q_S). When input_q is TND, the output is a Tensor of shape (Q_N, Q_T). When return_softmax_lse is False, the output is a Tensor of shape [1] with value 0.
Constraints
Declaration:
- The parameters cu_seqlens_q, cu_seqlens_kv, seqused_q, seqused_kv, block_table, and attn_mask are tensors. Because the operator cannot obtain the specific values of tensors during the Tiling phase, the Tiling side does not validate the values. The user must ensure correctness. If invalid values are passed for the above parameters, undefined behavior is triggered (precision issues, program crashes caused by illegal memory access, etc.).
- The input parameters of flash_attn_metadata and flash_attn must be consistent when called. Because the operator is called in two phases through two APIs, the operator cannot validate this by itself. The user must ensure correctness. If inconsistent parameters are passed to the APIs, undefined behavior occurs (precision issues, program crashes caused by illegal memory access, etc.).
Feature Parameter Group
| Feature Parameter Group | Parameter | Field Grouping | Parameter 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 |
Basic Information
In the documentation constraints, common fields are defined as follows:
| Naming | Description |
|---|---|
| B | Batch. Indicates the input sample batch size. |
| 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 the sequence lengths of all batches of the input q tensor. |
| KV_T | Cumulative sum of the sequence lengths of all batches of the input k/v tensor. |
| D | headdim, the minimum unit size of the hidden layer of the input q/k/v tensor and the output attn_out. |
Parameter Group Constraints
Common Parameter Group
Handling of empty input parameters:
- An empty tensor means that the shape size of the required input and output is 0, that is, any axis is 0.
- Use cases that trigger an empty tensor are all intercepted and reported as errors.
q, k, v, attn_out validation
| Parameter | Single-Parameter Validation | Existence Validation | Consistency Validation | Feature Cross-Validation |
|---|---|---|---|---|
| q |
|
Must exist. |
|
Axis validation:
|
| k |
|
|||
| v | ||||
| attn_out |
|
Layout matching relationship table:
| layout_q | layout_kv | layout_out | layout_softmax_lse |
|---|---|---|---|
| BNSD | |
|
(B, Q_N, Q_S) |
| BSND | |
BSND | (B, Q_N, Q_S) |
| TND | |
TND | (Q_N, Q_T) |
metadata validation
| Parameter | Single-Parameter Validation | Existence Validation | Consistency Validation | Feature Cross-Validation |
|---|---|---|---|---|
| metadata |
|
Optional Parameter | None | When passed, it 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 value)
- 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, 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 | Not supported yet. |
SoftmaxLSE Parameter Group
| Parameter | Single-Parameter Validation | Existence Validation | Consistency Validation | Feature Cross-Validation |
|---|---|---|---|---|
| return_softmax_lse |
|
Optional attribute. Default Value: False. |
|
None |
| softmax_lse |
|
None | None |
Example
flash_attn_metadata + flash_attn joint call example (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()