File size: 1,005 Bytes
9c890d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""Attention backend with an optional FlashAttention fast path."""

from __future__ import annotations

import torch
import torch.nn.functional as F

try:
    from flash_attn import flash_attn_func as _flash_attn_func
except ImportError:
    _flash_attn_func = None


def memory_efficient_attention(
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    *,
    dropout_p: float = 0.0,
    softmax_scale: float | None = None,
) -> torch.Tensor:
    """Apply attention to tensors shaped ``(batch, tokens, heads, dim)``."""
    if _flash_attn_func is not None and query.is_cuda:
        return _flash_attn_func(
            query,
            key,
            value,
            dropout_p=dropout_p,
            softmax_scale=softmax_scale,
        )
    output = F.scaled_dot_product_attention(
        query.transpose(1, 2),
        key.transpose(1, 2),
        value.transpose(1, 2),
        dropout_p=dropout_p,
        scale=softmax_scale,
    )
    return output.transpose(1, 2)