Skip to content
29 changes: 29 additions & 0 deletions src/transformers/integrations/flex_attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,26 @@ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)


def create_packed_block_mask(
cu_seq_lens_q: torch.Tensor, cu_seq_lens_k: torch.Tensor | None, q_length: int, kv_length: int
) -> "BlockMask":
"""Block mask letting each sequence packed along the length attend to itself only, from their cumulative lengths.
Blocks across sequences are skipped, and the mask is built block by block, never densely."""
cu_seq_lens_k = cu_seq_lens_q if cu_seq_lens_k is None else cu_seq_lens_k
device = cu_seq_lens_q.device
q_sequence = torch.searchsorted(cu_seq_lens_q[1:], torch.arange(q_length, device=device), right=True)
kv_sequence = torch.searchsorted(cu_seq_lens_k[1:], torch.arange(kv_length, device=device), right=True)
return create_block_mask(
lambda batch_idx, head_idx, q_idx, kv_idx: q_sequence[q_idx] == kv_sequence[kv_idx],
None,
None,
q_length,
kv_length,
device=device,
_compile=True,
)


def flex_attention_forward(
module: torch.nn.Module,
query: torch.Tensor,
Expand All @@ -273,6 +293,15 @@ def flex_attention_forward(
" only (`model.eval()`) or turn off the attention dropout in the respective config."
)

# Sequences packed along the length, delimited by `cu_seq_lens_q` rather than by a mask: use the block mask the
# model built once for all its layers, or build one for this call
if (cu_seq_lens_q := kwargs.get("cu_seq_lens_q")) is not None and attention_mask is None:
attention_mask = kwargs.get("packed_block_mask")
if attention_mask is None:
attention_mask = create_packed_block_mask(
cu_seq_lens_q, kwargs.get("cu_seq_lens_k"), query.shape[2], key.shape[2]
)

block_mask = None
score_mask = None
if isinstance(attention_mask, BlockMask):
Expand Down
149 changes: 149 additions & 0 deletions src/transformers/integrations/sdpa_attention.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
from collections.abc import Callable

import torch

Expand Down Expand Up @@ -91,6 +92,144 @@ def create_position_bias_mask(
return position_bias_mask.contiguous()


def sdpa_packed_sequences_attention_forward(
module: torch.nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
cu_seq_lens_q: torch.Tensor,
cu_seq_lens_k: torch.Tensor | None = None,
is_causal: bool | None = None,
sliding_window: int | None = None,
sequence_lengths: list[int] | None = None,
**kwargs,
) -> tuple[torch.Tensor, None]:
"""
SDPA over sequences packed along the length, `(batch, heads, length, head_dim)`, delimited by `cu_seq_lens_q` (and
`cu_seq_lens_k`) over the flattened batch: one call per sequence, instead of a dense mask over the whole rows.
"""
batch_size, num_heads, _, head_dim = query.shape
cu_seq_lens_k = cu_seq_lens_q if cu_seq_lens_k is None else cu_seq_lens_k
is_causal = is_causal if is_causal is not None else getattr(module, "is_causal", True)
# One packed row of all the sequences: a view for a batch of one
query, key, value = (states.transpose(0, 1).flatten(1, 2)[None] for states in (query, key, value))
# The varlen kwargs of flash attention, unused here
for name in ("max_length_q", "max_length_k", "packed_block_mask"):
kwargs.pop(name, None)
attn_output, _ = per_sequence_attention_forward(
sdpa_attention_forward,
module,
query,
key,
value,
cu_seq_lens_q,
cu_seq_lens_k,
sequence_lengths=sequence_lengths,
is_causal=is_causal,
sliding_window=sliding_window,
**kwargs,
)
return attn_output.view(batch_size, -1, num_heads, head_dim), None


def per_sequence_attention_forward(
attention_fn: Callable,
module: torch.nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
cu_seq_lens_q: torch.Tensor,
cu_seq_lens_k: torch.Tensor,
sequence_lengths: list[int] | None = None,
is_causal: bool = True,
sliding_window: int | None = None,
causal_needs_mask: bool = False,
return_attention_weights: bool = False,
**kwargs,
) -> tuple[torch.Tensor, list[torch.Tensor] | None]:
"""
Calls `attention_fn` on each of the sequences packed along the length of a batch of one, with a mask only where
the attention needs it: a (causal) window narrower than the sequence, or causal attention itself when
`causal_needs_mask` (eager has no causal flag). Returns the outputs concatenated along the length, `(1, length,
heads, head_dim)`, and each sequence's weights if `return_attention_weights` (otherwise freed as it goes).
"""
# Splitting needs the lengths on the host: read once per forward when the model passes them (shared by queries
# and keys), here otherwise
if sequence_lengths is not None:
lengths_q = lengths_k = sequence_lengths
else:
lengths_q = (cu_seq_lens_q[1:] - cu_seq_lens_q[:-1]).tolist()
lengths_k = (cu_seq_lens_k[1:] - cu_seq_lens_k[:-1]).tolist()
attn_outputs, attn_weights = [], []
for q, k, v in zip(query.split(lengths_q, dim=2), key.split(lengths_k, dim=2), value.split(lengths_k, dim=2)):
mask = None
if (is_causal and causal_needs_mask) or (sliding_window is not None and k.shape[2] > sliding_window):
visible = torch.ones(q.shape[2], k.shape[2], dtype=torch.bool, device=q.device)
visible = visible.tril() if is_causal else visible
visible = visible.triu(1 - sliding_window) if sliding_window is not None else visible
mask = torch.zeros(visible.shape, dtype=q.dtype, device=q.device)
mask = mask.masked_fill(~visible, torch.finfo(q.dtype).min)[None, None]
attn_output, weights = attention_fn(module, q, k, v, mask, is_causal=is_causal, **kwargs)
attn_outputs.append(attn_output)
if return_attention_weights:
attn_weights.append(weights)
del weights
return torch.cat(attn_outputs, dim=1), attn_weights if return_attention_weights else None


def eager_packed_sequences_attention_forward(
eager_attention_forward: Callable,
module: torch.nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: torch.Tensor | None,
sliding_window: int | None = None,
**kwargs,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""
A model's `eager_attention_forward`, attending over each sequence of packed rows separately when the mask is their
cumulative lengths over the flattened batch (from `create_causal_mask`): small per-sequence masks instead of a
dense one over the whole rows. The weights are block-diagonal, kept only when attentions are recorded.
"""
if attention_mask is None or attention_mask.ndim != 1:
return eager_attention_forward(
module, query, key, value, attention_mask, sliding_window=sliding_window, **kwargs
)
batch_size, num_heads, length, head_dim = query.shape
is_causal = kwargs.pop("is_causal", None)
is_causal = is_causal if is_causal is not None else getattr(module, "is_causal", True)
record_attentions = kwargs.get(
"output_attentions", getattr(getattr(module, "config", None), "output_attentions", False)
)
# One packed row of all the sequences: a view for a batch of one
query, key, value = (states.transpose(0, 1).flatten(1, 2)[None] for states in (query, key, value))
attn_output, sequence_weights = per_sequence_attention_forward(
eager_attention_forward,
module,
query,
key,
value,
attention_mask,
attention_mask,
is_causal=is_causal,
sliding_window=sliding_window,
causal_needs_mask=True,
return_attention_weights=record_attentions,
**kwargs,
)
attn_weights = None
if sequence_weights is not None:
attn_weights = query.new_zeros(batch_size, num_heads, length, length)
start = 0
for weights in sequence_weights:
row, offset = divmod(start, length)
end = offset + weights.shape[-1]
attn_weights[row, :, offset:end, offset:end] = weights[0]
start += weights.shape[-1]
return attn_output.view(batch_size, length, num_heads, head_dim), attn_weights


def sdpa_attention_forward(
module: torch.nn.Module,
query: torch.Tensor,
Expand All @@ -113,6 +252,16 @@ def sdpa_attention_forward(
" Please set your attention to `eager` if you want any of these features."
)

# Sequences packed along the length, delimited by their cumulative lengths rather than by a mask: passed as the mask
# itself, 1D, for packed text rows (`create_causal_mask`), or as `cu_seq_lens_q` (packed encoders)
if attention_mask is not None and attention_mask.ndim == 1:
kwargs["cu_seq_lens_q"] = kwargs["cu_seq_lens_k"] = attention_mask
attention_mask = None
if kwargs.get("cu_seq_lens_q") is not None and attention_mask is None:
return sdpa_packed_sequences_attention_forward(
module, query, key, value, dropout=dropout, scaling=scaling, is_causal=is_causal, **kwargs
)

sdpa_kwargs = {}
q_length = query.shape[2]
if hasattr(module, "num_key_value_groups") and module.num_key_value_groups > 1:
Expand Down
51 changes: 49 additions & 2 deletions src/transformers/masking_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,7 @@ class AttentionMaskInterface(GeneralInterface):
"flash_attention_2": flash_attention_mask,
"flash_attention_3": flash_attention_mask,
"flash_attention_4": flash_attention_mask,
"flash_attention_torch": flash_attention_mask,
"flex_attention": flex_attention_mask,
}

Expand Down Expand Up @@ -764,6 +765,35 @@ def find_packed_sequence_indices(position_ids: torch.Tensor) -> torch.Tensor | N
return packed_sequence_mask


def packed_sequences_cu_seq_lens(
config: PreTrainedConfig,
packed_sequence_mask: torch.Tensor | None,
needs_dense_mask: bool,
) -> torch.Tensor | None:
"""
Packed rows are attended over by SDPA's varlen kernel, and by eager one sequence at a time, which take the
cumulative lengths of the sequences over the flattened batch instead of a dense mask. Returns them, or `None` when
the dense mask is needed.

The attention layers pass their own `sliding_window`, as for flash attention.
"""
if (
packed_sequence_mask is None
or config._attn_implementation not in ("sdpa", "eager")
or needs_dense_mask
# Sparse-attention indexers (`index_topk`) select their keys on the dense mask
or getattr(config, "index_topk", None) is not None
# The number of sequences is data-dependent
or is_tracing(packed_sequence_mask)
):
return None
# Sequence ids continue from one row to the next
sequences_per_row = packed_sequence_mask[:, -1] + 1
row_offsets = F.pad(sequences_per_row.cumsum(0)[:-1], (1, 0))
sequence_ids = (packed_sequence_mask + row_offsets[:, None]).flatten()
return F.pad(torch.bincount(sequence_ids).cumsum(0), (1, 0)).to(torch.int32)


def _preprocess_mask_arguments(
config: PreTrainedConfig,
inputs_embeds: torch.Tensor,
Expand Down Expand Up @@ -814,8 +844,9 @@ def _preprocess_mask_arguments(
kv_offset (`int`):
An offset to indicate at which first position the key and values states will refer to.
"""
# If the mask is already 4D, simply return as-is (it was already prepared, or it is custom)
if isinstance(attention_mask, (torch.Tensor, BlockMask)) and len(attention_mask.shape) == 4:
# If the mask is already 4D, simply return as-is (it was already prepared, or it is custom). So are the 1D
# cumulative lengths of packed rows (`packed_sequences_cu_seq_lens`), already prepared too
if isinstance(attention_mask, (torch.Tensor, BlockMask)) and len(attention_mask.shape) in (1, 4):
return True, attention_mask, None, None, None, None, None

# If the cache is from CB, immediate exit as well, we don't need any mask
Expand Down Expand Up @@ -962,6 +993,14 @@ def create_causal_mask(
if early_exit:
return attention_mask

# A mask the caller needs materialized, or that combines other masks, stays dense
needs_dense_mask = not allow_is_causal_skip or any(
overlay is not None for overlay in (or_mask_function, and_mask_function, block_sequence_ids)
)
cu_seq_lens = packed_sequences_cu_seq_lens(config, packed_sequence_mask, needs_dense_mask)
if cu_seq_lens is not None:
return cu_seq_lens

batch_size, dtype, device = inputs_embeds.shape[0], inputs_embeds.dtype, inputs_embeds.device
mask_factory_function = causal_mask_function
mask_interface = ALL_MASK_ATTENTION_FUNCTIONS[config._attn_implementation]
Expand Down Expand Up @@ -1193,6 +1232,14 @@ def create_sliding_window_causal_mask(
if early_exit:
return attention_mask

# A mask the caller needs materialized, or that combines other masks, stays dense
needs_dense_mask = not allow_is_causal_skip or any(
overlay is not None for overlay in (or_mask_function, and_mask_function, block_sequence_ids)
)
cu_seq_lens = packed_sequences_cu_seq_lens(config, packed_sequence_mask, needs_dense_mask)
if cu_seq_lens is not None:
return cu_seq_lens

sliding_window = getattr(config, "sliding_window", None)
if sliding_window is None:
raise ValueError("Could not find a `sliding_window` argument in the config, or it is not set")
Expand Down
73 changes: 72 additions & 1 deletion src/transformers/modeling_flash_attention_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ def is_flash_attn_available(kernels_fallback_ok=False):
"flash_attention_4": "kernels-community/flash-attn4",
}

# Torch's varlen attention gained `scale` and `window_size` in 2.11, and GQA in 2.12
_is_torch_greater_or_equal_than_2_11 = is_torch_greater_or_equal("2.11", accept_dev=True)
_is_torch_greater_or_equal_than_2_12 = is_torch_greater_or_equal("2.12", accept_dev=True)

FLASH_ATTN_KERNEL_VERSIONS = {
# v4 was only tested on 2.10 and upwards
"kernels-community/flash-attn2": 4 if is_torch_greater_or_equal("2.10", accept_dev=True) else 3,
Expand Down Expand Up @@ -143,6 +147,13 @@ def is_flash_attn_available(kernels_fallback_ok=False):
"supported_devices": ((is_torch_cuda_available, "cuda"),),
"cuda_min_major_version": 9, # Hopper
},
# Torch's native varlen attention, the Flash Attention kernel built into torch
"torch": {
"flash_attn_version": "torch",
"general_availability_check": lambda: _is_torch_greater_or_equal_than_2_11 and is_torch_cuda_available(),
"pkg_availability_check": lambda *args, **kwargs: _is_torch_greater_or_equal_than_2_11,
"supported_devices": ((is_torch_cuda_available, "cuda"),),
},
}


Expand All @@ -166,6 +177,62 @@ def is_flash_attn_available(kernels_fallback_ok=False):
_flash_api_alternative_names = {"s_aux": "learnable_sink", "block_table": "page_table"}


def _torch_flash_attn_varlen_func(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
dropout_p: float = 0.0,
softmax_scale: float | None = None,
causal: bool = False,
window_size: tuple[int, int] = (-1, -1),
s_aux: torch.Tensor | None = None,
) -> torch.Tensor:
"""`flash_attn_varlen_func` on torch's native varlen attention, for `flash_attention_torch`."""
if dropout_p != 0.0 or s_aux is not None:
raise ValueError(
"`flash_attention_torch` supports neither attention dropout nor attention sinks. Try using another "
"attention implementation, or turn off the dropout (e.g. with `model.eval()`)."
)
from torch.nn.attention.varlen import varlen_attn

varlen_kwargs = {}
if q.shape[1] != k.shape[1]:
if _is_torch_greater_or_equal_than_2_12:
varlen_kwargs["enable_gqa"] = True
else:
k = k.repeat_interleave(q.shape[1] // k.shape[1], dim=1)
v = v.repeat_interleave(q.shape[1] // v.shape[1], dim=1)
# Torch has no causal flag: causal attention is a window without keys on the right
window_size = (window_size[0], 0) if causal else window_size
return varlen_attn(
q,
k,
v,
cu_seqlens_q.to(torch.int32),
cu_seqlens_k.to(torch.int32),
max_seqlen_q,
max_seqlen_k,
scale=softmax_scale,
window_size=window_size,
**varlen_kwargs,
)


def _torch_flash_attn_func(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, **kwargs) -> torch.Tensor:
"""`flash_attn_func` on torch's native varlen attention, for `flash_attention_torch`: the batch as sequences of
the same length."""
batch_size, q_length, k_length = q.shape[0], q.shape[1], k.shape[1]
cu_seqlens_q = torch.arange(0, (batch_size + 1) * q_length, q_length, dtype=torch.int32, device=q.device)
cu_seqlens_k = torch.arange(0, (batch_size + 1) * k_length, k_length, dtype=torch.int32, device=q.device)
q, k, v = (states.flatten(0, 1) for states in (q, k, v))
out = _torch_flash_attn_varlen_func(q, k, v, cu_seqlens_q, cu_seqlens_k, q_length, k_length, **kwargs)
return out.view(batch_size, q_length, *out.shape[1:])


def _lazy_imports(
implementation: str | None, attention_wrapper: Callable | None = None, allow_all_kernels: bool = False
) -> tuple[Callable, Callable, Callable, Callable, Callable]:
Expand All @@ -187,8 +254,12 @@ def _lazy_imports(

pad_input, unpad_input = _pad_input, _unpad_input

if implementation == "flash_attention_torch":
flash_attn_func, flash_attn_varlen_func = _torch_flash_attn_func, _torch_flash_attn_varlen_func
flash_attn_with_kvcache = None # not supported yet

# If we are on NPU, use the NPU-specific flash functions. No need to check other branches, is_fa is False on NPU
if is_torch_npu_available():
elif is_torch_npu_available():
# Package `flash-attn` is unavailable on Ascend NPU, which will cause ImportError
# Flash-Attention2 related apis for Ascend NPU must be imported from `.integrations.npu_flash_attention` module
from .integrations.npu_flash_attention import npu_flash_attn_func as flash_attn_func
Expand Down
Loading
Loading