-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone_train.py
164 lines (144 loc) · 5.13 KB
/
backbone_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
import click
import lightning.pytorch as pl
from lightning.pytorch.loggers import TensorBoardLogger
from pytorchvideo.transforms import Normalize, Permute, RandAugment
from torch.utils.data import DataLoader
from torchvision.transforms import transforms as T
from torchvision.transforms._transforms_video import ToTensorVideo
from backbone_dataset import SyntaxDataset
from backbone_model import SyntaxLightningModule
@click.command()
@click.option("-r", "--dataset-root", type=click.Path(exists=True), required=True, help="path to dataset.")
@click.option("--fold", type=int, required=True, help="fold number.")
@click.option("-a", "--artery", type=str, required=True, help="{artery} or right artery.")
@click.option("-nc", "--num-classes", type=int, default=1, help="num of classes of dataset.")
@click.option("-b", "--batch-size", type=int, default=16, help="batch size.")
@click.option("-f", "--frames-per-clip", type=int, default=32, help="frame per clip.")
@click.option("-v", "--video-size", type=click.Tuple([int, int]), default=(256, 256), help="frame per clip.")
@click.option("--max-epochs", type=int, default=30, help="max epochs.")
@click.option("--num-workers", type=int, default=16)
@click.option("--fast-dev-run", type=bool, is_flag=True, show_default=True, default=False)
@click.option("--seed", type=int, default=42, help="random seed.")
def main(
dataset_root,
fold,
artery,
num_classes,
batch_size,
frames_per_clip,
video_size,
max_epochs,
num_workers,
fast_dev_run,
seed,
):
print(video_size)
Artery = artery.capitalize()
if artery == "left":
artery_bin = 0
elif artery == "right":
artery_bin = 1
else:
raise ValueError(f"Unknown artery '{artery}'")
pl.seed_everything(seed)
imagenet_mean = [0.485, 0.456, 0.406]
imagenet_std = [0.229, 0.224, 0.225]
train_transform = T.Compose(
[
ToTensorVideo(), # C, T, H, W
Permute(dims=[1, 0, 2, 3]), # T, C, H, W
RandAugment(magnitude=10, num_layers=2),
Permute(dims=[1, 0, 2, 3]), # C, T, H, W
T.RandomChoice([
T.Resize(size=video_size, antialias=False),
T.Resize(size=video_size, antialias=True),
]),
Normalize(mean=imagenet_mean, std=imagenet_std),
]
)
test_transform = T.Compose(
[
ToTensorVideo(),
T.Resize(size=video_size, antialias=True),
Normalize(mean=imagenet_mean, std=imagenet_std),
]
)
train_set = SyntaxDataset(
root=dataset_root,
meta = f"folds/step2_fold{fold:02d}_train.json",
train = True,
length = frames_per_clip,
label = f"syntax_{artery}",
artery_bin=artery_bin,
transform=train_transform,
)
val_set = SyntaxDataset(
root=dataset_root,
meta = f"folds/step2_fold{fold:02d}_eval.json",
train = False,
length = frames_per_clip,
label = f"syntax_{artery}",
artery_bin=artery_bin,
transform=test_transform,
)
train_dataloader = DataLoader(
train_set,
batch_size=batch_size,
num_workers=num_workers,
shuffle=True,
drop_last=True,
pin_memory=True,
)
val_dataloader = DataLoader(
val_set,
batch_size=1, #batch_size,
num_workers=num_workers,
shuffle=False,
drop_last=True,
pin_memory=True,
)
x, y, w, p = next(iter(train_dataloader))
print(x.shape)
# Train last fc
model = SyntaxLightningModule(
num_classes=num_classes,
lr=1e-4,
weight_decay=0.001,
max_epochs=10,
save_path=f"backbone/{artery}_pre_fold{fold:02d}.pt"
)
callbacks = [pl.callbacks.LearningRateMonitor(logging_interval="epoch")]
logger = TensorBoardLogger("back_logs", name=f"{Artery}BinSyntax_R3D_pre_fold{fold:02d}")
trainer = pl.Trainer(
max_epochs=10,
accelerator="auto",
fast_dev_run=fast_dev_run,
logger=logger,
callbacks=callbacks,
log_every_n_steps=10,
)
trainer.fit(model, train_dataloaders=train_dataloader, val_dataloaders=val_dataloader)
trainer.save_checkpoint(f"backbone/{Artery}BinSyntax_R3D_pre_fold{fold:02d}.pt")
# Train all
model = SyntaxLightningModule(
num_classes=num_classes,
lr=1e-4,
weight_decay=0.001,
max_epochs=max_epochs,
weight_path=f"backbone/{artery}_pre_fold{fold:02d}.pt",
save_path=f"backbone/{artery}_post_fold{fold:02d}.pt"
)
callbacks = [pl.callbacks.LearningRateMonitor(logging_interval="epoch")]
logger = TensorBoardLogger("back_logs", name=f"{Artery}BinSyntax_R3D_full_fold{fold:02d}")
trainer = pl.Trainer(
max_epochs=max_epochs,
accelerator="auto",
fast_dev_run=fast_dev_run,
logger=logger,
callbacks=callbacks,
log_every_n_steps=10,
)
trainer.fit(model, train_dataloaders=train_dataloader, val_dataloaders=val_dataloader)
trainer.save_checkpoint(f"backbone/{Artery}BinSyntax_R3D_full_fold{fold:02d}.pt")
if __name__ == "__main__":
main()