Spaces:
Sleeping
Sleeping
Update app/model_def.py
Browse files- app/model_def.py +73 -17
app/model_def.py
CHANGED
|
@@ -2,6 +2,7 @@ import torch
|
|
| 2 |
import torch.nn as nn
|
| 3 |
import math
|
| 4 |
|
|
|
|
| 5 |
class InputEmbedding(nn.Module):
|
| 6 |
def __init__(self, d_model: int, vocab_size: int):
|
| 7 |
super().__init__()
|
|
@@ -12,6 +13,7 @@ class InputEmbedding(nn.Module):
|
|
| 12 |
def forward(self, x):
|
| 13 |
return self.embed(x) * math.sqrt(self.d_model)
|
| 14 |
|
|
|
|
| 15 |
class PositionalEncoding(nn.Module):
|
| 16 |
def __init__(self, d_model: int, seq_len: int, dropout: float):
|
| 17 |
super().__init__()
|
|
@@ -20,16 +22,19 @@ class PositionalEncoding(nn.Module):
|
|
| 20 |
self.dropout = nn.Dropout(dropout)
|
| 21 |
pe = torch.zeros(seq_len, d_model)
|
| 22 |
position = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(1)
|
| 23 |
-
div_term = torch.exp(
|
|
|
|
|
|
|
| 24 |
pe[:, 0::2] = torch.sin(position * div_term)
|
| 25 |
pe[:, 1::2] = torch.cos(position * div_term)
|
| 26 |
pe = pe.unsqueeze(0)
|
| 27 |
-
self.register_buffer(
|
| 28 |
|
| 29 |
def forward(self, x):
|
| 30 |
-
x = x + (self.pe[:, :x.shape[1], :]).requires_grad_(False)
|
| 31 |
return self.dropout(x)
|
| 32 |
|
|
|
|
| 33 |
class LayerNorm(nn.Module):
|
| 34 |
def __init__(self, d_model: int, epsilon: float = 1e-6):
|
| 35 |
super().__init__()
|
|
@@ -42,6 +47,7 @@ class LayerNorm(nn.Module):
|
|
| 42 |
std = x.std(dim=-1, keepdim=True)
|
| 43 |
return self.gamma * (x - mean) / (std + self.epsilon) + self.beta
|
| 44 |
|
|
|
|
| 45 |
class FeedForward(nn.Module):
|
| 46 |
def __init__(self, d_model: int, d_ff: int, dropout: float):
|
| 47 |
super().__init__()
|
|
@@ -52,6 +58,7 @@ class FeedForward(nn.Module):
|
|
| 52 |
def forward(self, x):
|
| 53 |
return self.layer2(self.dropout(torch.relu(self.layer1(x))))
|
| 54 |
|
|
|
|
| 55 |
class MHA(nn.Module):
|
| 56 |
def __init__(self, d_model: int, h: int, dropout: float):
|
| 57 |
super().__init__()
|
|
@@ -80,13 +87,18 @@ class MHA(nn.Module):
|
|
| 80 |
query = self.w_q(q)
|
| 81 |
key = self.w_k(k)
|
| 82 |
value = self.w_v(v)
|
| 83 |
-
query = query.view(query.shape[0], query.shape[1], self.h, self.d_k).transpose(
|
|
|
|
|
|
|
| 84 |
key = key.view(key.shape[0], key.shape[1], self.h, self.d_k).transpose(1, 2)
|
| 85 |
-
value = value.view(value.shape[0], value.shape[1], self.h, self.d_k).transpose(
|
|
|
|
|
|
|
| 86 |
x, self.attention_scores = MHA.attention(query, key, value, mask, self.dropout)
|
| 87 |
x = x.transpose(1, 2).contiguous().view(x.shape[0], -1, self.h * self.d_k)
|
| 88 |
return self.w_o(x)
|
| 89 |
|
|
|
|
| 90 |
class SkipConnection(nn.Module):
|
| 91 |
def __init__(self, d_model: int, dropout: float):
|
| 92 |
super().__init__()
|
|
@@ -96,20 +108,26 @@ class SkipConnection(nn.Module):
|
|
| 96 |
def forward(self, x, sublayer):
|
| 97 |
return x + self.dropout(sublayer(self.norm(x)))
|
| 98 |
|
|
|
|
| 99 |
class EncoderBlock(nn.Module):
|
| 100 |
-
def __init__(
|
|
|
|
|
|
|
| 101 |
super().__init__()
|
| 102 |
# Name required by the saved model file
|
| 103 |
self.attention = self_attention
|
| 104 |
self.ffn = ffn
|
| 105 |
# Name required by the saved model file
|
| 106 |
-
self.residual = nn.ModuleList(
|
|
|
|
|
|
|
| 107 |
|
| 108 |
def forward(self, x, src_mask):
|
| 109 |
x = self.residual[0](x, lambda x: self.attention(x, x, x, src_mask))
|
| 110 |
x = self.residual[1](x, self.ffn)
|
| 111 |
return x
|
| 112 |
|
|
|
|
| 113 |
class Encoder(nn.Module):
|
| 114 |
def __init__(self, d_model: int, layers: nn.ModuleList):
|
| 115 |
super().__init__()
|
|
@@ -121,22 +139,36 @@ class Encoder(nn.Module):
|
|
| 121 |
x = layer(x, mask)
|
| 122 |
return self.norm(x)
|
| 123 |
|
|
|
|
| 124 |
class DecoderBlock(nn.Module):
|
| 125 |
-
def __init__(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
super().__init__()
|
| 127 |
# Name required by the saved model file
|
| 128 |
self.self_attention = self_attention
|
| 129 |
self.cross_attention = cross_attention
|
| 130 |
self.ffn = ffn
|
| 131 |
# Name required by the saved model file
|
| 132 |
-
self.residual = nn.ModuleList(
|
|
|
|
|
|
|
| 133 |
|
| 134 |
def forward(self, x, encoder_output, src_mask, trg_mask):
|
| 135 |
x = self.residual[0](x, lambda x: self.self_attention(x, x, x, trg_mask))
|
| 136 |
-
x = self.residual[1](
|
|
|
|
|
|
|
|
|
|
| 137 |
x = self.residual[2](x, self.ffn)
|
| 138 |
return x
|
| 139 |
|
|
|
|
| 140 |
class Decoder(nn.Module):
|
| 141 |
def __init__(self, d_model: int, layers: nn.ModuleList):
|
| 142 |
super().__init__()
|
|
@@ -148,6 +180,7 @@ class Decoder(nn.Module):
|
|
| 148 |
x = layer(x, encoder_output, src_mask, trg_mask)
|
| 149 |
return self.norm(x)
|
| 150 |
|
|
|
|
| 151 |
class Output(nn.Module):
|
| 152 |
def __init__(self, d_model: int, vocab_size: int):
|
| 153 |
super().__init__()
|
|
@@ -156,8 +189,18 @@ class Output(nn.Module):
|
|
| 156 |
def forward(self, x):
|
| 157 |
return self.proj(x)
|
| 158 |
|
|
|
|
| 159 |
class Transformer(nn.Module):
|
| 160 |
-
def __init__(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
super().__init__()
|
| 162 |
self.encoder = encoder
|
| 163 |
self.decoder = decoder
|
|
@@ -188,8 +231,6 @@ class Transformer(nn.Module):
|
|
| 188 |
for block in self.decoder.layers:
|
| 189 |
attn_scores = block.cross_attention.attention_scores
|
| 190 |
if attn_scores is not None:
|
| 191 |
-
# Shape: [batch, heads, tgt_len, src_len]
|
| 192 |
-
# Squeeze batch, transpose to [heads, src_len, tgt_len]
|
| 193 |
weights.append(attn_scores.squeeze(0).transpose(-2, -1))
|
| 194 |
return weights
|
| 195 |
|
|
@@ -216,7 +257,18 @@ class Transformer(nn.Module):
|
|
| 216 |
"cross_attn": cross_weights,
|
| 217 |
}
|
| 218 |
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
src_embed = InputEmbedding(d_model, src_vocab_size)
|
| 221 |
trg_embed = InputEmbedding(d_model, trg_vocab_size)
|
| 222 |
src_pos = PositionalEncoding(d_model, src_seq_len, dropout)
|
|
@@ -232,13 +284,17 @@ def BuildTransformer(src_vocab_size: int, trg_vocab_size: int, src_seq_len: int,
|
|
| 232 |
decoder_self_attention = MHA(d_model, h, dropout)
|
| 233 |
cross_attention = MHA(d_model, h, dropout)
|
| 234 |
ffn = FeedForward(d_model, d_ff, dropout)
|
| 235 |
-
decoder_block = DecoderBlock(
|
|
|
|
|
|
|
| 236 |
decoder_blocks.append(decoder_block)
|
| 237 |
encoder = Encoder(d_model, nn.ModuleList(encoder_blocks))
|
| 238 |
decoder = Decoder(d_model, nn.ModuleList(decoder_blocks))
|
| 239 |
projection = Output(d_model, trg_vocab_size)
|
| 240 |
-
transformer = Transformer(
|
|
|
|
|
|
|
| 241 |
for p in transformer.parameters():
|
| 242 |
if p.dim() > 1:
|
| 243 |
nn.init.xavier_uniform_(p)
|
| 244 |
-
return transformer
|
|
|
|
| 2 |
import torch.nn as nn
|
| 3 |
import math
|
| 4 |
|
| 5 |
+
|
| 6 |
class InputEmbedding(nn.Module):
|
| 7 |
def __init__(self, d_model: int, vocab_size: int):
|
| 8 |
super().__init__()
|
|
|
|
| 13 |
def forward(self, x):
|
| 14 |
return self.embed(x) * math.sqrt(self.d_model)
|
| 15 |
|
| 16 |
+
|
| 17 |
class PositionalEncoding(nn.Module):
|
| 18 |
def __init__(self, d_model: int, seq_len: int, dropout: float):
|
| 19 |
super().__init__()
|
|
|
|
| 22 |
self.dropout = nn.Dropout(dropout)
|
| 23 |
pe = torch.zeros(seq_len, d_model)
|
| 24 |
position = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(1)
|
| 25 |
+
div_term = torch.exp(
|
| 26 |
+
torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)
|
| 27 |
+
)
|
| 28 |
pe[:, 0::2] = torch.sin(position * div_term)
|
| 29 |
pe[:, 1::2] = torch.cos(position * div_term)
|
| 30 |
pe = pe.unsqueeze(0)
|
| 31 |
+
self.register_buffer("pe", pe)
|
| 32 |
|
| 33 |
def forward(self, x):
|
| 34 |
+
x = x + (self.pe[:, : x.shape[1], :]).requires_grad_(False)
|
| 35 |
return self.dropout(x)
|
| 36 |
|
| 37 |
+
|
| 38 |
class LayerNorm(nn.Module):
|
| 39 |
def __init__(self, d_model: int, epsilon: float = 1e-6):
|
| 40 |
super().__init__()
|
|
|
|
| 47 |
std = x.std(dim=-1, keepdim=True)
|
| 48 |
return self.gamma * (x - mean) / (std + self.epsilon) + self.beta
|
| 49 |
|
| 50 |
+
|
| 51 |
class FeedForward(nn.Module):
|
| 52 |
def __init__(self, d_model: int, d_ff: int, dropout: float):
|
| 53 |
super().__init__()
|
|
|
|
| 58 |
def forward(self, x):
|
| 59 |
return self.layer2(self.dropout(torch.relu(self.layer1(x))))
|
| 60 |
|
| 61 |
+
|
| 62 |
class MHA(nn.Module):
|
| 63 |
def __init__(self, d_model: int, h: int, dropout: float):
|
| 64 |
super().__init__()
|
|
|
|
| 87 |
query = self.w_q(q)
|
| 88 |
key = self.w_k(k)
|
| 89 |
value = self.w_v(v)
|
| 90 |
+
query = query.view(query.shape[0], query.shape[1], self.h, self.d_k).transpose(
|
| 91 |
+
1, 2
|
| 92 |
+
)
|
| 93 |
key = key.view(key.shape[0], key.shape[1], self.h, self.d_k).transpose(1, 2)
|
| 94 |
+
value = value.view(value.shape[0], value.shape[1], self.h, self.d_k).transpose(
|
| 95 |
+
1, 2
|
| 96 |
+
)
|
| 97 |
x, self.attention_scores = MHA.attention(query, key, value, mask, self.dropout)
|
| 98 |
x = x.transpose(1, 2).contiguous().view(x.shape[0], -1, self.h * self.d_k)
|
| 99 |
return self.w_o(x)
|
| 100 |
|
| 101 |
+
|
| 102 |
class SkipConnection(nn.Module):
|
| 103 |
def __init__(self, d_model: int, dropout: float):
|
| 104 |
super().__init__()
|
|
|
|
| 108 |
def forward(self, x, sublayer):
|
| 109 |
return x + self.dropout(sublayer(self.norm(x)))
|
| 110 |
|
| 111 |
+
|
| 112 |
class EncoderBlock(nn.Module):
|
| 113 |
+
def __init__(
|
| 114 |
+
self, self_attention: MHA, ffn: FeedForward, d_model: int, dropout: float
|
| 115 |
+
):
|
| 116 |
super().__init__()
|
| 117 |
# Name required by the saved model file
|
| 118 |
self.attention = self_attention
|
| 119 |
self.ffn = ffn
|
| 120 |
# Name required by the saved model file
|
| 121 |
+
self.residual = nn.ModuleList(
|
| 122 |
+
[SkipConnection(d_model, dropout) for _ in range(2)]
|
| 123 |
+
)
|
| 124 |
|
| 125 |
def forward(self, x, src_mask):
|
| 126 |
x = self.residual[0](x, lambda x: self.attention(x, x, x, src_mask))
|
| 127 |
x = self.residual[1](x, self.ffn)
|
| 128 |
return x
|
| 129 |
|
| 130 |
+
|
| 131 |
class Encoder(nn.Module):
|
| 132 |
def __init__(self, d_model: int, layers: nn.ModuleList):
|
| 133 |
super().__init__()
|
|
|
|
| 139 |
x = layer(x, mask)
|
| 140 |
return self.norm(x)
|
| 141 |
|
| 142 |
+
|
| 143 |
class DecoderBlock(nn.Module):
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
self_attention: MHA,
|
| 147 |
+
cross_attention: MHA,
|
| 148 |
+
ffn: FeedForward,
|
| 149 |
+
d_model: int,
|
| 150 |
+
dropout: float,
|
| 151 |
+
):
|
| 152 |
super().__init__()
|
| 153 |
# Name required by the saved model file
|
| 154 |
self.self_attention = self_attention
|
| 155 |
self.cross_attention = cross_attention
|
| 156 |
self.ffn = ffn
|
| 157 |
# Name required by the saved model file
|
| 158 |
+
self.residual = nn.ModuleList(
|
| 159 |
+
[SkipConnection(d_model, dropout) for _ in range(3)]
|
| 160 |
+
)
|
| 161 |
|
| 162 |
def forward(self, x, encoder_output, src_mask, trg_mask):
|
| 163 |
x = self.residual[0](x, lambda x: self.self_attention(x, x, x, trg_mask))
|
| 164 |
+
x = self.residual[1](
|
| 165 |
+
x,
|
| 166 |
+
lambda x: self.cross_attention(x, encoder_output, encoder_output, src_mask),
|
| 167 |
+
)
|
| 168 |
x = self.residual[2](x, self.ffn)
|
| 169 |
return x
|
| 170 |
|
| 171 |
+
|
| 172 |
class Decoder(nn.Module):
|
| 173 |
def __init__(self, d_model: int, layers: nn.ModuleList):
|
| 174 |
super().__init__()
|
|
|
|
| 180 |
x = layer(x, encoder_output, src_mask, trg_mask)
|
| 181 |
return self.norm(x)
|
| 182 |
|
| 183 |
+
|
| 184 |
class Output(nn.Module):
|
| 185 |
def __init__(self, d_model: int, vocab_size: int):
|
| 186 |
super().__init__()
|
|
|
|
| 189 |
def forward(self, x):
|
| 190 |
return self.proj(x)
|
| 191 |
|
| 192 |
+
|
| 193 |
class Transformer(nn.Module):
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
encoder: Encoder,
|
| 197 |
+
decoder: Decoder,
|
| 198 |
+
src_embed: InputEmbedding,
|
| 199 |
+
trg_embed: InputEmbedding,
|
| 200 |
+
src_pos: PositionalEncoding,
|
| 201 |
+
trg_pos: PositionalEncoding,
|
| 202 |
+
output: Output,
|
| 203 |
+
):
|
| 204 |
super().__init__()
|
| 205 |
self.encoder = encoder
|
| 206 |
self.decoder = decoder
|
|
|
|
| 231 |
for block in self.decoder.layers:
|
| 232 |
attn_scores = block.cross_attention.attention_scores
|
| 233 |
if attn_scores is not None:
|
|
|
|
|
|
|
| 234 |
weights.append(attn_scores.squeeze(0).transpose(-2, -1))
|
| 235 |
return weights
|
| 236 |
|
|
|
|
| 257 |
"cross_attn": cross_weights,
|
| 258 |
}
|
| 259 |
|
| 260 |
+
|
| 261 |
+
def BuildTransformer(
|
| 262 |
+
src_vocab_size: int,
|
| 263 |
+
trg_vocab_size: int,
|
| 264 |
+
src_seq_len: int,
|
| 265 |
+
trg_seq_len: int,
|
| 266 |
+
d_model: int = 512,
|
| 267 |
+
N: int = 6,
|
| 268 |
+
h: int = 8,
|
| 269 |
+
dropout: float = 0.1,
|
| 270 |
+
d_ff: int = 2048,
|
| 271 |
+
) -> Transformer:
|
| 272 |
src_embed = InputEmbedding(d_model, src_vocab_size)
|
| 273 |
trg_embed = InputEmbedding(d_model, trg_vocab_size)
|
| 274 |
src_pos = PositionalEncoding(d_model, src_seq_len, dropout)
|
|
|
|
| 284 |
decoder_self_attention = MHA(d_model, h, dropout)
|
| 285 |
cross_attention = MHA(d_model, h, dropout)
|
| 286 |
ffn = FeedForward(d_model, d_ff, dropout)
|
| 287 |
+
decoder_block = DecoderBlock(
|
| 288 |
+
decoder_self_attention, cross_attention, ffn, d_model, dropout
|
| 289 |
+
)
|
| 290 |
decoder_blocks.append(decoder_block)
|
| 291 |
encoder = Encoder(d_model, nn.ModuleList(encoder_blocks))
|
| 292 |
decoder = Decoder(d_model, nn.ModuleList(decoder_blocks))
|
| 293 |
projection = Output(d_model, trg_vocab_size)
|
| 294 |
+
transformer = Transformer(
|
| 295 |
+
encoder, decoder, src_embed, trg_embed, src_pos, trg_pos, projection
|
| 296 |
+
)
|
| 297 |
for p in transformer.parameters():
|
| 298 |
if p.dim() > 1:
|
| 299 |
nn.init.xavier_uniform_(p)
|
| 300 |
+
return transformer
|