-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.py
144 lines (123 loc) · 5.68 KB
/
models.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from allennlp.models import Model
from allennlp.modules.token_embedders import Embedding
from allennlp.nn.util import get_text_field_mask
from allennlp.training.metrics import CategoricalAccuracy
import copy
import numpy as np
import random
from loss import CrossEntropyLossSmooth
import warnings
warnings.filterwarnings("ignore")
# Simple LSTM classifier that uses the final hidden state to classify Sentiment. Based on AllenNLP
class Detector(Model):
def __init__(self,
model,
encoder,
vocab,
out_dim,
trapdoor=[],
trapdoor_class=0,
training=True,
regularizer=None,
class_weight=None,
train_base_model=False):
super().__init__(vocab, regularizer)
self.trainable = True
self.feature_model = copy.deepcopy(model)
self.feature_model.eval()
for name, param in self.feature_model.named_parameters():
param.requires_grad = train_base_model
self.hidden_dim = self.feature_model.hidden_dim
self.linear = torch.nn.Sequential(torch.nn.Linear(in_features=self.hidden_dim, out_features=out_dim))
self.accuracy = CategoricalAccuracy()
self.trapdoor = trapdoor
self.trapdoor_class = trapdoor_class
self.training = training
self.encoder_outs = []
self.signature = None
self.use_cosine = False
# self.smooth_eps = smooth_eps
self.cos = torch.nn.CosineSimilarity(dim=1, eps=1e-5)
self.loss_function = torch.nn.CrossEntropyLoss(weight=class_weight)
def set_class_weight(self, class_weight):
self.loss_function = torch.nn.CrossEntropyLoss(weight=class_weight)
def forward(self, tokens, label, adv):
encoder_out = self.feature_model(tokens, label, adv, return_feat=True)
if self.trapdoor and self.training:
encoder_out_trap = encoder_out.clone()
encoder_out_trap += self.trapdoor
label_clean = torch.tensor([0]*len(encoder_out)).cuda()
label_trap = torch.tensor([1]*len(encoder_out)).cuda()
encoder_out = torch.cat((encoder_out, encoder_out_trap),0)
label = torch.cat((label_clean, label_trap), 0)
if self.training:
try:
idx = torch.nonzero(label != 0, as_tuple=True)[0]
except:
idx = torch.nonzero(label != 0)
self.encoder_outs.append(encoder_out[idx])
self.signature = torch.mean(torch.cat(self.encoder_outs,0),0).view(-1)
if not self.use_cosine:
logits = self.linear(encoder_out)
output = {"logits": logits, 'encoder_out': encoder_out, 'labels':label}
if label is not None:
self.accuracy(logits, label)
output["loss"] = self.loss_function(logits, label)
else:
bs = len(encoder_out)
logits = self.cos(self.signature.repeat(bs).view(bs,-1), encoder_out)
output = {"logits": logits, 'labels':label}
return output
def get_metrics(self, reset=False):
return {'accuracy': self.accuracy.get_metric(reset)}
class GenericClassifier(Model):
def __init__(self, word_embeddings, encoder, vocab, num_class, trapdoor=[], trapdoor_class=0, training=True, smooth_eps=0.2):
super().__init__(vocab)
self.word_embeddings = word_embeddings
self.encoder = encoder
self.hidden_dim = encoder.get_output_dim()
self.output_dim = num_class
self.linear = torch.nn.Linear(in_features=self.hidden_dim,
out_features=self.output_dim)
self.accuracy = CategoricalAccuracy()
self.trapdoor = trapdoor
self.trapdoor_class = trapdoor_class
self.training = training
self.smooth_eps = smooth_eps
self.loss_function = torch.nn.CrossEntropyLoss(reduction='none')
self.loss_function_smooth = CrossEntropyLossSmooth(smooth_eps=self.smooth_eps)
def set_class_weight(self, class_weight):
self.loss_function = torch.nn.CrossEntropyLoss(weight=class_weight, reduction='none')
self.loss_function_smooth = CrossEntropyLossSmooth(weight=class_weight, smooth_eps=self.smooth_eps)
def forward_from_embedding(self, embeddings, mask, label, adv, return_feat=False):
try:
encoder_out = self.encoder(embeddings, mask)
except Exception as e:
print("ERROR", e)
print("mask", mask)
print("tokens", tokens)
if return_feat:
return encoder_out
logits = self.linear(encoder_out)
output = {"logits": logits, 'encoder_out': encoder_out, 'labels':label, 'embeddings': (embeddings, mask)}
if label is not None:
self.accuracy(logits, label)
coefs = torch.ones(len(label)).float().cuda()
if adv is not None:
adv_idx = torch.nonzero(adv == 1, as_tuple=True)[0]
if len(adv_idx) > 0 and self.smooth_eps < 1.0:
coefs[adv_idx] = self.smooth_eps
loss = self.loss_function(logits, label)
loss = torch.mean(coefs*loss, 0)
output["loss"] = loss
return output
def forward(self, tokens, label, adv, return_feat=False, noise=None):
mask = get_text_field_mask(tokens)
embeddings = self.word_embeddings(tokens)
return self.forward_from_embedding(embeddings, mask, label, adv, return_feat=return_feat)
def get_metrics(self, reset=False):
return {'accuracy': self.accuracy.get_metric(reset)}