首页 > 其他分享 >Attention

Attention

时间:2023-09-21 17:36:58浏览次数:29  
标签:attention torch self Attention num valid size

注意力实现:

import math
import torch
from torch import nn
import matplotlib.pyplot as plt
from d2l import torch as d2l


def sequence_mask(X, valid_len, value=0):
    """在序列中屏蔽不相关的项"""
    max_len = X.size(1)
    mask = torch.arange((max_len), dtype=torch.float32,
                        device=X.device)[None, :] < valid_len[:, None]
    X[~mask] = value
    return X


def masked_softmax(x, valid_lens):
    if valid_lens is None:
        return nn.functional.softmax(x, dim=-1)
    else:
        shape = x.shape
        if valid_lens.dim() == 1:
            valid_lens = torch.repeat_interleave(valid_lens, shape[1])
        else:
            valid_lens = valid_lens.reshape(-1)

        # 最后一轴上被掩蔽的元素使用一个非常大的负值替换,从而其softmax输出为0
        x = sequence_mask(x.reshape(-1, shape[-1]), valid_lens, value=-1e6)

        return nn.functional.softmax(x.reshape(shape), dim=-1)


x = torch.ones(2, 3, 4)
print(masked_softmax(torch.rand(2, 2, 4), torch.tensor([2, 3])))


# 加性注意力:

class AdditiveAttention(nn.Module):
    """加性注意力"""

    def __init__(self, key_size, query_size, num_hidden, dropout, **kwargs):
        super(AdditiveAttention, self).__init__(**kwargs)
        self.w_k = nn.Linear(key_size, num_hidden, bias=False)
        self.w_q = nn.Linear(query_size, num_hidden, bias=False)
        self.w_v = nn.Linear(num_hidden, 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)
        features = queries.unsqueeze(2) + keys.unsqueeze(1)
        features = torch.tanh(features)
        scores = self.w_v(features).squeeze(-1)

        self.attention_weights = masked_softmax(scores, valid_lens)
        return torch.bmm(self.dropout(self.attention_weights), values)


queries, keys = torch.normal(0, 1, (2, 1, 20)), torch.ones((2, 10, 2))

print("queries:")
print(queries)
print("keys:")
print(keys)

values = torch.arange(40, dtype=torch.float32).reshape(1, 10, 4).repeat(2, 1, 1)
print("values:")
print(values)

valid_lens = torch.tensor([2, 6])

attention = AdditiveAttention(key_size=2, query_size=20, num_hidden=8,
                              dropout=0.1)

attention.eval()
print(attention(queries, keys, values, valid_lens))

d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),
                  xlabel='Keys', ylabel='Queries')
plt.show()


# 点积模型:

class DotProductAttention(nn.Module):
    def __init__(self, dropout, **kwargs):
        super(DotProductAttention, self).__init__(**kwargs)
        self.dropout = nn.Dropout(dropout)

    # queries的形状:(batch_size,查询的个数,d)
    # keys的形状:(batch_size,“键-值”对的个数,d)
    # values的形状:(batch_size,“键-值”对的个数,值的维度)
    # valid_lens的形状:(batch_size,)或者(batch_size,查询的个数)

    def forward(self, queries, keys, values, valid_lens=None):
        d = queries.shape[-1]
        scores = torch.bmm(queries, keys.transpose(1, 2) / math.sqrt(d))
        self.attention_weights = masked_softmax(scores, valid_lens)
        return torch.bmm(self.dropout(self.attention_weights), values)


queries = torch.normal(0, 1, (2, 1, 2))
attention = DotProductAttention(dropout=0.5)
attention.eval()
print(attention(queries, keys, values, valid_lens))

d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),
                  xlabel='Keys', ylabel='Queries')
plt.show()

seq2seq经过action优化之后:

import torch
from torch import nn
from d2l import torch as d2l
import matplotlib.pyplot as plt


# @save
class AttentionDecoder(d2l.Decoder):
    """带有注意力机制解码器的基本接口"""

    def __init__(self, **kwargs):
        super(AttentionDecoder, self).__init__(**kwargs)

    @property
    def attention_weights(self):
        raise NotImplementedError


class Seq2SeqAttentionDecoder(AttentionDecoder):
    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
                 dropout=0, **kwargs):
        super(Seq2SeqAttentionDecoder, self).__init__(**kwargs)
        self.attention = d2l.AdditiveAttention(num_hiddens, num_hiddens, num_hiddens, dropout)
        self.embedding = nn.Embedding(vocab_size, embed_size)
        self.rnn = nn.GRU(embed_size + num_hiddens, num_hiddens, num_layers,
                          dropout=dropout)
        self.dense = nn.Linear(num_hiddens, vocab_size)

    def init_state(self, enc_outputs, enc_valid_lens, *args):
        # outputs的形状为(batch_size,num_steps,num_hidden).
        # hidden_state的形状为(num_layers,batch_size,num_hidden)
        outputs, hidden_state = enc_outputs
        return (outputs.permute(1, 0, 2), hidden_state, enc_valid_lens)

    def forward(self, x, state):
        # enc_outputs的形状为(batch_size,num_steps,num_hidden).
        # hidden_state的形状为(num_layers,batch_size,
        # num_hidden)
        enc_outputs, hidden_state, enc_valid_lens = state
        # 输出X的形状为(num_steps,batch_size,embed_size)
        x = self.embedding(x).permute(1, 0, 2)
        outputs, self._attention_weights = [], []
        for x_ in x:
            query = torch.unsqueeze(hidden_state[-1], dim=1)  # query的形状为(batch_size,1,num_hidden)
            context = self.attention(query, enc_outputs, enc_outputs, enc_valid_lens)
            # context的形状为(batch_size,1,num_hidden)
            x_ = torch.cat((context, torch.unsqueeze(x_, dim=1)), dim=-1)
            # 将x变形为(1,batch_size,embed_size+num_hidden)
            out, hidden_state = self.rnn(x_.permute(1, 0, 2), hidden_state)
            outputs.append(out)
            self._attention_weights.append(self.attention.attention_weights)
        # 全连接层变换后,outputs的形状为
        # (num_steps,batch_size,vocab_size)
        outputs = self.dense(torch.cat(outputs, dim=0))
        return outputs.permute(1, 0, 2), [enc_outputs, hidden_state, enc_valid_lens]

    @property
    def attention_weights(self):
        return self._attention_weights


encoder = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,
                             num_layers=2)
encoder.eval()

decoder = Seq2SeqAttentionDecoder(vocab_size=10, embed_size=8, num_hiddens=16,
                                  num_layers=2)
decoder.eval()

x = torch.zeros((4, 7), dtype=torch.long)
state = decoder.init_state(encoder(x), None)
output, state = decoder(x, state)
print(output.shape, len(state), state[0].shape, len(state[1]), state[1][0].shape)

embed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1
batch_size, num_steps = 64, 10
lr, num_epochs, device = 0.005, 250, d2l.try_gpu()

train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)
encoder = d2l.Seq2SeqEncoder(
    len(src_vocab), embed_size, num_hiddens, num_layers, dropout)
decoder = Seq2SeqAttentionDecoder(
    len(tgt_vocab), embed_size, num_hiddens, num_layers, dropout)
net = d2l.EncoderDecoder(encoder, decoder)
print(d2l.train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device))

plt.show()
engs = ['go .', "i lost .", 'he\'s calm .', 'i\'m home .']
fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .']
for eng, fra in zip(engs, fras):
    translation, dec_attention_weight_seq = d2l.predict_seq2seq(
        net, eng, src_vocab, tgt_vocab, num_steps, device, True)
    print(f'{eng} => {translation}, ',
          f'bleu {d2l.bleu(translation, fra, k=2):.3f}')

 

标签:attention,torch,self,Attention,num,valid,size
From: https://www.cnblogs.com/o-Sakurajimamai-o/p/17720475.html

相关文章

  • Attention Mixtures for Time-Aware Sequential Recommendation
    目录概符号说明MOJITO代码TranV.,Salha-GalvanG.,SguerraB.andHennequinR.Attentionmixturesfortime-awaresequentialrecommendation.SIGIR,2023.概本文希望更好地利用时间信息,主要是在short-/long-interest上地研究,对于时间信息的利用感觉很一般.符......
  • 【CVPR2022】Shunted Self-Attention via Multi-Scale Token Aggregation
    来自CVPR2022基于多尺度令牌聚合的分流自注意力论文地址:[2111.15193]ShuntedSelf-AttentionviaMulti-ScaleTokenAggregation(arxiv.org)项目地址:https://github.com/OliverRensu/Shunted-Transformer一、Introduction还是经典的ViT的历史遗留问题:ViT中的自注意力计算......
  • JSNeedAttention
    JSAttentionpush返回的是数组增加后的长度!!!对象名可变setFieldsValue({[`bank${index}`]:val});判断是否空对象Object.keys(obj);JSON.stringify(obj)!=="{}";还有$.isEmptyObject(data2);Object.getOwnPropertyNames(data3);//和Object.keys类似关闭标签替......
  • 【学习笔记】Self-attention
    最近想学点NLP的东西,开始看BERT,看了发现transformer知识丢光了,又来看self-attention;看完self-attention发现还得再去学学wordembedding...推荐学习顺序是:wordembedding、self-attention/transformer、BERT(后面可能还会补充新的)我是看的李宏毅老师的课程+pdf,真的很爱他的课........
  • Self-Attention
    Self-Attention参考:https://zhuanlan.zhihu.com/p/619154409在Attentionisallyouneed这篇论文中,可以看到这样一个公式:$Attention(Q,K,V)=softmax(\frac{QK^{T}}{\sqrt{d_k}})V$1.定义input在进行Self-Attention之前,我们首先定义3个1×4的input。pytorch代码如下:......
  • FlashAttention算法详解
    这篇文章的目的是详细的解释FlashAttention,为什么要解释FlashAttention呢?因为FlashAttention是一种重新排序注意力计算的算法,它无需任何近似即可加速注意力计算并减少内存占用。所以作为目前LLM的模型加速它是一个非常好的解决方案,本文介绍经典的V1版本,最新的V2做了其他优化我们......
  • 关于Makefile出现E325: ATTENTION报错
    前言对于新手使用Makefile,有时候使用vi命令打开Makefile会出现E325:ATTENTION报错,而只要出现了一次,之后每次使用vi命令打开相同的Makefile都会出现这个报错。原因目前我发现出现这种bug的原因有两个,还有其他可能触发这种问题的可以在评论区留言。原因一编辑文件......
  • Attention机制竟有bug?Softmax是罪魁祸首,影响所有Transformer
    前言 「大模型开发者,你们错了。」本文转载自机器之心仅用于学术分享,若侵权请联系删除欢迎关注公众号CV技术指南,专注于计算机视觉的技术总结、最新技术跟踪、经典论文解读、CV招聘信息。CV各大方向专栏与各个部署框架最全教程整理【CV技术指南】CV全栈指导班、基础入门班、论......
  • 斯坦福博士一己之力让Attention提速9倍!FlashAttention燃爆显存,Transformer上下文长度
    前言 FlashAttention新升级!斯坦福博士一人重写算法,第二代实现了最高9倍速提升。本文转载自新智元仅用于学术分享,若侵权请联系删除欢迎关注公众号CV技术指南,专注于计算机视觉的技术总结、最新技术跟踪、经典论文解读、CV招聘信息。CV各大方向专栏与各个部署框架最全教程整理......
  • self-attention
    Selfattention考虑了整个sequence的资讯【transfermer中重要的架构是self-attention】 解决sequence2sequence的问题,考虑前后文 Isawasaw第一个saw对应输出动词 第二个输出名词 如何计算相关性【attentionscore】输入的两个向量乘两个矩阵Q=query   k=key......