Cyan's Blog

Search

Search IconIcon to open search

D2L-68-Additive Attention

Last updated Apr 21, 2022 Edit Source

# 加性注意力

2022-04-21

Tags: #Attention #DeepLearning

# 通用形式

1
2
queries的形状:(batch_size,num_of_queries,query_length)
key的形状:(batch_size,num_of_key-value_pair,key_length)
 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
class AdditiveAttention(nn.Module):
    """加性注意力"""
    def __init__(self, key_size, query_size, num_hiddens, dropout, **kwargs):
        super(AdditiveAttention, self).__init__(**kwargs)
        self.W_k = nn.Linear(key_size, num_hiddens, bias=False)
        self.W_q = nn.Linear(query_size, num_hiddens, bias=False)
        self.w_v = nn.Linear(num_hiddens, 1, bias=False)
        self.dropout = nn.Dropout(dropout)

    def forward(self, queries, keys, values, valid_lens):
	    # 先和权重相乘
        queries, keys = self.W_q(queries), self.W_k(keys)
        # 在维度扩展后,
        # queries的形状:(batch_size,查询的个数,1,num_hidden)
        # key的形状:(batch_size,1,“键-值”对的个数,num_hiddens)
        # 使用广播方式进行求和
        # 现在feature的形状为: 
        # (batch_size,查询的个数,“键-值”对的个数,num_hiddens)
        features = queries.unsqueeze(2) + keys.unsqueeze(1)
        features = torch.tanh(features)
        # w_v(features)的形状为:(batch_size,查询的个数,“键-值”对的个数,1)
        # self.w_v仅有一个输出,因此从形状中移除最后那个维度。
        scores = self.w_v(features).squeeze(-1)
        # scores的形状:(batch_size,查询的个数,“键-值”对的个数)
        self.attention_weights = masked_softmax(scores, valid_lens)
        # attention_weights的形状:(batch_size,查询的个数,“键-值”对的个数)
        # values的形状:(batch_size,“键-值”对的个数,值的维度)
        return torch.bmm(self.dropout(self.attention_weights), values)
        # 返回值的形状:(batch_size,查询的个数,值的维度)
        

可视化Softmax的结果: attention_weights如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
queries, keys = torch.normal(0, 1, (2, 1, 20)), torch.ones((2, 10, 2))
# values的小批量,两个值矩阵是相同的
values = torch.arange(40, dtype=torch.float32).reshape(1, 10, 4).repeat(
    2, 1, 1)
valid_lens = torch.tensor([2, 6])

attention = AdditiveAttention(key_size=2, query_size=20, num_hiddens=8,
                              dropout=0.1)
attention.eval()
attention(queries, keys, values, valid_lens)