Create modeling_custom.py
Browse files- modeling_custom.py +29 -0
modeling_custom.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch import nn
|
| 2 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 3 |
+
|
| 4 |
+
class GatedRegressionModel(nn.Module, PyTorchModelHubMixin):
|
| 5 |
+
def __init__(self, base_model):
|
| 6 |
+
super().__init__()
|
| 7 |
+
self.base_model = base_model
|
| 8 |
+
self.hidden_dim = 1024
|
| 9 |
+
self.gate_model = nn.ModuleList([
|
| 10 |
+
nn.Linear(self.base_model.pre_classifier.out_features, self.hidden_dim, bias=True),
|
| 11 |
+
nn.GELU(),
|
| 12 |
+
nn.Dropout(p=0.2),
|
| 13 |
+
nn.Linear(self.hidden_dim, self.hidden_dim, bias=True),
|
| 14 |
+
nn.GELU(),
|
| 15 |
+
nn.Dropout(p=0.2),
|
| 16 |
+
nn.Linear(self.hidden_dim, 1, bias=True),
|
| 17 |
+
nn.GELU(),
|
| 18 |
+
nn.Dropout(p=0.2),
|
| 19 |
+
])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def forward(self, input_ids, attention_mask):
|
| 23 |
+
o = self.base_model.distilbert(input_ids=input_ids, attention_mask=attention_mask)[0][:, 0] # encoder-decoder architecture
|
| 24 |
+
o = self.base_model.pre_classifier(o)
|
| 25 |
+
scores = self.base_model.classifier(o)
|
| 26 |
+
gate = o
|
| 27 |
+
for layer in self.gate_model:
|
| 28 |
+
gate = layer(gate)
|
| 29 |
+
return (gate * scores).sum(axis=1)
|