-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtrain_object_text.py
169 lines (134 loc) · 7.7 KB
/
train_object_text.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
import numpy as np
import torch
import torch.nn as nn
from functools import partial
from torch.utils.tensorboard import SummaryWriter
from torch.utils import data
import argparse
import os
import sys
sys.path.append("../")
from utils.logger import LOGGER
from train_template import TrainerTemplate
from data.object_text_dataset import ObjectTextDataset
from text_based.model import TransformerClassificationHead, MODEL_DICT
from utils.optim_utils import get_optimizer
class TrainerObjectText(TrainerTemplate):
def init_model(self):
base_model = self.config['model']['class'].from_pretrained(self.config['model']['pretrain'])
if self.config['num_layers_freeze'] > 0:
for n, p in base_model.named_parameters():
if n.startswith("encoder.layer"):
layer_num = int(n.split(".")[2]) # encoder.layer.##...
if layer_num < self.config['num_layers_freeze']:
print("Freezing %s..." % n)
p.requires_grad = False
self.model = TransformerClassificationHead(
num_layers=1,
hidden_dim=512,
act_fn=nn.GELU(),
base_model=base_model,
use_pretrained_pool=False,
dropout=0.5,
num_classes=1)
def load_model(self):
# Load pretrained model
if self.model_file:
checkpoint = torch.load(self.model_file)
else:
checkpoint = {}
self.model.load_state_dict(checkpoint['model_state_dict'])
def init_optimizer(self):
def group_param_func(named_params):
base = {'params': [(n,p) for n,p in named_params if n.startswith("base_model")], "lr": config["lr"]}
head = {'params': [(n,p) for n,p in named_params if not n.startswith("base_model")], "lr": config["lr_head"]}
return [head, base]
self.optimizer = get_optimizer(self.model, self.config, group_param_func=group_param_func)
def train_iter_step(self):
tokenized_text, self.batch_label = self.batch
self.batch_label = self.batch_label.to(self.device)
# Text input
tokenized_text = {key: tokenized_text[key].to(self.device) for key in tokenized_text}
self.preds = self.model(**tokenized_text)
self.calculate_loss(self.preds, self.batch_label, grad_step=True)
def eval_iter_step(self, iters, batch, test):
tokenized_text, batch_label = batch
batch_label = batch_label.to(self.device)
# Forward pass
tokenized_text = {key: tokenized_text[key].to(self.device) for key in tokenized_text}
preds = self.model(**tokenized_text)
self.calculate_loss(preds, batch_label, grad_step=False)
def test_iter_step(self, batch):
tokenized_text, batch_label = batch
batch_label = batch_label.to(self.device)
# Forward pass
tokenized_text = {key: tokenized_text[key].to(self.device) for key in tokenized_text}
preds = self.model(**tokenized_text)
return preds.squeeze()
if __name__ == '__main__':
defaults = {
'lr': 5e-5,
'warmup_steps': 200,
'scheduler': 'warmup_cosine',
'optimizer': 'adamw',
'log_every': 50,
'max_epoch': 8,
'batch_size': 16
}
parser = argparse.ArgumentParser()
TrainerTemplate.add_default_argparse(parser, defaults=defaults)
#### Pre-processing Params ####
parser.add_argument('--max_txt_len', type=int, default=256,
help='max number of tokens in text (BERT BPE)')
parser.add_argument('--model', type=str, default="BERT",
help='Name of the model to use (BERT, RoBERTa, ELECTRA, ALBERT)')
parser.add_argument('--lr_head', type=float, default=1e-4,
help='Learning rate for the MLP head')
parser.add_argument('--num_layers_freeze', type=int, default=0,
help='Number of layers to freeze in BERT')
parser.add_argument("--join_token", type=str, default="", help="Token used to join the different objects. A space will be added to the entered token.")
parser.add_argument("--threshold_min", type=float, default=0.4, help="Minimum confidence threshold during training")
parser.add_argument("--threshold_max", type=float, default=0.7, help="Maximum confidence threshold during training")
parser.add_argument("--threshold_test", type=float, default=0.6, help="Confidence threshold during testing")
parser.add_argument("--swap_prob", type=float, default=0.1, help="Probability to swap two object positions randomly during training")
args, unparsed = parser.parse_known_args()
if len(unparsed) > 0:
LOGGER.warning("There have been unprocessed parser arguments: " + str(unparsed))
config = args.__dict__
config = TrainerTemplate.preprocess_args(config)
config['model'] = config['model'].lower()
assert config['model'] in MODEL_DICT, "Given model is not known. Please choose between the following: " + str(MODEL_DICT.keys())
config['model'] = MODEL_DICT[config['model']]
# Tokenize
tokenizer = config['model']["tokenizer"].from_pretrained(config['model']['pretrain'])
tokenizer_func = partial(tokenizer, max_length=config['max_txt_len'], padding='longest',
truncation=True, return_tensors='pt')
# Prepare the datasets and iterator for training
shared_kwargs = {"sep_token": tokenizer.sep_token,
"join_token": config["join_token"] + " ",
"text_padding": tokenizer_func,
"object_filepath": "../data/image_objects.npz",
"object_to_text_filepath": "../data/bbox_classes.json"}
train_dataset = ObjectTextDataset(meme_filepath=os.path.join(config['data_path'], 'train.jsonl'),
confidence_threshold=(config["threshold_min"], config["threshold_max"]),
swap_prob=config["swap_prob"],
**shared_kwargs)
val_dataset = ObjectTextDataset(meme_filepath=os.path.join(config['data_path'], 'dev_seen.jsonl'),
confidence_threshold=config["threshold_test"],
swap_prob=0.0,
**shared_kwargs)
test_dataset = ObjectTextDataset(meme_filepath=os.path.join(config['data_path'], 'test_seen.jsonl'),
return_ids=True,
confidence_threshold=config["threshold_test"],
swap_prob=0.0,
**shared_kwargs)
config['train_loader'] = data.DataLoader(train_dataset, batch_size=config['batch_size'], num_workers=config['num_workers'], collate_fn=train_dataset.get_collate_fn(), shuffle=True, drop_last=True, pin_memory=True)
config['val_loader'] = data.DataLoader(val_dataset, batch_size=config['batch_size'], num_workers=config['num_workers'], collate_fn=val_dataset.get_collate_fn())
config['test_loader'] = data.DataLoader(test_dataset, batch_size=config['batch_size'], num_workers=config['num_workers'], collate_fn=test_dataset.get_collate_fn())
trainer = None
try:
trainer = TrainerObjectText(config)
trainer.train_main()
except KeyboardInterrupt:
LOGGER.warning("Keyboard interrupt by user detected at iteration %i...\nClosing the tensorboard writer!" % ((trainer.iters + trainer.total_iters) if trainer is not None else -1))
config['writer'].close()