-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathmain.py
346 lines (305 loc) · 11.4 KB
/
main.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# Adapted from Huggingface's transformers library:
# /~https://github.com/allenai/allennlp/
""" Main script. """
import os
import logging
import argparse
import datetime
from collections import Counter
import torch
from torch.nn import CrossEntropyLoss
from transformers import (
BertConfig,
BertTokenizer,
BertForTokenClassification,
BertForSequenceClassification
)
from utils.character_cnn import CharacterIndexer
from modeling.character_bert import CharacterBertModel
from data import load_classification_dataset, load_sequence_labelling_dataset
from utils.misc import set_seed
from utils.data import retokenize, build_features
from utils.training import train, evaluate
from download import MODEL_TO_URL
AVAILABLE_MODELS = list(MODEL_TO_URL.keys()) + ['bert-base-uncased']
def parse_args():
""" Parse command line arguments and initialize experiment. """
parser = argparse.ArgumentParser()
parser.add_argument(
"--task",
type=str,
required=True,
choices=['classification', 'sequence_labelling'],
help="The evaluation task."
)
parser.add_argument(
"--embedding",
type=str,
required=True,
choices=AVAILABLE_MODELS,
help="The model to use."
)
parser.add_argument(
"--do_lower_case",
action="store_true",
help="Whether to apply lowercasing during tokenization."
)
parser.add_argument(
"--train_batch_size",
type=int,
default=1,
help="Batch size to use for training."
)
parser.add_argument(
"--eval_batch_size",
type=int,
default=1,
help="Batch size to use for evaluation."
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of gradient accumulation steps."
)
parser.add_argument(
"--num_train_epochs",
type=int,
default=3,
help="Number of training epochs."
)
parser.add_argument(
"--validation_ratio",
default=0.5, type=float, help="Proportion of training set to use as a validation set.")
parser.add_argument(
"--learning_rate",
default=5e-5, type=float, help="The initial learning rate for Adam.")
parser.add_argument(
"--weight_decay",
default=0.1, type=float, help="Weight decay if we apply some.")
parser.add_argument(
"--warmup_ratio",
default=0.1, type=int, help="Linear warmup over warmup_ratio*total_steps.")
parser.add_argument(
"--adam_epsilon",
default=1e-8, type=float, help="Epsilon for Adam optimizer.")
parser.add_argument(
"--max_grad_norm",
default=1.0, type=float, help="Max gradient norm.")
parser.add_argument(
"--do_train",
action="store_true",
help="Do training & validation."
)
parser.add_argument(
"--do_predict",
action="store_true",
help="Do prediction on the test set."
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="Random seed."
)
args = parser.parse_args()
args.start_time = datetime.datetime.now().strftime('%d-%m-%Y_%Hh%Mm%Ss')
args.output_dir = os.path.join(
'results',
args.task,
args.embedding,
f'{args.start_time}__seed-{args.seed}')
# --------------------------------- INIT ---------------------------------
# Set up logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(filename)s - %(message)s",
datefmt="%d/%m/%Y %H:%M:%S",
level=logging.INFO)
# Check for GPUs
if torch.cuda.is_available():
assert torch.cuda.device_count() == 1 # This script doesn't support multi-gpu
args.device = torch.device("cuda")
logging.info("Using GPU (`%s`)", torch.cuda.get_device_name(0))
else:
args.device = torch.device("cpu")
logging.info("Using CPU")
# Set random seed for reproducibility
set_seed(seed_value=args.seed)
return args
def main(args):
""" Main function. """
# --------------------------------- DATA ---------------------------------
# Tokenizer
logging.disable(logging.INFO)
try:
tokenizer = BertTokenizer.from_pretrained(
os.path.join('pretrained-models', args.embedding),
do_lower_case=args.do_lower_case)
except OSError:
# For CharacterBert models use BertTokenizer.basic_tokenizer for tokenization
# and CharacterIndexer for indexing
tokenizer = BertTokenizer.from_pretrained(
os.path.join('pretrained-models', 'bert-base-uncased'),
do_lower_case=args.do_lower_case)
tokenizer = tokenizer.basic_tokenizer
characters_indexer = CharacterIndexer()
logging.disable(logging.NOTSET)
tokenization_function = tokenizer.tokenize
# Pre-processsing: apply basic tokenization (both) then split into wordpieces (BERT only)
data = {}
for split in ['train', 'test']:
if args.task == 'classification':
func = load_classification_dataset
elif args.task == 'sequence_labelling':
func = load_sequence_labelling_dataset
else:
raise NotImplementedError
data[split] = func(step=split, do_lower_case=args.do_lower_case)
retokenize(data[split], tokenization_function)
logging.info('Splitting training data into train / validation sets...')
data['validation'] = data['train'][:int(args.validation_ratio * len(data['train']))]
data['train'] = data['train'][int(args.validation_ratio * len(data['train'])):]
logging.info('New number of training sequences: %d', len(data['train']))
logging.info('New number of validation sequences: %d', len(data['validation']))
# Count target labels or classes
if args.task == 'classification':
counter_all = Counter(
[example.label for example in data['train'] + data['validation'] + data['test']])
counter = Counter(
[example.label for example in data['train']])
# Maximum sequence length is either 512 or maximum token sequence length + 3
max_seq_length = min(
512,
3 + max(
map(len, [
e.tokens_a if e.tokens_b is None else e.tokens_a + e.tokens_b
for e in data['train'] + data['validation'] + data['test']
])
)
)
elif args.task == 'sequence_labelling':
counter_all = Counter(
[label
for example in data['train'] + data['validation'] + data['test']
for label in example.label_sequence])
counter = Counter(
[label
for example in data['train']
for label in example.label_sequence])
# Maximum sequence length is either 512 or maximum token sequence length + 5
max_seq_length = min(
512,
5 + max(
map(len, [
e.token_sequence
for e in data['train'] + data['validation'] + data['test']
])
)
)
else:
raise NotImplementedError
labels = sorted(counter_all.keys())
num_labels = len(labels)
logging.info("Goal: predict the following labels")
for i, label in enumerate(labels):
logging.info("* %s: %s (count: %s)", label, i, counter[label])
# Input features: list[token indices] (BERT) or list[list[character indices]] (CharacterBERT)
pad_token_id = None
if 'character' not in args.embedding:
pad_token_id = tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0]
pad_token_label_id = None
if args.task == 'sequence_labelling':
pad_token_label_id = CrossEntropyLoss().ignore_index
dataset = {}
logging.info("Maximum sequence lenght: %s", max_seq_length)
for split in data:
dataset[split] = build_features(
args,
split=split,
tokenizer=tokenizer \
if 'character' not in args.embedding \
else characters_indexer,
examples=data[split],
labels=labels,
pad_token_id=pad_token_id,
pad_token_label_id=pad_token_label_id,
max_seq_length=max_seq_length)
del data # Not used anymore
# --------------------------------- MODEL ---------------------------------
# Initialize model
if args.task == 'classification':
model = BertForSequenceClassification
elif args.task == 'sequence_labelling':
model = BertForTokenClassification
else:
raise NotImplementedError
logging.info('Loading `%s` model...', args.embedding)
logging.disable(logging.INFO)
config = BertConfig.from_pretrained(
os.path.join('pretrained-models', args.embedding),
num_labels=num_labels)
if 'character' not in args.embedding:
model = model.from_pretrained(
os.path.join('pretrained-models', args.embedding),
config=config)
else:
model = model(config=config)
model.bert = CharacterBertModel.from_pretrained(
os.path.join('pretrained-models', args.embedding),
config=config)
logging.disable(logging.NOTSET)
model.to(args.device)
logging.info('Model:\n%s', model)
# ------------------------------ TRAIN / EVAL ------------------------------
# Log args
logging.info('Using the following arguments for training:')
for k, v in vars(args).items():
logging.info("* %s: %s", k, v)
# Training
if args.do_train:
global_step, train_loss, best_val_metric, best_val_epoch = train(
args=args,
dataset=dataset,
model=model,
tokenizer=tokenizer,
labels=labels,
pad_token_label_id=pad_token_label_id
)
logging.info("global_step = %s, average training loss = %s", global_step, train_loss)
logging.info("Best performance: Epoch=%d, Value=%s", best_val_epoch, best_val_metric)
# Evaluation on test data
if args.do_predict:
# Load best model
if args.task == 'classification':
model = BertForSequenceClassification
elif args.task == 'sequence_labelling':
model = BertForTokenClassification
else:
raise NotImplementedError
logging.disable(logging.INFO)
if 'character' not in args.embedding:
model = model.from_pretrained(args.output_dir)
else:
state_dict = torch.load(
os.path.join(args.output_dir, 'pytorch_model.bin'), map_location='cpu')
model = model(config=config)
model.bert = CharacterBertModel(config=config)
model.load_state_dict(state_dict, strict=True)
logging.disable(logging.NOTSET)
model.to(args.device)
# Compute predictions and metrics
results, _ = evaluate(
args=args,
eval_dataset=dataset["test"],
model=model, labels=labels,
pad_token_label_id=pad_token_label_id
)
# Save metrics
with open(os.path.join(args.output_dir, 'performance_on_test_set.txt'), 'w') as f:
f.write(f'best validation score: {best_val_metric}\n')
f.write(f'best validation epoch: {best_val_epoch}\n')
f.write('--- Performance on test set ---\n')
for k, v in results.items():
f.write(f'{k}: {v}\n')
if __name__ == "__main__":
main(parse_args())