forked from suprosanna/relationformer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
233 lines (212 loc) · 8.16 KB
/
trainer.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
from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union
import torch
from torch.optim.optimizer import Optimizer
from torch.utils.data import DataLoader
from monai.config import IgniteInfo
from monai.engines.utils import (
GanKeys,
IterationEvents,
default_make_latent,
default_metric_cmp_fn,
default_prepare_batch,
)
from monai.inferers import Inferer, SimpleInferer
from monai.transforms import Transform
from monai.utils import PT_BEFORE_1_7, min_version, optional_import
from monai.utils.enums import CommonKeys as Keys
import os
from torch.nn.functional import interpolate
from monai.engines import SupervisedTrainer
from monai.handlers import LrScheduleHandler, ValidationHandler, StatsHandler, TensorBoardStatsHandler, CheckpointSaver, MeanDice
from monai.transforms import (
Compose,
AsDiscreted,
)
import torch
from torch.nn.utils import clip_grad_norm
from inference import relation_matcher
import gc
if TYPE_CHECKING:
from ignite.engine import Engine, EventEnum
from ignite.metrics import Metric
else:
Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
Metric, _ = optional_import("ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric")
EventEnum, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum")
# define customized trainer
class RelationformerTrainer(SupervisedTrainer):
def __init__(
self,
device: torch.device,
max_epochs: int,
train_data_loader: Union[Iterable, DataLoader],
network: torch.nn.Module,
optimizer: Optimizer,
loss_function: Callable,
epoch_length: Optional[int] = None,
non_blocking: bool = False,
prepare_batch: Callable = default_prepare_batch,
iteration_update: Optional[Callable] = None,
inferer: Optional[Inferer] = None,
postprocessing: Optional[Transform] = None,
key_train_metric: Optional[Dict[str, Metric]] = None,
additional_metrics: Optional[Dict[str, Metric]] = None,
metric_cmp_fn: Callable = default_metric_cmp_fn,
train_handlers: Optional[Sequence] = None,
amp: bool = False,
event_names: Optional[List[Union[str, EventEnum]]] = None,
event_to_attr: Optional[dict] = None,
decollate: bool = True,
optim_set_to_none: bool = False,
**kwargs,
) -> None:
super().__init__(
device=device,
max_epochs=max_epochs,
train_data_loader=train_data_loader,
epoch_length=epoch_length,
non_blocking=non_blocking,
prepare_batch=prepare_batch,
iteration_update=iteration_update,
postprocessing=postprocessing,
key_train_metric=key_train_metric,
additional_metrics=additional_metrics,
metric_cmp_fn=metric_cmp_fn,
train_handlers=train_handlers,
amp=amp,
event_names=event_names,
event_to_attr=event_to_attr,
decollate=decollate,
network = network,
optimizer = optimizer,
loss_function = loss_function,
inferer = SimpleInferer() if inferer is None else inferer,
optim_set_to_none = optim_set_to_none,
)
self.config = kwargs.pop('config')
def _iteration(self, engine, batchdata):
images, nodes, edges = batchdata[0], batchdata[1], batchdata[2]
# # inputs, targets = self.get_batch(batchdata, image_keys=IMAGE_KEYS, label_keys="label")
# # inputs = torch.cat(inputs, 1)
images = images.to(engine.state.device, non_blocking=False)
#segs = segs.to(engine.state.device, non_blocking=False)
nodes = [node.to(engine.state.device, non_blocking=False) for node in nodes]
edges = [edge.to(engine.state.device, non_blocking=False) for edge in edges]
target = {"nodes": nodes, "edges": edges}
self.network.train()
self.optimizer.zero_grad()
h, out = self.network(images)
valid_token = torch.argmax(out['pred_logits'], -1)
# valid_token = torch.sigmoid(nodes_prob[...,3])>0.5
# print('valid_token number', valid_token.sum(1))
# out1 = relation_matcher(h, out, self.network, self.config.MODEL.DECODER.OBJ_TOKEN, self.config.MODEL.DECODER.RLN_TOKEN)
losses = self.loss_function(h, out, target)
# Clip the gradient
# clip_grad_norm_(
# self.network.parameters(),
# max_norm=GRADIENT_CLIP_L2_NORM,
# norm_type=2,
# )
losses['total'].backward()
self.optimizer.step()
gc.collect()
torch.cuda.empty_cache()
return {"images": images, "nodes": nodes, "edges": edges, "loss": losses}
def build_trainer(train_loader, net, loss, optimizer, scheduler, writer,
evaluator, config, device, fp16=False):
"""[summary]
Args:
train_loader ([type]): [description]
net ([type]): [description]
loss ([type]): [description]
optimizer ([type]): [description]
evaluator ([type]): [description]
scheduler ([type]): [description]
max_epochs ([type]): [description]
device ([type]): [description]
Returns:
[type]: [description]
"""
train_handlers = [
LrScheduleHandler(
lr_scheduler=scheduler,
print_lr=True,
epoch_level=False,
),
ValidationHandler(
validator=evaluator,
interval=config.TRAIN.VAL_INTERVAL,
epoch_level=True
),
StatsHandler(
tag_name="train_loss",
output_transform=lambda x: x["loss"]["total"]
),
CheckpointSaver(
save_dir=os.path.join(config.TRAIN.SAVE_PATH, "runs", '%s_%d' % (config.log.exp_name, config.DATA.SEED), 'models'),
save_dict={"net": net, "optimizer": optimizer, "scheduler": scheduler},
save_interval=1,
n_saved=1),
TensorBoardStatsHandler(
writer,
tag_name="classification_loss",
output_transform=lambda x: x["loss"]["class"],
global_epoch_transform=lambda x: scheduler.last_epoch
),
TensorBoardStatsHandler(
writer,
tag_name="node_loss",
output_transform=lambda x: x["loss"]["nodes"],
global_epoch_transform=lambda x: scheduler.last_epoch
),
TensorBoardStatsHandler(
writer,
tag_name="edge_loss",
output_transform=lambda x: x["loss"]["edges"],
global_epoch_transform=lambda x: scheduler.last_epoch
),
TensorBoardStatsHandler(
writer,
tag_name="box_loss",
output_transform=lambda x: x["loss"]["boxes"],
global_epoch_transform=lambda x: scheduler.last_epoch
),
TensorBoardStatsHandler(
writer,
tag_name="card_loss",
output_transform=lambda x: x["loss"]["cards"],
global_epoch_transform=lambda x: scheduler.last_epoch
),
TensorBoardStatsHandler(
writer,
tag_name="total_loss",
output_transform=lambda x: x["loss"]["total"],
global_epoch_transform=lambda x: scheduler.last_epoch
)
]
# train_post_transform = Compose(
# [AsDiscreted(keys=("pred", "label"),
# argmax=(True, False),
# to_onehot=True,
# n_classes=N_CLASS)]
# )
trainer = RelationformerTrainer(
config= config,
device=device,
max_epochs=config.TRAIN.EPOCHS,
train_data_loader=train_loader,
network=net,
optimizer=optimizer,
loss_function=loss,
inferer=SimpleInferer(),
# post_transform=train_post_transform,
# key_train_metric={
# "train_mean_dice": MeanDice(
# include_background=False,
# output_transform=lambda x: (x["pred"], x["label"]),
# )
# },
train_handlers=train_handlers,
# amp=fp16,
)
return trainer