-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrain.py
174 lines (144 loc) · 6.24 KB
/
train.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
import json
import os
from pathlib import Path
from typing import Dict
import torch
from torch.cuda.amp import autocast
from torch.nn import CrossEntropyLoss, MSELoss
from tqdm import tqdm
from data.instance_storage import fetch_index_by_instance_class
from utils.directory import mkdir_if_not_exists
from utils.distilbert import fetch_tokenizer
from utils.eval import AverageMeter
from torch.utils.data import DataLoader
from transformers import get_linear_schedule_with_warmup
from torch.optim import AdamW
from arguments import fetch_standard_training_arguments
from data.dataset import fetch_dataset
from models.language_refer import fetch_model
from utils.logging import get_logger
logger = get_logger(__name__)
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
def run_evaluation(args, model, test_dl, device, global_num_iter):
tqdm_eval_iter = tqdm(enumerate(test_dl))
out_matched = []
out_assignment_id = []
count = 0
with torch.no_grad():
for local_eval_num_iter, batch in tqdm_eval_iter:
refined_batch = model.prepare_batch(batch, device)
matched = model.eval_forward(batch=refined_batch)
out_matched.append(matched)
out_assignment_id.append(batch['assignment_ids'])
count += 1
matched = torch.cat(out_matched).detach().cpu()
assignment_id = torch.cat(out_assignment_id).detach().cpu()
matched_dict = {a.item(): m.item() for m, a in zip(matched, assignment_id)}
print('Iteration {}, Accuracy {:7.5f}'.format(
global_num_iter, sum(1 for v in matched_dict.values() if v) / len(matched_dict.values()) * 100))
with open(str(Path(args.output_dir) / 'eval{:06d}.json'.format(global_num_iter)), 'w') as file:
json.dump(matched_dict, file, indent=4)
logger.info('wrote an evaluation file: {}'.format(Path(args.output_dir) / 'eval{:06d}.json'.format(global_num_iter)))
def train():
args = fetch_standard_training_arguments()
device = 'cuda:0'
tokenizer = fetch_tokenizer()
train_dataset = fetch_dataset(
args=args,
split_name='train',
tokenizer=tokenizer)
test_dataset = fetch_dataset(
args=args,
split_name='test',
tokenizer=tokenizer)
model = fetch_model(args=args, tokenizer=tokenizer)
model.train()
model = model.to(device)
index_by_instance_class = fetch_index_by_instance_class(
label_type=args.label_type,
dataset_name=args.dataset_name)
default_task_name = 'viewpoint' if args.use_bbox_annotation_only else 'ref'
task_names = {default_task_name}
criterion_dict = {
default_task_name: CrossEntropyLoss().to(device),
}
weight_dict = {
default_task_name: args.weight_ref,
}
if args.use_clf_loss:
ignore_class = 'otherprop' if args.label_type == 'revised' else 'pad'
task_names.add('cls')
criterion_dict['cls'] = CrossEntropyLoss(ignore_index=index_by_instance_class[ignore_class]).to(device)
weight_dict['cls'] = args.weight_clf
if args.use_tar_loss:
task_names.add('tar')
criterion_dict['tar'] = CrossEntropyLoss().to(device)
weight_dict['tar'] = args.weight_tar
if args.use_pos_loss:
task_names.add('pos')
criterion_dict['pos'] = MSELoss().to(device)
weight_dict['pos'] = args.weight_pos
if args.use_mask_loss:
task_names.add('mask')
criterion_dict['mask'] = CrossEntropyLoss(ignore_index=-100).to(device)
weight_dict['mask'] = args.weight_mask
meter_dict: Dict[str, AverageMeter] = {key: AverageMeter(key) for key in task_names}
scaler = torch.cuda.amp.GradScaler()
optimizer = AdamW(model.parameters(), lr=args.learning_rate)
scheduler = get_linear_schedule_with_warmup(
optimizer,
args.warmup_steps,
args.num_train_epochs * len(train_dataset) // args.per_device_train_batch_size)
train_dl = DataLoader(
train_dataset,
batch_size=args.per_device_train_batch_size,
num_workers=args.dataloader_num_workers,
drop_last=True,
shuffle=True,
pin_memory=True)
test_dl = DataLoader(
test_dataset,
batch_size=args.per_device_eval_batch_size,
num_workers=args.dataloader_num_workers,
drop_last=False,
shuffle=False,
pin_memory=True)
global_num_iter = 0
for num_batch in range(args.num_train_epochs):
tqdm_iter = tqdm(enumerate(train_dl))
for local_num_iter, batch in tqdm_iter:
global_num_iter += 1
refined_batch = model.prepare_batch(batch, device)
optimizer.zero_grad()
with autocast():
logits_dict, gt_dict = model(**refined_batch)
loss_dict = {
name: criterion_dict[name](logits_dict[name], gt_dict[name].to(dtype=torch.long, device=device))
for name in task_names}
for key, value in loss_dict.items():
meter_dict[key].update(value, args.logging_steps)
loss = sum([weight_dict[key] * loss_dict[key] for key in loss_dict.keys()])
if global_num_iter % args.logging_steps == 0:
for key in meter_dict.keys():
meter_dict[key].reset()
tqdm_iter.set_description('loss: {:7.5f}'.format(loss))
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
scheduler.step()
if global_num_iter % args.save_steps == 0:
checkpoint_dir = mkdir_if_not_exists(
Path(args.output_dir) / 'checkpoint-{:06d}'.format(global_num_iter))
model_path = checkpoint_dir / 'model.pt'
optimizer_path = checkpoint_dir / 'optimizer.pt'
state_path = checkpoint_dir / 'state.pt'
torch.save(model.state_dict(), str(model_path))
torch.save(optimizer.state_dict(), str(optimizer_path))
torch.save({
'num_batch': num_batch,
'local_num_iter': local_num_iter,
'global_num_iter': global_num_iter,
}, str(state_path))
run_evaluation(args, model, test_dl, device, global_num_iter)
if __name__ == '__main__':
train()