victory的博客

长安一片月,万户捣衣声

0%

  • Transformer

    Transformer是一种基于自注意力机制的深度学习模型,由Google在2017年的论文“Attention is All You Need”提出。Transformer由编码器(Encoder)和解码器(Decoder)组成,结构如下图所示:

  • Transformer Pytorch代码实现

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import torch
import torch.nn as nn
import torch.nn.functional as F
import math


class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super(PositionalEncoding, self).__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)

def forward(self, x):
return x + self.pe[:, :x.size(1)].detach()


class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super(MultiHeadAttention, self).__init__()
self.d_model = d_model
self.num_heads = num_heads
assert d_model % self.num_heads == 0 # 确保 d_model 能被 num_heads 整除

self.depth = d_model // self.num_heads

self.wq = nn.Linear(d_model, d_model)
self.wk = nn.Linear(d_model, d_model)
self.wv = nn.Linear(d_model, d_model)

self.dense = nn.Linear(d_model, d_model)

def split_heads(self, x, batch_size):
x = x.view(batch_size, -1, self.num_heads, self.depth)
return x.permute(0, 2, 1, 3)

def attention(self, query, key, value, mask=None, dropout=None):
matmul_qk = torch.matmul(query, key.transpose(-2, -1)) # QK^T
dk = query.size(-1)
scaled_attention_logits = matmul_qk / math.sqrt(dk)

if mask is not None:
scaled_attention_logits += (mask * -1e9) # 避免pad部分被注意到

attention_weights = torch.softmax(scaled_attention_logits, dim=-1)
if dropout is not None:
attention_weights = dropout(attention_weights)

output = torch.matmul(attention_weights, value)
return output, attention_weights

def forward(self, query, key, value, mask=None, dropout=None):
batch_size = query.size(0)

query = self.split_heads(self.wq(query), batch_size)
key = self.split_heads(self.wk(key), batch_size)
value = self.split_heads(self.wv(value), batch_size)

output, attention_weights = self.attention(query, key, value, mask, dropout)
output = output.permute(0, 2, 1, 3).contiguous().view(batch_size, -1, self.d_model)

return self.dense(output)


class FeedForwardNetwork(nn.Module):
def __init__(self, d_model, d_ff=2048, dropout=0.1):
super(FeedForwardNetwork, self).__init__()
self.linear1 = nn.Linear(d_model, d_ff)
self.linear2 = nn.Linear(d_ff, d_model)
self.dropout = nn.Dropout(dropout)

def forward(self, x):
x = F.relu(self.linear1(x))
x = self.dropout(x)
return self.linear2(x)


class EncoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff=2048, dropout=0.1):
super(EncoderLayer, self).__init__()
self.attention = MultiHeadAttention(d_model, num_heads)
self.ffn = FeedForwardNetwork(d_model, d_ff, dropout)
self.layernorm1 = nn.LayerNorm(d_model)
self.layernorm2 = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)

def forward(self, x, mask=None):
# 自注意力层
attn_output = self.attention(x, x, x, mask, self.dropout)
x = self.layernorm1(x + attn_output) # 残差连接 + LayerNorm

# 前馈网络层
ffn_output = self.ffn(x)
x = self.layernorm2(x + ffn_output) # 残差连接 + LayerNorm

return x


class DecoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff=2048, dropout=0.1):
super(DecoderLayer, self).__init__()
self.attention1 = MultiHeadAttention(d_model, num_heads)
self.attention2 = MultiHeadAttention(d_model, num_heads)
self.ffn = FeedForwardNetwork(d_model, d_ff, dropout)
self.layernorm1 = nn.LayerNorm(d_model)
self.layernorm2 = nn.LayerNorm(d_model)
self.layernorm3 = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)

def forward(self, x, enc_output, look_ahead_mask=None, padding_mask=None):
# 解码器中的自注意力层
attn1_output = self.attention1(x, x, x, look_ahead_mask, self.dropout)
x = self.layernorm1(attn1_output + x)

# 编码器-解码器注意力层
attn2_output = self.attention2(x, enc_output, enc_output, padding_mask, self.dropout)
x = self.layernorm2(attn2_output + x)

# 前馈网络层
ffn_output = self.ffn(x)
x = self.layernorm3(ffn_output + x)

return x


class TransformerEncoder(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, d_ff=2048, dropout=0.1):
super(TransformerEncoder, self).__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.positional_encoding = PositionalEncoding(d_model)
self.layers = nn.ModuleList([
EncoderLayer(d_model, num_heads, d_ff, dropout) for _ in range(num_layers)
])
self.d_model = d_model

def forward(self, x, mask=None):
x = self.embedding(x) * math.sqrt(self.d_model) # 嵌入 + 缩放
x = self.positional_encoding(x)

for layer in self.layers:
x = layer(x, mask)

return x


class TransformerDecoder(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, d_ff=2048, dropout=0.1):
super(TransformerDecoder, self).__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.positional_encoding = PositionalEncoding(d_model)
self.layers = nn.ModuleList([
DecoderLayer(d_model, num_heads, d_ff, dropout) for _ in range(num_layers)
])
self.d_model = d_model

def forward(self, x, enc_output, look_ahead_mask=None, padding_mask=None):
x = self.embedding(x) * math.sqrt(self.d_model)
x = self.positional_encoding(x)

for layer in self.layers:
x = layer(x, enc_output, look_ahead_mask, padding_mask)

return x


class Transformer(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, d_ff=2048, dropout=0.1):
super(Transformer, self).__init__()

self.encoder = TransformerEncoder(vocab_size, d_model, num_heads, num_layers, d_ff, dropout)
self.decoder = TransformerDecoder(vocab_size, d_model, num_heads, num_layers, d_ff, dropout)
self.output_layer = nn.Linear(d_model, vocab_size)

def forward(self, src, tgt, src_mask=None, tgt_mask=None):
# 编码器部分
enc_output = self.encoder(src, src_mask)

# 解码器部分
dec_output = self.decoder(tgt, enc_output, tgt_mask, src_mask)

# 输出层
return self.output_layer(dec_output)


vocab_size = 10000 # 词汇表大小
d_model = 512 # 特征维度
num_heads = 8 # 注意力头数
num_layers = 6 # 编码器和解码器层数
dropout = 0.1 # Dropout 比例

# 初始化 Transformer 模型
transformer = Transformer(vocab_size, d_model, num_heads, num_layers, dropout=dropout)

# 输入张量(batch_size, sequence_length)
src = torch.randint(0, vocab_size, (32, 100)) # 假设 source 语言输入 batch_size=32,序列长度=100
tgt = torch.randint(0, vocab_size, (32, 100)) # 假设 target 语言输入 batch_size=32,序列长度=100

# 创建遮罩(假设没有 padding)
src_mask = None
tgt_mask = None

# 前向传播
output = transformer(src, tgt, src_mask, tgt_mask)

print("Output shape:", output.shape) # 输出的形状 (batch_size, tgt_sequence_length, vocab_size)

  • 自注意力机制(Self-Attention)

    自注意力机制是Transfromer中的重要组件,它通过计算Query (Q)、Key (K)、Value (V)获取token之间的相关性。Q、K、V矩阵是通过输入嵌入(或前一层的输出)与权重矩阵进行线性变换得到的。

    自注意力机制的输入格式为(batch_size, seq_len, d_model),batch_size是批次大小,seq_len是序列长度,d_model是嵌入维度。

    Q、K、V的计算:Q=X x W_Q, K=X x W_K, V=X x W_V。

    自注意力输出的计算:output = (QxK_T) x V。

  • 自注意力机制pytorch代码实现

    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
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    import torch
    import torch.nn.functional as F
    from torch import nn


    class SingleHeadAttention(nn.Module):
    def __init__(self, embed_size):
    super(SingleHeadAttention, self).__init__()

    # 输入的embedding维度
    self.embed_size = embed_size

    # 定义查询、键和值的线性变换
    self.query_fc = nn.Linear(embed_size, embed_size)
    self.key_fc = nn.Linear(embed_size, embed_size)
    self.value_fc = nn.Linear(embed_size, embed_size)

    # 输出的线性变换
    self.out_fc = nn.Linear(embed_size, embed_size)

    def forward(self, X, mask=None):
    print("X.shape: ", X.shape)
    # Step1: 通过线性层生成查询、键和值的向量
    Q = self.query_fc(X) # (batch_size, seq_len, embed_size)
    print("Q.shape: ", Q.shape)
    K = self.key_fc(X) # (batch_size, seq_len, embed_size)
    print("K.shape: ", K.shape)
    V = self.value_fc(X) # (batch_size, seq_len, embed_size)
    print("V.shape: ", V.shape)

    # Step2: 计算注意力得分
    attention_scores = torch.matmul(Q, K.transpose(-2, -1)) / (self.embed_size ** 0.5)
    print("attention_scores.shape: ", attention_scores.shape)

    # 如果有mask,应用mask
    if mask is not None:
    attention_scores = attention_scores.masked_fill(mask == 0, float('-inf'))

    # Step3: 计算注意力权重(softmax)
    attention_weights = F.softmax(attention_scores, dim=-1) # (batch_size, seq_len, seq_len)

    # Step4: 加权求和得到输出
    output = torch.matmul(attention_weights, V) # (batch_size, seq_len, embed_size)

    return output


    if __name__ == "__main__":
    batch_size = 2
    seq_len = 4
    embed_size = 8

    # 随机生成输入数据
    X = torch.randn(batch_size, seq_len, embed_size)

    # 创建自注意力模型
    attention_layer = SingleHeadAttention(embed_size)

    # 前向传播
    output = attention_layer(X)

    print(f"Output: {output.shape}") # (batch_size, seq_len, embed_size)

  • 多头注意力机制(Multi-Head Attention)

    多头注意力机制是Transformer模型中的一个核心组成部分,它通过并行计算多个注意力头来捕捉输入序列的不同信息,每个注意力头都有独立的Q、K、V,能够关注输入的不同子空间,从而增强模型对不同特征的表达能力。

    多头注意力计算过程:

    1. 线性变换:输入的向量首先会通过不同的线性变换(权重矩阵)生成多个查询(Q)、键(K)和值(V)向量。
    2. 计算注意力:每个注意力头根据查询、键和值计算注意力权重,并通过加权求和得到一个输出。
    3. 拼接:所有头的输出会被拼接在一起。
    4. 线性变换:拼接后的结果通过一个线性变换,最终输出。
  • 多头注意力机制pytorch代码实现

    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
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    import torch
    import torch.nn as nn
    import torch.nn.functional as F


    class MultiHeadAttention(nn.Module):
    def __init__(self, embed_size, num_heads):
    super(MultiHeadAttention, self).__init__()
    self.embed_size = embed_size
    self.num_heads = num_heads
    self.head_dim = embed_size // num_heads

    assert self.head_dim * num_heads == embed_size, "Embedding size must be divisible by num_heads"

    # 定义查询、键、值的线性变换
    self.query_fc = nn.Linear(embed_size, embed_size)
    self.key_fc = nn.Linear(embed_size, embed_size)
    self.value_fc = nn.Linear(embed_size, embed_size)

    # 定义输出的线性变换
    self.fc_out = nn.Linear(embed_size, embed_size)

    def forward(self, X):
    batch_size = X.shape[1]

    # 通过线性变换得到 Q, K, V
    Q = self.query_fc(X) # (seq_len, batch_size, embed_size)
    print("Q.shape: ", Q.shape)
    K = self.key_fc(X)
    print("K.shape: ", K.shape)
    V = self.value_fc(X)
    print("V.shape: ", V.shape)

    # 将Q, K, V 切分成多个头
    Q = Q.view(X.shape[0], batch_size, self.num_heads, self.head_dim).transpose(1,
    2) # (seq_len, batch_size, num_heads, head_dim)
    print("Q_multi_head.shape: ", Q.shape)
    K = K.view(X.shape[0], batch_size, self.num_heads, self.head_dim).transpose(1, 2)
    print("K_multi_head.shape: ", K.shape)
    V = V.view(X.shape[0], batch_size, self.num_heads, self.head_dim).transpose(1, 2)
    print("V_multi_head.shape: ", V.shape)

    # 计算注意力得分
    energy = torch.matmul(Q, K.transpose(-2, -1)) # (seq_len, batch_size, num_heads, seq_len)
    attention = torch.softmax(energy / (self.head_dim ** 0.5), dim=-1) # 注意力得分
    print("Q*K.shape", attention.shape)

    # 计算加权求和的输出
    out = torch.matmul(attention, V) # (seq_len, batch_size, num_heads, head_dim)

    # 将多个头合并
    out = out.transpose(1, 2).contiguous().view(X.shape[0], batch_size, self.num_heads * self.head_dim)

    # 通过输出的线性层
    out = self.fc_out(out)

    return out


    # 测试
    embed_size = 64
    num_heads = 8
    seq_len = 10
    batch_size = 32

    multihead_attention = MultiHeadAttention(embed_size, num_heads)

    # 输入张量,shape: (seq_len, batch_size, embed_size)
    X = torch.rand(seq_len, batch_size, embed_size)

    out = multihead_attention(X)
    print(out.shape) # (seq_len, batch_size, embed_size)

Netron是一款开源的深度学习模型可视化工具,支持多种深度学习框架生成的模型(例如,PyTorch、TensorFlow、ONNX等)的可视化。

网页版工具地址:Netron

模型蒸馏的核心思想是在保持较高预测性能的同时,通过知识迁移的方式,将一个复杂的大模型(教师模型)的知识传授给一个相对简单的小模型(学生模型),极大地降低了模型的复杂性和计算资源需求,实现了模型的轻量化和高效化。

阅读全文 »