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_attn is a cann_ops_transformer extension API based on TorchNPU. It calls the FlashAttn operator to perform non-quantized attention computation with shared KV (Key and Value use the same input), unifying training and inference.

    flash_attn_metadata is the metadata generation API of flash_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:

    1. Prepare inputs such as q, k, and v.
    2. Call flash_attn_metadata to generate metadata.
    3. Call flash_attn and pass the metadata obtained in the previous step to the main operator.
  • 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
) -> Tensor
cann_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

NameTypeRequired/OptionalDescriptionData TypeData FormatDimensions
num_heads_qintRequiredNumber of Query heads.int32--
num_heads_kvintRequiredNumber of Key/Value heads.int32--
head_dimintRequiredDimension of each attention head.int32--
cu_seqlens_qTensorOptionalCumulative sequence length, used to process variable-length sequences. The first element must be 0int32ND(B+1,)
cu_seqlens_kvTensorOptionalCumulative sequence length, used to process variable-length sequences. The first element must be 0int32ND(B+1,)
seqused_qTensorOptionalSpecifies the actual sequence length used in each batch to truncate redundant computation.int32ND(B,)
seqused_kvTensorOptionalSpecifies the actual sequence length used in each batch to truncate redundant computation.int32ND(B,)
batch_sizeintOptionalBatch size. Derived from cu_seqlens_q or seqused_q if not passed. The default value is None.int32--
max_seqlen_qintOptionalUpper limit of the sequence length of query q.int32--
max_seqlen_kvintOptionalUpper limit of the sequence length of key k and value v.int32--
mask_modeintOptionalMask mode.int32--
win_leftintOptionalLeft boundary of the window.int32--
win_rightintOptionalRight boundary of the window.int32--
layout_qstringOptionalDefines the layout format of the input q tensor.string--
layout_kvstringOptionalDefines the layout format of the input k and v tensors.string--
layout_outstringOptionalDefines the layout format of the output tensor.string--

flash_attn

NameTypeRequired/OptionalDescriptionData TypeData FormatDimension
qTensorRequiredq in the formulabfloat16/float16ND
  • (B, Q_S, Q_N, D)
  • (B, Q_N, Q_S, D)
  • (Q_T, Q_N, D)
kTensorRequiredk in the formulabfloat16/float16ND
  • (B, KV_S, KV_N, D)
  • (B, KV_N, KV_S, D)
  • (KV_T, KV_N, D)
  • (num_blocks, block_size, KV_N, D)
  • (num_blocks, KV_N, block_size, D)
vTensorRequiredv in the formulabfloat16/float16ND
  • (B, KV_S, KV_N, D)
  • (B, KV_N, KV_S, D)
  • (KV_T, KV_N, D)
  • (num_blocks, block_size, KV_N, D)
  • (num_blocks, KV_N, block_size, D)
block_tableTensorOptionalBlock index mapping in block-wise attention computation.int32ND(B, max_num_blocks_per_seq)
cu_seqlens_qTensorOptionalCumulative sequence length, used to process variable-length sequences. The first element must be 0int32ND(B+1,)
cu_seqlens_kvTensorOptionalCumulative sequence length, used to process variable-length sequences. The first element must be 0int32ND(B+1,)
seqused_qTensorOptionalSpecifies the actual sequence length used in each batch to truncate redundant computation.int32ND(B,)
seqused_kvTensorOptionalSpecifies the actual sequence length used in each batch to truncate redundant computation.int32ND(B,)
sinksTensorOptionalAttention sink parameter used to improve the numerical stability of self-attention computation.float32ND(Q_N,)
metadataTensorOptionalTask splitting result generated by flash_attn_metadata. Passing it in optimizes scheduling.int32ND(max_schedule_size,)
softmax_scalefloatOptionalScaling factor that can be explicitly set to override the default computation.float32--
mask_modeintOptionalMask mode.int32--
attn_maskTensorOptionalMask matrix.int8ND(2048, 2048)
win_leftintOptionalLeft boundary of the window.int32--
win_rightintOptionalRight boundary of the window.int32--
max_seqlen_qintOptionalUpper limit of the sequence length of query q.int32--
max_seqlen_kvintOptionalUpper limit of the sequence length of key k and value v.int32--
layout_qstringOptionalDefines the layout format of the input q tensor.string--
layout_kvstringOptionalDefines the layout format of the input k and v tensors.string--
layout_outstringOptionalDefines the layout format of the output tensor.string--
return_softmax_lseboolOptionalWhether to obtain the LSE result of softmax.bool--

Return Values

flash_attn_metadata

NameTypeRequired/OptionalDescriptionData TypeData FormatDimensions
metadataTensorRequiredTask splitting data of flash_attn.int32NDShape is dynamically calculated based on batch_size and num_heads_kv.

flash_attn

NameTypeRequired/OptionalDescriptionData TypeData FormatDimension
attn_outTensorRequiredComputation output of flash_attn.bfloat16/float16ND
  • (B, Q_S, Q_N, D)
  • (B, Q_N, Q_S, D)
  • (Q_T, Q_N, D )
softmax_lseTensorOptionalLSE result of softmax.float32ND
  • (B, Q_N, Q_S)
  • (Q_N, Q_T)

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 GroupParameter Field NameField GroupingField Type
Common Parameter GroupqINPUTTensor
kINPUTTensor
vINPUTTensor
metadataINPUT(OPTIONAL)Tensor
softmax_scaleATTR(OPTIONAL)float
layout_qATTR(OPTIONAL)string
layout_kvATTR(OPTIONAL)string
layout_outATTR(OPTIONAL)string
attn_outOUTPUTTensor
Mask Parameter Groupmask_modeATTR(OPTIONAL)int
win_leftATTR(OPTIONAL)int
win_rightATTR(OPTIONAL)int
attn_maskINPUT(OPTIONAL)Tensor
SeqLens Parameter Groupcu_seqlens_qINPUT(OPTIONAL)Tensor
cu_seqlens_kvINPUT(OPTIONAL)Tensor
seqused_qINPUT(OPTIONAL)Tensor
seqused_kvINPUT(OPTIONAL)Tensor
max_seqlen_qATTR(OPTIONAL)int
max_seqlen_kvATTR(OPTIONAL)int
Paged Attention Parameter Groupblock_tableINPUT(OPTIONAL)Tensor
Sinks Parameter GroupsinksINPUT(OPTIONAL)Tensor
SoftmaxLSE Parameter Groupreturn_softmax_lseATTR(OPTIONAL)bool
softmax_lseOUTPUTTensor

Baseline Information

Common fields in the documentation constraints are defined as follows:

NameMeaning
BBatch, indicating the batch size of input samples.
Q_NNumber of heads of the input q tensor, corresponding to N in the q shape.
KV_NNumber of heads of the input k/v tensor, corresponding to N in the k/v shape.
Q_SSequence length of the input q tensor, corresponding to S in the q shape.
KV_SSequence length of the input k/v tensor, corresponding to S in the k/v shape.
Q_TCumulative sum of sequence lengths of all batches in the input q tensor.
KV_TCumulative sum of sequence lengths of all batches in the input k/v tensor.
DMinimum 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
  • data_type supports INT
  • Only 0, 3, and 4 are supported as input. The default value is 0.
Optional input. If this parameter is not passed in, the default value is 0.
  • When mask_mode is 0, win_left and win_right must be -1, and passing in attn_mask is not supported.
  • When mask_mode is 3, win_left and win_right must be -1, and the attn_mask matrix must be passed in.
  • When mask_mode is 4, the attn_mask matrix must be passed in.
  • None
attn_mask
  • tensor_type supports int8
  • tensor_shape dimension is (2048, 2048). The matrix is fixed as a 2048*2048 lower triangular matrix with all 0s on the diagonal.
None
win_left
  • data_type supports INT
  • If this parameter is not passed in or is set to -1, the value is positive infinity.
  • The value must be >= -1.
win_right

SeqLengths parameter group

Parameter Single-Parameter Validation Existence Validation Consistency Validation Feature Cross-Validation
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_kv must be less than or equal to KV_S.
Optional parameter None None
seqused_kv
cu_seqlens_q
  • tensor_type supports int32.
  • tensor_shape is (B+1,).
  • Only non-negative integers are supported.
  • Values must be non-decreasing (greater than or equal to the previous value).
  • cu_seqlens_q: the first element is 0 and the last element equals Q_T.
  • cu_seqlens_kv: the first element is 0 and the last element equals KV_T.
  • When layout_q is TND, cu_seqlens_q must be passed in.
  • When layout_q is not TND, passing in cu_seqlens_q is not supported.
  • When layout_kv is TND, cu_seqlens_kv must be passed in.
  • When layout_kv is not TND, passing in cu_seqlens_kv is not supported.
cu_seqlens_kv
max_seqlen_q
  • data_type supports INT.
  • The default value is -1.
  • Optional parameter.
  • The value must be greater than or equal to -1. When passed in, the value must equal the actual maximum sequence length. Otherwise, the behavior is undefined.
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
  • tensor_type only supports int32.
  • tensor_shape is (B, max_num_blocks_per_seq).
  • Values must be positive integers.
  • 1024 >= block_size >= 16, block_size % 16 == 0.
Optional parameter None
  • If PagedAttention is enabled, seqused_kv must be passed in.
  • If PagedAttention is enabled, block_table must not be empty.

Sinks Parameter Group

Parameter Single-Parameter Validation Existence Validation Consistency Validation Feature Cross-Validation
sinks
  • Currently not supported.
Optional parameter None Currently not supported.

SoftmaxLSE Parameter Group

Parameter Single-Parameter Validation Existence Validation Consistency Validation Feature Cross-Validation
return_softmax_lse
  • data_type only supports BOOL.
  • The value only supports True and False. True indicates that softmax_lse is enabled, and False indicates that softmax_lse is disabled.
Optional attribute. The default value is False.
  • If return_softmax_lse is False, the output is a Tensor with shape [1] and value 0.
  • If return_softmax_lse is True, the output shape is described in the layout matching relationship table.
None
softmax_lse
  • data_type only supports float32
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()