forked from maum-ai/pnlp-mixer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
189 lines (166 loc) · 6.9 KB
/
run.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
from dataset import PnlpMixerDataModule
from model import PnlpMixerSeqCls, PnlpMixerTokenCls
from omegaconf import OmegaConf
from omegaconf.dictconfig import DictConfig
from typing import Any, Dict, List
import argparse
import numpy as np
import torch
import torch.nn.functional as F
import pytorch_lightning as pl
class PnlpMixerSeqClsTrainModule(pl.LightningModule):
def __init__(self, optimizer_cfg: DictConfig, model_cfg: DictConfig, **kwargs):
super(PnlpMixerSeqClsTrainModule, self).__init__(**kwargs)
self.optimizer_cfg = optimizer_cfg
self.model = PnlpMixerSeqCls(
model_cfg.bottleneck,
model_cfg.mixer,
model_cfg.sequence_cls,
)
def shared_step(self, batch):
inputs = batch['inputs']
targets = batch['targets']
logits = self.model(inputs)
loss = F.cross_entropy(logits, targets)
corr = torch.sum(logits.argmax(dim=-1) == targets)
all = logits.size(0)
return {
'loss': loss,
'corr': corr,
'all': all
}
def compute_accuracy(self, outputs: List[Dict[str, Any]]):
corr = 0
all = 0
for output in outputs:
corr += output['corr']
all += output['all']
return {
'acc': corr / all,
}
def training_step(self, batch, batch_idx):
results = self.shared_step(batch)
self.log('train_loss', results['loss'], on_step=True, on_epoch=True, prog_bar=True, logger=True)
return results
def training_epoch_end(self, outputs):
accuracy = self.compute_accuracy(outputs)
self.log('train_acc', accuracy['acc'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
def validation_step(self, batch, batch_idx):
results = self.shared_step(batch)
self.log('val_loss', results['loss'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
return results
def validation_epoch_end(self, outputs):
accuracy = self.compute_accuracy(outputs)
self.log('val_acc', accuracy['acc'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
def test_step(self, batch, batch_idx):
results = self.shared_step(batch)
self.log('test_loss', results['loss'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
return results
def test_epoch_end(self, outputs):
accuracy = self.compute_accuracy(outputs)
self.log('test_acc', accuracy['acc'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
def configure_optimizers(self):
optimizer_cfg = self.optimizer_cfg
optimizer = torch.optim.Adam(self.parameters(), **optimizer_cfg)
return optimizer
class PnlpMixerTokenClsTrainModule(pl.LightningModule):
def __init__(self, optimizer_cfg: DictConfig, model_cfg: DictConfig, **kwargs):
super(PnlpMixerTokenClsTrainModule, self).__init__(**kwargs)
self.optimizer_cfg = optimizer_cfg
self.model = PnlpMixerTokenCls(
model_cfg.bottleneck,
model_cfg.mixer,
model_cfg.token_cls,
)
def common_step(self, batch):
inputs = batch['inputs']
targets = batch['targets']
logits = self.model(inputs)
loss = F.cross_entropy(logits.transpose(-1, -2), targets, ignore_index=-1)
corr = torch.sum(torch.logical_and(logits.argmax(dim=-1) == targets, targets > 0))
all = torch.sum(targets > 0)
return {
'loss': loss,
'corr': corr,
'all': all,
}
def compute_accuracy(self, outputs: List[Dict[str, Any]]):
corr = 0
all = 0
for output in outputs:
corr += output['corr']
all += output['all']
return {
'acc': corr / all
}
def training_step(self, batch, batch_idx):
results = self.common_step(batch)
self.log('train_loss', results['loss'], on_step=True, on_epoch=True, prog_bar=True, logger=True)
return results
def training_epoch_end(self, outputs):
accuracy = self.compute_accuracy(outputs)
self.log('train_acc', accuracy['acc'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
def validation_step(self, batch, batch_idx):
results = self.common_step(batch)
self.log('val_loss', results['loss'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
return results
def validation_epoch_end(self, outputs):
accuracy = self.compute_accuracy(outputs)
self.log('val_acc', accuracy['acc'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
def test_step(self, batch, batch_idx):
results = self.common_step(batch)
self.log('test_loss', results['loss'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
return results
def test_epoch_end(self, outputs):
accuracy = self.compute_accuracy(outputs)
self.log('test_acc', accuracy['acc'], on_step=False, on_epoch=True, prog_bar=True, logger=True)
def configure_optimizers(self):
optimizer_cfg = self.optimizer_cfg
optimizer = torch.optim.Adam(self.parameters(), **optimizer_cfg)
return optimizer
def parse_args():
args = argparse.ArgumentParser()
args.add_argument('-c', '--cfg', type=str)
args.add_argument('-n', '--name', type=str)
args.add_argument('-p', '--ckpt', type=str)
args.add_argument('-m', '--mode', type=str, default='train')
return args.parse_args()
def get_module_cls(type: str):
if type == 'mtop':
return PnlpMixerTokenClsTrainModule
if type == 'matis' or type == 'imdb':
return PnlpMixerSeqClsTrainModule
if __name__ == '__main__':
args = parse_args()
cfg = OmegaConf.load(args.cfg)
vocab_cfg = cfg.vocab
train_cfg = cfg.train
model_cfg = cfg.model
module_cls = get_module_cls(train_cfg.dataset_type)
if args.ckpt:
train_module = module_cls.load_from_checkpoint(args.ckpt, optimizer_cfg=train_cfg.optimizer, model_cfg=model_cfg)
else:
train_module = module_cls(train_cfg.optimizer, model_cfg)
data_module = PnlpMixerDataModule(cfg.vocab, train_cfg, model_cfg.projection)
trainer = pl.Trainer(
# accelerator='ddp',
# amp_backend='native',
# amp_level='O2',
callbacks=[
pl.callbacks.ModelCheckpoint(
monitor='val_acc',
save_last=True,
save_top_k=5,
mode='max'
)
],
checkpoint_callback=True,
gpus=-1,
log_every_n_steps=train_cfg.log_interval_steps,
logger=pl.loggers.TensorBoardLogger(train_cfg.tensorboard_path, args.name),
max_epochs=train_cfg.epochs,
)
if args.mode == 'train':
trainer.fit(train_module, data_module)
if args.mode == 'test':
trainer.test(train_module, data_module)