torinriley
commited on
Upload model.py
Browse files
model.py
ADDED
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import math
|
4 |
+
|
5 |
+
class LayerNormalization(nn.Module):
|
6 |
+
def __init__(self, features: int, eps: float = 1e-6) -> None:
|
7 |
+
super().__init__()
|
8 |
+
self.eps = eps
|
9 |
+
self.alpha = nn.Parameter(torch.ones(features))
|
10 |
+
self.bias = nn.Parameter(torch.zeros(features))
|
11 |
+
|
12 |
+
def forward(self, x):
|
13 |
+
mean = x.mean(dim=-1, keepdim=True)
|
14 |
+
std = x.std(dim=-1, keepdim=True)
|
15 |
+
return self.alpha * (x - mean) / (std + self.eps) + self.bias
|
16 |
+
|
17 |
+
class FeedForwardBlock(nn.Module):
|
18 |
+
def __init__(self, d_model: int, d_ff: int, dropout: float) -> None:
|
19 |
+
super().__init__()
|
20 |
+
self.fc1 = nn.Linear(d_model, d_ff)
|
21 |
+
self.dropout = nn.Dropout(dropout)
|
22 |
+
self.fc2 = nn.Linear(d_ff, d_model)
|
23 |
+
|
24 |
+
def forward(self, x):
|
25 |
+
return self.fc2(self.dropout(torch.relu(self.fc1(x))))
|
26 |
+
|
27 |
+
class InputEmbeddings(nn.Module):
|
28 |
+
def __init__(self, d_model: int, vocab_size: int) -> None:
|
29 |
+
super().__init__()
|
30 |
+
self.d_model = d_model
|
31 |
+
self.embedding = nn.Embedding(vocab_size, d_model)
|
32 |
+
|
33 |
+
def forward(self, x):
|
34 |
+
return self.embedding(x) * math.sqrt(self.d_model)
|
35 |
+
|
36 |
+
class PositionalEncoding(nn.Module):
|
37 |
+
def __init__(self, d_model: int, seq_len: int, dropout: float) -> None:
|
38 |
+
super().__init__()
|
39 |
+
self.dropout = nn.Dropout(dropout)
|
40 |
+
pe = torch.zeros(seq_len, d_model)
|
41 |
+
position = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(1)
|
42 |
+
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
43 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
44 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
45 |
+
pe = pe.unsqueeze(0)
|
46 |
+
self.register_buffer('pe', pe)
|
47 |
+
|
48 |
+
def forward(self, x):
|
49 |
+
x = x + self.pe[:, :x.shape[1], :].requires_grad_(False)
|
50 |
+
return self.dropout(x)
|
51 |
+
|
52 |
+
class ResidualConnection(nn.Module):
|
53 |
+
def __init__(self, features: int, dropout: float) -> None:
|
54 |
+
super().__init__()
|
55 |
+
self.dropout = nn.Dropout(dropout)
|
56 |
+
self.norm = LayerNormalization(features)
|
57 |
+
|
58 |
+
def forward(self, x, sublayer):
|
59 |
+
return x + self.dropout(sublayer(self.norm(x)))
|
60 |
+
|
61 |
+
class MultiHeadAttentionBlock(nn.Module):
|
62 |
+
def __init__(self, d_model: int, num_heads: int, dropout: float) -> None:
|
63 |
+
super().__init__()
|
64 |
+
self.num_heads = num_heads
|
65 |
+
self.d_k = d_model // num_heads
|
66 |
+
self.w_q = nn.Linear(d_model, d_model, bias=False)
|
67 |
+
self.w_k = nn.Linear(d_model, d_model, bias=False)
|
68 |
+
self.w_v = nn.Linear(d_model, d_model, bias=False)
|
69 |
+
self.w_o = nn.Linear(d_model, d_model, bias=False)
|
70 |
+
self.dropout = nn.Dropout(dropout)
|
71 |
+
|
72 |
+
@staticmethod
|
73 |
+
def attention(query, key, value, mask, dropout: nn.Dropout):
|
74 |
+
d_k = query.shape[-1]
|
75 |
+
scores = (query @ key.transpose(-2, -1)) / math.sqrt(d_k)
|
76 |
+
if mask is not None:
|
77 |
+
scores.masked_fill_(mask == 0, -1e9)
|
78 |
+
scores = scores.softmax(dim=-1)
|
79 |
+
if dropout is not None:
|
80 |
+
scores = dropout(scores)
|
81 |
+
return scores @ value, scores
|
82 |
+
|
83 |
+
def forward(self, q, k, v, mask):
|
84 |
+
query = self.w_q(q)
|
85 |
+
key = self.w_k(k)
|
86 |
+
value = self.w_v(v)
|
87 |
+
query = query.view(query.shape[0], query.shape[1], self.num_heads, self.d_k).transpose(1, 2)
|
88 |
+
key = key.view(key.shape[0], key.shape[1], self.num_heads, self.d_k).transpose(1, 2)
|
89 |
+
value = value.view(value.shape[0], value.shape[1], self.num_heads, self.d_k).transpose(1, 2)
|
90 |
+
x, self.attention_scores = MultiHeadAttentionBlock.attention(query, key, value, mask, self.dropout)
|
91 |
+
x = x.transpose(1, 2).contiguous().view(x.shape[0], -1, self.num_heads * self.d_k)
|
92 |
+
return self.w_o(x)
|
93 |
+
|
94 |
+
class EncoderBlock(nn.Module):
|
95 |
+
def __init__(self, features: int, self_attention: MultiHeadAttentionBlock, feed_forward: FeedForwardBlock, dropout: float) -> None:
|
96 |
+
super().__init__()
|
97 |
+
self.self_attention = self_attention
|
98 |
+
self.feed_forward = feed_forward
|
99 |
+
self.residuals = nn.ModuleList([ResidualConnection(features, dropout) for _ in range(2)])
|
100 |
+
|
101 |
+
def forward(self, x, src_mask):
|
102 |
+
x = self.residuals[0](x, lambda x: self.self_attention(x, x, x, src_mask))
|
103 |
+
x = self.residuals[1](x, self.feed_forward)
|
104 |
+
return x
|
105 |
+
|
106 |
+
class Encoder(nn.Module):
|
107 |
+
def __init__(self, features: int, layers: nn.ModuleList) -> None:
|
108 |
+
super().__init__()
|
109 |
+
self.layers = layers
|
110 |
+
self.norm = LayerNormalization(features)
|
111 |
+
|
112 |
+
def forward(self, x, mask):
|
113 |
+
for layer in self.layers:
|
114 |
+
x = layer(x, mask)
|
115 |
+
return self.norm(x)
|
116 |
+
|
117 |
+
class DecoderBlock(nn.Module):
|
118 |
+
def __init__(self, features: int, self_attention: MultiHeadAttentionBlock, cross_attention: MultiHeadAttentionBlock, feed_forward: FeedForwardBlock, dropout: float) -> None:
|
119 |
+
super().__init__()
|
120 |
+
self.self_attention = self_attention
|
121 |
+
self.cross_attention = cross_attention
|
122 |
+
self.feed_forward = feed_forward
|
123 |
+
self.residuals = nn.ModuleList([ResidualConnection(features, dropout) for _ in range(3)])
|
124 |
+
|
125 |
+
def forward(self, x, encoder_output, src_mask, tgt_mask):
|
126 |
+
x = self.residuals[0](x, lambda x: self.self_attention(x, x, x, tgt_mask))
|
127 |
+
x = self.residuals[1](x, lambda x: self.cross_attention(x, encoder_output, encoder_output, src_mask))
|
128 |
+
x = self.residuals[2](x, self.feed_forward)
|
129 |
+
return x
|
130 |
+
|
131 |
+
class Decoder(nn.Module):
|
132 |
+
def __init__(self, features: int, layers: nn.ModuleList) -> None:
|
133 |
+
super().__init__()
|
134 |
+
self.layers = layers
|
135 |
+
self.norm = LayerNormalization(features)
|
136 |
+
|
137 |
+
def forward(self, x, encoder_output, src_mask, tgt_mask):
|
138 |
+
for layer in self.layers:
|
139 |
+
x = layer(x, encoder_output, src_mask, tgt_mask)
|
140 |
+
return self.norm(x)
|
141 |
+
|
142 |
+
class ProjectionLayer(nn.Module):
|
143 |
+
def __init__(self, d_model, vocab_size) -> None:
|
144 |
+
super().__init__()
|
145 |
+
self.proj = nn.Linear(d_model, vocab_size)
|
146 |
+
|
147 |
+
def forward(self, x) -> None:
|
148 |
+
return self.proj(x)
|
149 |
+
|
150 |
+
class Transformer(nn.Module):
|
151 |
+
def __init__(self, encoder: Encoder, decoder: Decoder, src_embed: InputEmbeddings, tgt_embed: InputEmbeddings, src_pos: PositionalEncoding, tgt_pos: PositionalEncoding, projection_layer: ProjectionLayer) -> None:
|
152 |
+
super().__init__()
|
153 |
+
self.encoder = encoder
|
154 |
+
self.decoder = decoder
|
155 |
+
self.src_embed = src_embed
|
156 |
+
self.tgt_embed = tgt_embed
|
157 |
+
self.src_pos = src_pos
|
158 |
+
self.tgt_pos = tgt_pos
|
159 |
+
self.projection_layer = projection_layer
|
160 |
+
|
161 |
+
def encode(self, src, src_mask):
|
162 |
+
src = self.src_embed(src)
|
163 |
+
src = self.src_pos(src)
|
164 |
+
return self.encoder(src, src_mask)
|
165 |
+
|
166 |
+
def decode(self, encoder_output: torch.Tensor, src_mask: torch.Tensor, tgt: torch.Tensor, tgt_mask: torch.Tensor):
|
167 |
+
tgt = self.tgt_embed(tgt)
|
168 |
+
tgt = self.tgt_pos(tgt)
|
169 |
+
return self.decoder(tgt, encoder_output, src_mask, tgt_mask)
|
170 |
+
|
171 |
+
def project(self, x):
|
172 |
+
return self.projection_layer(x)
|
173 |
+
|
174 |
+
def build_transformer(src_vocab_size: int, tgt_vocab_size: int, src_seq_len: int, tgt_seq_len: int, d_model: int = 512, num_layers: int = 6, num_heads: int = 8, dropout: float = 0.1, d_ff: int = 2048) -> Transformer:
|
175 |
+
src_embed = InputEmbeddings(d_model, src_vocab_size)
|
176 |
+
tgt_embed = InputEmbeddings(d_model, tgt_vocab_size)
|
177 |
+
src_pos = PositionalEncoding(d_model, src_seq_len, dropout)
|
178 |
+
tgt_pos = PositionalEncoding(d_model, tgt_seq_len, dropout)
|
179 |
+
|
180 |
+
encoder_blocks = []
|
181 |
+
for _ in range(num_layers):
|
182 |
+
self_attention = MultiHeadAttentionBlock(d_model, num_heads, dropout)
|
183 |
+
feed_forward = FeedForwardBlock(d_model, d_ff, dropout)
|
184 |
+
encoder_block = EncoderBlock(d_model, self_attention, feed_forward, dropout)
|
185 |
+
encoder_blocks.append(encoder_block)
|
186 |
+
|
187 |
+
decoder_blocks = []
|
188 |
+
for _ in range(num_layers):
|
189 |
+
self_attention = MultiHeadAttentionBlock(d_model, num_heads, dropout)
|
190 |
+
cross_attention = MultiHeadAttentionBlock(d_model, num_heads, dropout)
|
191 |
+
feed_forward = FeedForwardBlock(d_model, d_ff, dropout)
|
192 |
+
decoder_block = DecoderBlock(d_model, self_attention, cross_attention, feed_forward, dropout)
|
193 |
+
decoder_blocks.append(decoder_block)
|
194 |
+
|
195 |
+
encoder = Encoder(d_model, nn.ModuleList(encoder_blocks))
|
196 |
+
decoder = Decoder(d_model, nn.ModuleList(decoder_blocks))
|
197 |
+
projection_layer = ProjectionLayer(d_model, tgt_vocab_size)
|
198 |
+
transformer = Transformer(encoder, decoder, src_embed, tgt_embed, src_pos, tgt_pos, projection_layer)
|
199 |
+
|
200 |
+
for p in transformer.parameters():
|
201 |
+
if p.dim() > 1:
|
202 |
+
nn.init.xavier_uniform_(p)
|
203 |
+
|
204 |
+
return transformer
|