-
Notifications
You must be signed in to change notification settings - Fork 166
/
train_demo.py
253 lines (233 loc) · 10.2 KB
/
train_demo.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
from fewshot_re_kit.data_loader import get_loader, get_loader_pair, get_loader_unsupervised
from fewshot_re_kit.framework import FewShotREFramework
from fewshot_re_kit.sentence_encoder import CNNSentenceEncoder, BERTSentenceEncoder, BERTPAIRSentenceEncoder, RobertaSentenceEncoder, RobertaPAIRSentenceEncoder
import models
from models.proto import Proto
from models.gnn import GNN
from models.snail import SNAIL
from models.metanet import MetaNet
from models.siamese import Siamese
from models.pair import Pair
from models.d import Discriminator
from models.mtb import Mtb
import sys
import torch
from torch import optim, nn
import numpy as np
import json
import argparse
import os
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--train', default='train_wiki',
help='train file')
parser.add_argument('--val', default='val_wiki',
help='val file')
parser.add_argument('--test', default='test_wiki',
help='test file')
parser.add_argument('--adv', default=None,
help='adv file')
parser.add_argument('--trainN', default=10, type=int,
help='N in train')
parser.add_argument('--N', default=5, type=int,
help='N way')
parser.add_argument('--K', default=5, type=int,
help='K shot')
parser.add_argument('--Q', default=5, type=int,
help='Num of query per class')
parser.add_argument('--batch_size', default=4, type=int,
help='batch size')
parser.add_argument('--train_iter', default=30000, type=int,
help='num of iters in training')
parser.add_argument('--val_iter', default=1000, type=int,
help='num of iters in validation')
parser.add_argument('--test_iter', default=10000, type=int,
help='num of iters in testing')
parser.add_argument('--val_step', default=2000, type=int,
help='val after training how many iters')
parser.add_argument('--model', default='proto',
help='model name')
parser.add_argument('--encoder', default='cnn',
help='encoder: cnn or bert or roberta')
parser.add_argument('--max_length', default=128, type=int,
help='max length')
parser.add_argument('--lr', default=-1, type=float,
help='learning rate')
parser.add_argument('--weight_decay', default=1e-5, type=float,
help='weight decay')
parser.add_argument('--dropout', default=0.0, type=float,
help='dropout rate')
parser.add_argument('--na_rate', default=0, type=int,
help='NA rate (NA = Q * na_rate)')
parser.add_argument('--grad_iter', default=1, type=int,
help='accumulate gradient every x iterations')
parser.add_argument('--optim', default='sgd',
help='sgd / adam / adamw')
parser.add_argument('--hidden_size', default=230, type=int,
help='hidden size')
parser.add_argument('--load_ckpt', default=None,
help='load ckpt')
parser.add_argument('--save_ckpt', default=None,
help='save ckpt')
parser.add_argument('--fp16', action='store_true',
help='use nvidia apex fp16')
parser.add_argument('--only_test', action='store_true',
help='only test')
parser.add_argument('--ckpt_name', type=str, default='',
help='checkpoint name.')
# only for bert / roberta
parser.add_argument('--pair', action='store_true',
help='use pair model')
parser.add_argument('--pretrain_ckpt', default=None,
help='bert / roberta pre-trained checkpoint')
parser.add_argument('--cat_entity_rep', action='store_true',
help='concatenate entity representation as sentence rep')
# only for prototypical networks
parser.add_argument('--dot', action='store_true',
help='use dot instead of L2 distance for proto')
# only for mtb
parser.add_argument('--no_dropout', action='store_true',
help='do not use dropout after BERT (still has dropout in BERT).')
# experiment
parser.add_argument('--mask_entity', action='store_true',
help='mask entity names')
parser.add_argument('--use_sgd_for_bert', action='store_true',
help='use SGD instead of AdamW for BERT.')
opt = parser.parse_args()
trainN = opt.trainN
N = opt.N
K = opt.K
Q = opt.Q
batch_size = opt.batch_size
model_name = opt.model
encoder_name = opt.encoder
max_length = opt.max_length
print("{}-way-{}-shot Few-Shot Relation Classification".format(N, K))
print("model: {}".format(model_name))
print("encoder: {}".format(encoder_name))
print("max_length: {}".format(max_length))
if encoder_name == 'cnn':
try:
glove_mat = np.load('./pretrain/glove/glove_mat.npy')
glove_word2id = json.load(open('./pretrain/glove/glove_word2id.json'))
except:
raise Exception("Cannot find glove files. Run glove/download_glove.sh to download glove files.")
sentence_encoder = CNNSentenceEncoder(
glove_mat,
glove_word2id,
max_length)
elif encoder_name == 'bert':
pretrain_ckpt = opt.pretrain_ckpt or 'bert-base-uncased'
if opt.pair:
sentence_encoder = BERTPAIRSentenceEncoder(
pretrain_ckpt,
max_length)
else:
sentence_encoder = BERTSentenceEncoder(
pretrain_ckpt,
max_length,
cat_entity_rep=opt.cat_entity_rep,
mask_entity=opt.mask_entity)
elif encoder_name == 'roberta':
pretrain_ckpt = opt.pretrain_ckpt or 'roberta-base'
if opt.pair:
sentence_encoder = RobertaPAIRSentenceEncoder(
pretrain_ckpt,
max_length)
else:
sentence_encoder = RobertaSentenceEncoder(
pretrain_ckpt,
max_length,
cat_entity_rep=opt.cat_entity_rep)
else:
raise NotImplementedError
if opt.pair:
train_data_loader = get_loader_pair(opt.train, sentence_encoder,
N=trainN, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size, encoder_name=encoder_name)
val_data_loader = get_loader_pair(opt.val, sentence_encoder,
N=N, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size, encoder_name=encoder_name)
test_data_loader = get_loader_pair(opt.test, sentence_encoder,
N=N, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size, encoder_name=encoder_name)
else:
train_data_loader = get_loader(opt.train, sentence_encoder,
N=trainN, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size)
val_data_loader = get_loader(opt.val, sentence_encoder,
N=N, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size)
test_data_loader = get_loader(opt.test, sentence_encoder,
N=N, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size)
if opt.adv:
adv_data_loader = get_loader_unsupervised(opt.adv, sentence_encoder,
N=trainN, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size)
if opt.optim == 'sgd':
pytorch_optim = optim.SGD
elif opt.optim == 'adam':
pytorch_optim = optim.Adam
elif opt.optim == 'adamw':
from transformers import AdamW
pytorch_optim = AdamW
else:
raise NotImplementedError
if opt.adv:
d = Discriminator(opt.hidden_size)
framework = FewShotREFramework(train_data_loader, val_data_loader, test_data_loader, adv_data_loader, adv=opt.adv, d=d)
else:
framework = FewShotREFramework(train_data_loader, val_data_loader, test_data_loader)
prefix = '-'.join([model_name, encoder_name, opt.train, opt.val, str(N), str(K)])
if opt.adv is not None:
prefix += '-adv_' + opt.adv
if opt.na_rate != 0:
prefix += '-na{}'.format(opt.na_rate)
if opt.dot:
prefix += '-dot'
if opt.cat_entity_rep:
prefix += '-catentity'
if len(opt.ckpt_name) > 0:
prefix += '-' + opt.ckpt_name
if model_name == 'proto':
model = Proto(sentence_encoder, dot=opt.dot)
elif model_name == 'gnn':
model = GNN(sentence_encoder, N, hidden_size=opt.hidden_size)
elif model_name == 'snail':
model = SNAIL(sentence_encoder, N, K, hidden_size=opt.hidden_size)
elif model_name == 'metanet':
model = MetaNet(N, K, sentence_encoder.embedding, max_length)
elif model_name == 'siamese':
model = Siamese(sentence_encoder, hidden_size=opt.hidden_size, dropout=opt.dropout)
elif model_name == 'pair':
model = Pair(sentence_encoder, hidden_size=opt.hidden_size)
elif model_name == 'mtb':
model = Mtb(sentence_encoder, use_dropout=not opt.no_dropout)
else:
raise NotImplementedError
if not os.path.exists('checkpoint'):
os.mkdir('checkpoint')
ckpt = 'checkpoint/{}.pth.tar'.format(prefix)
if opt.save_ckpt:
ckpt = opt.save_ckpt
if torch.cuda.is_available():
model.cuda()
if not opt.only_test:
if encoder_name in ['bert', 'roberta']:
bert_optim = True
else:
bert_optim = False
if opt.lr == -1:
if bert_optim:
opt.lr = 2e-5
else:
opt.lr = 1e-1
opt.train_iter = opt.train_iter * opt.grad_iter
framework.train(model, prefix, batch_size, trainN, N, K, Q,
pytorch_optim=pytorch_optim, load_ckpt=opt.load_ckpt, save_ckpt=ckpt,
na_rate=opt.na_rate, val_step=opt.val_step, fp16=opt.fp16, pair=opt.pair,
train_iter=opt.train_iter, val_iter=opt.val_iter, bert_optim=bert_optim,
learning_rate=opt.lr, use_sgd_for_bert=opt.use_sgd_for_bert, grad_iter=opt.grad_iter)
else:
ckpt = opt.load_ckpt
if ckpt is None:
print("Warning: --load_ckpt is not specified. Will load Hugginface pre-trained checkpoint.")
ckpt = 'none'
acc = framework.eval(model, batch_size, N, K, Q, opt.test_iter, na_rate=opt.na_rate, ckpt=ckpt, pair=opt.pair)
print("RESULT: %.2f" % (acc * 100))
if __name__ == "__main__":
main()