评价此页

torch.nn.functional.scaled_dot_product_attention#

torch.nn.functional.scaled_dot_product_attention()#
scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0,

is_causal=False, scale=None, enable_gqa=False) -> Tensor

在查询(query)、键(key)和值(value)张量上计算缩放点积注意力(scaled dot product attention),如果传入了注意力掩码(attention mask),则使用该掩码,并在指定了大于0.0的概率时应用dropout。可选的scale参数只能作为关键字参数传入。

# Efficient implementation equivalent to the following:
def scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0,
        is_causal=False, scale=None, enable_gqa=False) -> torch.Tensor:
    L, S = query.size(-2), key.size(-2)
    scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale
    attn_bias = torch.zeros(L, S, dtype=query.dtype, device=query.device)
    if is_causal:
        assert attn_mask is None
        temp_mask = torch.ones(L, S, dtype=torch.bool).tril(diagonal=0)
        attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
        attn_bias.to(query.dtype)

    if attn_mask is not None:
        if attn_mask.dtype == torch.bool:
            attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
        else:
            attn_bias = attn_mask + attn_bias

    if enable_gqa:
        key = key.repeat_interleave(query.size(-3)//key.size(-3), -3)
        value = value.repeat_interleave(query.size(-3)//value.size(-3), -3)

    attn_weight = query @ key.transpose(-2, -1) * scale_factor
    attn_weight += attn_bias
    attn_weight = torch.softmax(attn_weight, dim=-1)
    attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
    return attn_weight @ value

警告

此函数处于beta阶段,可能会发生更改。

警告

此函数始终根据指定的 dropout_p 参数应用dropout。要在评估期间禁用dropout,请确保在调用函数的模块不处于训练模式时传递 0.0 的值。

例如

class MyModel(nn.Module):
    def __init__(self, p=0.5):
        super().__init__()
        self.p = p

    def forward(self, ...):
        return F.scaled_dot_product_attention(...,
            dropout_p=(self.p if self.training else 0.0))

注意

目前支持三种缩放点积注意力的实现:

当使用CUDA后端时,该函数可能会调用优化的内核以提高性能。对于所有其他后端,将使用PyTorch实现。

所有实现均默认启用。缩放点积注意力会尝试根据输入自动选择最优的实现。为了对使用的实现进行更精细地控制,提供了以下用于启用和禁用实现的函数。上下文管理器是首选机制:

每个融合内核都有特定的输入限制。如果用户需要使用特定的融合实现,请使用 torch.nn.attention.sdpa_kernel() 禁用PyTorch C++实现。如果融合实现不可用,则会发出警告,说明原因。

由于浮点运算融合的性质,此函数的输出可能因选择的后端内核而异。C++实现支持torch.float64,在需要更高精度时可以使用。对于math后端,如果输入是torch.half或torch.bfloat16,则所有中间计算都保留为torch.float。

有关更多信息,请参阅 数值精度

Grouped Query Attention (GQA) 是一项实验性功能。目前它仅适用于CUDA张量上的FlashAttention和math内核,不支持Nested tensor。GQA的约束条件:

  • number_of_heads_query % number_of_heads_key_value == 0 且,

  • number_of_heads_key == number_of_heads_value

注意

在某些情况下,当在CUDA设备上使用CuDNN时,此运算符可能会选择非确定性算法以提高性能。如果这不可取,您可以通过设置 torch.backends.cudnn.deterministic = True 来尝试使操作确定化(可能会牺牲性能)。有关更多信息,请参阅 可复现性

参数
  • query ( Tensor ) – 查询张量;形状为 (N,...,Hq,L,E)(N, ..., Hq, L, E)

  • key ( Tensor ) – 键张量;形状为 (N,...,H,S,E)(N, ..., H, S, E)

  • value ( Tensor ) – 值张量;形状为 (N,...,H,S,Ev)(N, ..., H, S, Ev)

  • attn_mask (optional Tensor) – Attention mask;形状必须可广播到 attention weights 的形状,即 (N,...,L,S)(N,..., L, S)。支持两种类型的掩码。布尔掩码,其中 True 值表示该元素应该参与 attention。与 query、key、value 类型相同的浮点掩码,添加到 attention 分数中。

  • dropout_p (float) – Dropout 概率;如果大于 0.0,则应用 dropout

  • is_causal (bool) – 如果设置为 true,当掩码是方阵时,attention 掩码是一个下三角矩阵。当掩码是非方阵时,attention 掩码的形式是由于对齐而产生的左上因果偏置(参见 torch.nn.attention.bias.CausalBias)。如果同时设置了 attn_mask 和 is_causal,则会抛出错误。

  • scale (optional python:float, keyword-only) – Softmax 之前应用的缩放因子。如果为 None,则默认值为 1E\frac{1}{\sqrt{E}}

  • enable_gqa (bool) – 如果设置为 True,则启用分组查询注意力 (GQA),默认设置为 False。

返回

Attention output;形状 (N,...,Hq,L,Ev)(N, ..., Hq, L, Ev)

返回类型

output (Tensor)

形状图例
  • N:Batch size...:Any number of other batch dimensions (optional)N: \text{Batch size} ... : \text{Any number of other batch dimensions (optional)}

  • S:Source sequence lengthS: \text{Source sequence length}

  • L:Target sequence lengthL: \text{Target sequence length}

  • E:Embedding dimension of the query and keyE: \text{Embedding dimension of the query and key}

  • Ev:Embedding dimension of the valueEv: \text{Embedding dimension of the value}

  • Hq:Number of heads of queryHq: \text{Number of heads of query}

  • H:Number of heads of key and valueH: \text{Number of heads of key and value}

示例

>>> # Optionally use the context manager to ensure one of the fused kernels is run
>>> query = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
>>> key = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
>>> value = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
>>> with sdpa_kernel(backends=[SDPBackend.FLASH_ATTENTION]):
>>>     F.scaled_dot_product_attention(query,key,value)
>>> # Sample for GQA for llama3
>>> query = torch.rand(32, 32, 128, 64, dtype=torch.float16, device="cuda")
>>> key = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
>>> value = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
>>> with sdpa_kernel(backends=[SDPBackend.MATH]):
>>>     F.scaled_dot_product_attention(query,key,value,enable_gqa=True)