Create custom_model.py
Browse files- custom_model.py +35 -0
custom_model.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# custom_model.py
|
2 |
+
|
3 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
|
7 |
+
class CustomConfig(PretrainedConfig):
|
8 |
+
model_type = "custom_model"
|
9 |
+
|
10 |
+
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, num_labels=2, **kwargs):
|
11 |
+
super().__init__(**kwargs)
|
12 |
+
self.vocab_size = vocab_size
|
13 |
+
self.hidden_size = hidden_size
|
14 |
+
self.num_hidden_layers = num_hidden_layers
|
15 |
+
self.num_attention_heads = num_attention_heads
|
16 |
+
self.num_labels = num_labels
|
17 |
+
|
18 |
+
class CustomModel(PreTrainedModel):
|
19 |
+
config_class = CustomConfig
|
20 |
+
|
21 |
+
def __init__(self, config):
|
22 |
+
super().__init__(config)
|
23 |
+
self.embedding = nn.Embedding(config.vocab_size, config.hidden_size)
|
24 |
+
self.layers = nn.ModuleList([nn.TransformerEncoderLayer(d_model=config.hidden_size, nhead=config.num_attention_heads) for _ in range(config.num_hidden_layers)])
|
25 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
26 |
+
|
27 |
+
self.init_weights()
|
28 |
+
|
29 |
+
def forward(self, input_ids):
|
30 |
+
embeddings = self.embedding(input_ids)
|
31 |
+
x = embeddings
|
32 |
+
for layer in self.layers:
|
33 |
+
x = layer(x)
|
34 |
+
logits = self.classifier(x.mean(dim=1)) # Example: taking the mean of the output as input to the classifier
|
35 |
+
return logits
|