PyTorch——自注意力(self-attention)机制实现(代码详解)

参考链接

  1. https://www.bilibili.com/video/BV1JE411g7XF?p=54
  2. https://arxiv.org/abs/1706.03762
  3. https://blog.csdn.net/qq_36653505/article/details/83375160

简述自注意力机制(self-attention)

self-attention可以视为一个特征提取层,给定输入特征 a 1 , a 2 , ⋅ ⋅ ⋅ a n a^{1},a^{2},\cdot \cdot \cdot a^{n} a1,a2,an,经过self-attention layer,融合每个输入特征,得到新的特征 b 1 , b 2 , ⋅ ⋅ ⋅ b n b^{1},b^{2},\cdot \cdot \cdot b^{n} b1,b2,bn。具体如下:

设输入特征为 I I I,分别将其乘以三个矩阵 W q W^{q} Wq W k W^{k} Wk W v W^{v} Wv得到 Q Q Q(query)、 K K K(key)和 V V V(value)三个矩阵;接下来使用矩阵 Q Q Q K K K的乘积得到注意力矩阵 A A A,归一化得到 A ^ \hat{A} A^;最后,将归一化后的注意力矩阵 A ^ \hat{A} A^乘上 V V V,得到最后的输出特征 O O O
在这里插入图片描述

多头自注意力机制(multi-head self-attention)

上述的self-attention中,每个输入特征 a i a^{i} ai乘上矩阵 W q W^{q} Wq W k W^{k} Wk W v W^{v} Wv后,分别得到一个向量 q i q^{i} qi k i k^{i} ki v i v^{i} vi,称为单头自注意力机制。如果将这些向量 q i q^{i} qi k i k^{i} ki v i v^{i} vi分裂为 n n n个就得到 n n n头自注意力机制了。公认多头自注意力机制的效果好于单头的,因为前者可以捕获更多维度的信息。示意图如下:
在这里插入图片描述

代码实现

设超参数num_attention_heads为自注意力机制的头数,如此,计算出每个头的维度attention_head_size。

self.num_attention_heads = num_attention_heads
self.attention_head_size = int(hidden_size / num_attention_heads)
self.all_head_size = hidden_size

定义 W q W^{q} Wq W k W^{k} Wk W v W^{v} Wv三个矩阵。

self.query = nn.Linear(input_size, self.all_head_size)
self.key = nn.Linear(input_size, self.all_head_size)
self.value = nn.Linear(input_size, self.all_head_size)

下面开始逐步计算,需要主要的是计算过程中张量维度的变化。
将输入特征乘以三个矩阵 W q W^{q} Wq W k W^{k} Wk W v W^{v} Wv,输出的张量此时还没有区分出多个头。维度变化为:input_tensor ( b a t c h , n , i n p u t _ s i z e ) \left ( batch,n,input\_size\right ) (batch,n,input_size)到mixed_query_layer ( b a t c h , n , a l l _ h e a d _ s i z e ) \left ( batch,n,all\_head\_size\right ) (batch,n,all_head_size)

mixed_query_layer = self.query(input_tensor)
mixed_key_layer = self.key(input_tensor)
mixed_value_layer = self.value(input_tensor)

切分为num_attention_heads个头,并变换维度。维度变化为:mixed_query_layer ( b a t c h , n , a l l _ h e a d _ s i z e ) \left ( batch,n,all\_head\_size\right ) (batch,n,all_head_size)到query_layer ( b a t c h , n u m _ a t t e n t i o n _ h e a d s , n , a t t e n t i o n _ h e a d _ s i z e ) \left ( batch,num\_attention\_heads,n,attention\_head\_size\right ) (batch,num_attention_heads,n,attention_head_size)

def transpose_for_scores(self, x):
   new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
   x = x.view(*new_x_shape)
   return x.permute(0, 2, 1, 3)

query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)

矩阵 Q Q Q K K K相乘,得到注意力矩阵,并除以向量的维度的开方,防止注意力分数随维度增大而增大。维度变化为:query_layer ( b a t c h , n u m _ a t t e n t i o n _ h e a d s , n , a t t e n t i o n _ h e a d _ s i z e ) \left ( batch,num\_attention\_heads,n,attention\_head\_size\right ) (batch,num_attention_heads,n,attention_head_size)到attention_scores ( b a t c h , n u m _ a t t e n t i o n _ h e a d s , n , n ) \left ( batch,num\_attention\_heads,n,n\right ) (batch,num_attention_heads,n,n)

attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))

attention_scores = attention_scores / math.sqrt(self.attention_head_size)

注意力矩阵归一化。维度变化为:attention_scores ( b a t c h , n u m _ a t t e n t i o n _ h e a d s , n , n ) \left ( batch,num\_attention\_heads,n,n\right ) (batch,num_attention_heads,n,n)到attention_probs ( b a t c h , n u m _ a t t e n t i o n _ h e a d s , n , n ) \left ( batch,num\_attention\_heads,n,n\right ) (batch,num_attention_heads,n,n)

attention_probs = nn.Softmax(dim=-1)(attention_scores)

将注意力矩阵乘以矩阵 V V V。维度变化为:ttention_probs ( b a t c h , n u m _ a t t e n t i o n _ h e a d s , n , n ) \left ( batch,num\_attention\_heads,n,n\right ) (batch,num_attention_heads,n,n)乘以value_layer ( b a t c h , n u m _ a t t e n t i o n _ h e a d s , n , a t t e n t i o n _ h e a d _ s i z e ) \left ( batch,num\_attention\_heads,n,attention\_head\_size\right ) (batch,num_attention_heads,n,attention_head_size)到context_layer ( b a t c h , n u m _ a t t e n t i o n _ h e a d s , n , a t t e n t i o n _ h e a d _ s i z e ) \left ( batch,num\_attention\_heads,n,attention\_head\_size\right ) (batch,num_attention_heads,n,attention_head_size)

context_layer = torch.matmul(attention_probs, value_layer)

变换context_layer维度,为了后面将各头得到的结果拼接。这里的contiguous()是将tensor的内存变成连续的,为后面的view()做准备。维度变化为:context_layer ( b a t c h , n u m _ a t t e n t i o n _ h e a d s , n , a t t e n t i o n _ h e a d _ s i z e ) \left ( batch,num\_attention\_heads,n,attention\_head\_size\right ) (batch,num_attention_heads,n,attention_head_size)到context_layer ( b a t c h , n , n u m _ a t t e n t i o n _ h e a d s , a t t e n t i o n _ h e a d _ s i z e ) \left ( batch,n,num\_attention\_heads,attention\_head\_size\right ) (batch,n,num_attention_heads,attention_head_size)

context_layer = context_layer.permute(0, 2, 1, 3).contiguous()

将各头的结果拼接起来。维度变化为:context_layer ( b a t c h , n , n u m _ a t t e n t i o n _ h e a d s , a t t e n t i o n _ h e a d _ s i z e ) \left ( batch,n,num\_attention\_heads,attention\_head\_size\right ) (batch,n,num_attention_heads,attention_head_size)到context_layer ( b a t c h , n , a l l _ h e a d _ s i z e ) \left ( batch,n,all\_head\_size\right ) (batch,n,all_head_size)

new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)

完整代码

class LayerNorm(nn.Module):
    def __init__(self, hidden_size, eps=1e-12):
        """Construct a layernorm module in the TF style (epsilon inside the square root).
        """
        super(LayerNorm, self).__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        self.bias = nn.Parameter(torch.zeros(hidden_size))
        self.variance_epsilon = eps

    def forward(self, x):
        u = x.mean(-1, keepdim=True)
        s = (x - u).pow(2).mean(-1, keepdim=True)
        x = (x - u) / torch.sqrt(s + self.variance_epsilon)
        return self.weight * x + self.bias
        
class SelfAttention(nn.Module):
    def __init__(self, num_attention_heads, input_size, hidden_size, hidden_dropout_prob):
        super(SelfAttention, self).__init__()
        if hidden_size % num_attention_heads != 0:
            raise ValueError(
                "The hidden size (%d) is not a multiple of the number of attention "
                "heads (%d)" % (hidden_size, num_attention_heads))
        self.num_attention_heads = num_attention_heads
        self.attention_head_size = int(hidden_size / num_attention_heads)
        self.all_head_size = hidden_size

        self.query = nn.Linear(input_size, self.all_head_size)
        self.key = nn.Linear(input_size, self.all_head_size)
        self.value = nn.Linear(input_size, self.all_head_size)

        self.attn_dropout = nn.Dropout(attention_probs_dropout_prob)

        # 做完self-attention 做一个前馈全连接 LayerNorm 输出
        self.dense = nn.Linear(hidden_size, hidden_size)
        self.LayerNorm = LayerNorm(hidden_size, eps=1e-12)
        self.out_dropout = nn.Dropout(hidden_dropout_prob)

    def transpose_for_scores(self, x):
        new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
        x = x.view(*new_x_shape)
        return x.permute(0, 2, 1, 3)

    def forward(self, input_tensor):
        mixed_query_layer = self.query(input_tensor)
        mixed_key_layer = self.key(input_tensor)
        mixed_value_layer = self.value(input_tensor)

        query_layer = self.transpose_for_scores(mixed_query_layer)
        key_layer = self.transpose_for_scores(mixed_key_layer)
        value_layer = self.transpose_for_scores(mixed_value_layer)

        # Take the dot product between "query" and "key" to get the raw attention scores.
        attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))

        attention_scores = attention_scores / math.sqrt(self.attention_head_size)
        # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
        # [batch_size heads seq_len seq_len] scores
        # [batch_size 1 1 seq_len]

        # attention_scores = attention_scores + attention_mask

        # Normalize the attention scores to probabilities.
        attention_probs = nn.Softmax(dim=-1)(attention_scores)
        # This is actually dropping out entire tokens to attend to, which might
        # seem a bit unusual, but is taken from the original Transformer paper.
        # Fixme
        attention_probs = self.attn_dropout(attention_probs)
        context_layer = torch.matmul(attention_probs, value_layer)
        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(*new_context_layer_shape)
        hidden_states = self.dense(context_layer)
        hidden_states = self.out_dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)

        return hidden_states
  • 121
    点赞
  • 725
    收藏
    觉得还不错? 一键收藏
  • 55
    评论
### 回答1: 要将self-attention机制添加到mlp中,您可以使用PyTorch中的torch.nn.MultiheadAttention模块。这个模块可以实现self-attention机制,并且可以直接用在多层感知机(mlp)中。 首先,您需要定义一个包含多个线性层和self-attention模块的PyTorch模型。然后,您可以将输入传递给多层感知机,并将多层感知机的输出作为self-attention模块的输入。最后,将self-attention模块的输出传递给后续的层进行处理,例如输出层。 以下是一个简单的示例代码,演示如何在PyTorch中将self-attention机制添加到mlp中: ``` import torch import torch.nn as nn class MLPWithSelfAttention(nn.Module): def __init__(self, input_dim, hidden_dim, num_heads): super(MLPWithSelfAttention, self).__init__() # 定义多层感知机的线性层 self.fc1 = nn.Linear(input_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) # 定义self-attention模块 self.self_attn = nn.MultiheadAttention(hidden_dim, num_heads) # 定义输出层 self.out = nn.Linear(hidden_dim, 1) def forward(self, x): # 通过多层感知机进行前向传递 x = self.fc1(x) x = torch.relu(x) x = self.fc2(x) # 通过self-attention模块进行前向传递 x, _ = self.self_attn(x, x, x) # 通过输出层进行前向传递 x = self.out(x) return x ``` 在这个例子中,MLPWithSelfAttention类定义了一个包含两个线性层、一个self-attention模块和一个输出层的多层感知机。在forward()方法中,输入首先通过两个线性层进行处理,然后将输出传递给self-attention模块进行处理。最后,self-attention模块的输出传递给输出层进行处理,并返回模型的输出。 ### 回答2: 实现self-attention机制添加到多层感知机(MLP)中需要使用PyTorch框架。Self-attention是一种在序列数据上运行的机制,它可以提取序列内元素之间的关系。以下是一个简单的示例代码,演示了如何将self-attention添加到一个具有两个隐藏层的MLP中: 首先,需要导入PyTorch库: ``` python import torch import torch.nn as nn ``` 然后,定义一个自定义的MLP模型类,并在其中添加self-attention机制: ``` python class MLPWithSelfAttention(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(MLPWithSelfAttention, self).__init__() self.fc1 = nn.Linear(input_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.fc3 = nn.Linear(hidden_dim, output_dim) self.self_attention = nn.MultiheadAttention(hidden_dim, num_heads=1) def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) # 将隐层的输出作为query, key和value输入到self-attentionattention_output, _ = self.self_attention(x, x, x) x = torch.relu(attention_output) x = self.fc3(x) return x ``` 在这个示例中,MLP模型通过三个全连接层进行前向传播,然后将隐层输出作为query、key和value输入到了self-attention中。在self-attention层之后,我们使用ReLU激活函数进行非线性处理,并最终通过全连接层输出结果。 这就是如何将self-attention机制添加到MLP中的示例代码,通过将MLP输出作为self-attention的输入,可以提取序列数据中元素之间的关系,并增强模型的表达能力。 ### 回答3: 为了将self-attention机制添加到MLP中,我们可以使用PyTorch提供的功能和技巧。 首先,我们需要导入PyTorch和必要的模块。在导入阶段,我们需要引入`nn`,`MultiheadAttention`和`Sequential`等模块。 ```python import torch import torch.nn as nn from torch.nn import MultiheadAttention from torch.nn import Sequential ``` 然后,我们可以创建一个自定义的MLP模型,并在其中定义self-attention层。我们可以使用`Sequential`来定义MLP的结构,其中包含线性层和激活函数。 ```python class MLPWithSelfAttention(nn.Module): def __init__(self, input_size, hidden_size, num_heads): super(MLPWithSelfAttention, self).__init__() self.attention = MultiheadAttention(hidden_size, num_heads) self.mlp = Sequential( nn.Linear(input_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, hidden_size), nn.ReLU() ) def forward(self, x): attention_output, _ = self.attention(x, x, x) mlp_output = self.mlp(attention_output) return mlp_output ``` 在上面的代码中,我们在MLP模型中添加了一个self-attention层,并将其命名为`attention`。然后,我们使用`Sequential`定义了MLP的结构,其中包含两个线性层和ReLU激活函数。以`attention_output`作为输入,将其输入到MLP中,得到最终的MLP输出`mlp_output`。注意,这里的self-attention输入和输出都使用相同的变量`x`。 最后,我们可以创建一个MLPWithSelfAttention的实例,并将它传递给训练环节。 ```python input_size = 100 hidden_size = 64 num_heads = 8 model = MLPWithSelfAttention(input_size, hidden_size, num_heads) input_data = torch.randn(32, input_size) output = model(input_data) ``` 在这个例子中,我们创建了一个MLPWithSelfAttention实例,并传入输入数据,最后得到输出结果。这样,我们就成功地将self-attention机制添加到了MLP中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 55
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值