forked from Kyubyong/msg_reply
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
37 lines (30 loc) · 1.04 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import torch
import torch.nn as nn
from pytorch_pretrained_bert import BertForSequenceClassification
from hparams import hp
class Net(nn.Module):
def __init__(self, n_classes):
super().__init__()
self.bert = BertForSequenceClassification.from_pretrained('bert-base-uncased',
num_labels=n_classes)
self.softmax = nn.Softmax(-1)
def forward(self, x):
'''
x: (N, T). int64
Returns
logits: (N, n_classes)
y_hat: (N, n_candidates)
y_hat_prob: (N, n_candidates)
'''
if self.training:
self.bert.train()
logits = self.bert(x)
else:
self.bert.eval()
with torch.no_grad():
logits = self.bert(x)
activated = self.softmax(logits)
y_hat_prob, y_hat = activated.sort(-1, descending=True)
y_hat_prob = y_hat_prob[:, :hp.n_candidates]
y_hat = y_hat[:, :hp.n_candidates]
return logits, y_hat, y_hat_prob