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
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
# 超参数
d_model = 512
num_heads = 8
num_layers = 6
max_seq_len = 50
vocab_size = 10000
d_ff = 2048
# Tokenizer
def tokenize(text):
return [ord(c) % vocab_size for c in text] # 字符级别 Tokenizer
def detokenize(tokens):
return ''.join([chr(t) for t in tokens])
# 位置编码
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_seq_len):
super().__init__()
self.positional_encoding = self._generate_positional_encoding(d_model, max_seq_len)
def _generate_positional_encoding(self, d_model, max_seq_len):
pos = np.arange(max_seq_len).reshape(-1, 1)
i = np.arange(d_model).reshape(1, -1)
angle_rates = 1 / np.power(10000, (2 * (i // 2)) / d_model)
pos_encoding = pos * angle_rates
pos_encoding[:, 0::2] = np.sin(pos_encoding[:, 0::2]) # 偶数列
pos_encoding[:, 1::2] = np.cos(pos_encoding[:, 1::2]) # 奇数列
return torch.tensor(pos_encoding, dtype=torch.float32)
def forward(self, x):
seq_len = x.size(1)
return x + self.positional_encoding[:seq_len, :]
# 多头注意力机制
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
self.num_heads = num_heads
self.d_head = d_model // num_heads
self.q_linear = nn.Linear(d_model, d_model)
self.k_linear = nn.Linear(d_model, d_model)
self.v_linear = nn.Linear(d_model, d_model)
self.out_linear = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
batch_size = q.size(0)
q = self.q_linear(q).view(batch_size, -1, self.num_heads, self.d_head).transpose(1, 2)
k = self.k_linear(k).view(batch_size, -1, self.num_heads, self.d_head).transpose(1, 2)
v = self.v_linear(v).view(batch_size, -1, self.num_heads, self.d_head).transpose(1, 2)
scores = torch.matmul(q, k.transpose(-2, -1)) / np.sqrt(self.d_head)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attention_weights = F.softmax(scores, dim=-1)
attention_output = torch.matmul(attention_weights, v)
attention_output = attention_output.transpose(1, 2).contiguous().view(batch_size, -1, self.num_heads * self.d_head)
return self.out_linear(attention_output)
# 前向传播网络
class FeedForward(nn.Module):
def __init__(self, d_model, d_ff):
super().__init__()
self.linear1 = nn.Linear(d_model, d_ff)
self.linear2 = nn.Linear(d_ff, d_model)
def forward(self, x):
return self.linear2(F.relu(self.linear1(x)))
# 编码器层
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff):
super().__init__()
self.attention = MultiHeadAttention(d_model, num_heads)
self.norm1 = nn.LayerNorm(d_model)
self.ffn = FeedForward(d_model, d_ff)
self.norm2 = nn.LayerNorm(d_model)
def forward(self, x, mask=None):
attention_output = self.attention(x, x, x, mask)
x = self.norm1(x + attention_output)
ffn_output = self.ffn(x)
return self.norm2(x + ffn_output)
# 解码器层
class TransformerDecoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff):
super().__init__()
self.self_attention = MultiHeadAttention(d_model, num_heads)
self.norm1 = nn.LayerNorm(d_model)
self.cross_attention = MultiHeadAttention(d_model, num_heads)
self.norm2 = nn.LayerNorm(d_model)
self.ffn = FeedForward(d_model, d_ff)
self.norm3 = nn.LayerNorm(d_model)
def forward(self, x, encoder_output, tgt_mask=None, memory_mask=None):
self_attention_output = self.self_attention(x, x, x, tgt_mask)
x = self.norm1(x + self_attention_output)
cross_attention_output = self.cross_attention(x, encoder_output, encoder_output, memory_mask)
x = self.norm2(x + cross_attention_output)
ffn_output = self.ffn(x)
return self.norm3(x + ffn_output)
# 编码器
class TransformerEncoder(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, max_seq_len, d_ff):
super().__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.positional_encoding = PositionalEncoding(d_model, max_seq_len)
self.layers = nn.ModuleList([TransformerEncoderLayer(d_model, num_heads, d_ff) for _ in range(num_layers)])
def forward(self, x, mask=None):
x = self.embedding(x)
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, max_seq_len, d_ff):
super().__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.positional_encoding = PositionalEncoding(d_model, max_seq_len)
self.layers = nn.ModuleList([TransformerDecoderLayer(d_model, num_heads, d_ff) for _ in range(num_layers)])
self.out_proj = nn.Linear(d_model, vocab_size)
def forward(self, x, encoder_output, tgt_mask=None, memory_mask=None):
x = self.embedding(x)
x = self.positional_encoding(x)
for layer in self.layers:
x = layer(x, encoder_output, tgt_mask, memory_mask)
return self.out_proj(x)
# 完整 Transformer
class Transformer(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, max_seq_len, d_ff):
super().__init__()
self.encoder = TransformerEncoder(vocab_size, d_model, num_heads, num_layers, max_seq_len, d_ff)
self.decoder = TransformerDecoder(vocab_size, d_model, num_heads, num_layers, max_seq_len, d_ff)
def forward(self, src, tgt, src_mask=None, tgt_mask=None, memory_mask=None):
encoder_output = self.encoder(src, src_mask)
decoder_output = self.decoder(tgt, encoder_output, tgt_mask, memory_mask)
return decoder_output