Spaces:
Sleeping
Sleeping
Update evo_model.py
Browse files- evo_model.py +39 -20
evo_model.py
CHANGED
|
@@ -1,26 +1,45 @@
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
-
|
| 4 |
|
| 5 |
-
class
|
| 6 |
-
def __init__(self,
|
| 7 |
-
super(
|
| 8 |
-
self.embedding = nn.Embedding(vocab_size, d_model)
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
x = torch.cat([memory_token, x], dim=1)
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
x = self.transformer(x)
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
|
| 5 |
+
class TransformerEncoder(nn.Module):
|
| 6 |
+
def __init__(self, config):
|
| 7 |
+
super().__init__()
|
| 8 |
+
self.embedding = nn.Embedding(config["vocab_size"], config["d_model"])
|
| 9 |
+
encoder_layer = nn.TransformerEncoderLayer(
|
| 10 |
+
d_model=config["d_model"],
|
| 11 |
+
nhead=config["nhead"],
|
| 12 |
+
dim_feedforward=config["ff_dim"],
|
| 13 |
+
dropout=0.1,
|
| 14 |
+
activation="gelu",
|
| 15 |
+
batch_first=True,
|
| 16 |
+
)
|
| 17 |
+
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=config["num_layers"])
|
| 18 |
+
self.memory_token = nn.Parameter(torch.randn(1, 1, config["d_model"]))
|
| 19 |
+
self.memory_proj = nn.Linear(config["d_model"], config["d_model"])
|
|
|
|
| 20 |
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
x = self.embedding(x)
|
| 23 |
+
B, T, D = x.shape
|
| 24 |
+
memory = self.memory_token.repeat(B, 1, 1)
|
| 25 |
+
x = torch.cat([memory, x], dim=1)
|
| 26 |
x = self.transformer(x)
|
| 27 |
+
memory_out = x[:, 0]
|
| 28 |
+
return self.memory_proj(memory_out)
|
| 29 |
+
|
| 30 |
+
class EvoTransformer(nn.Module):
|
| 31 |
+
def __init__(self):
|
| 32 |
+
super().__init__()
|
| 33 |
+
config = {
|
| 34 |
+
"vocab_size": 30522,
|
| 35 |
+
"d_model": 384,
|
| 36 |
+
"nhead": 6,
|
| 37 |
+
"ff_dim": 1024,
|
| 38 |
+
"num_layers": 6,
|
| 39 |
+
}
|
| 40 |
+
self.encoder = TransformerEncoder(config)
|
| 41 |
+
self.classifier = nn.Linear(config["d_model"], 2)
|
| 42 |
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
x = self.encoder(x)
|
| 45 |
+
return self.classifier(x)
|