forked from vturrisi/solo-learn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_pretrain.py
228 lines (193 loc) · 7.85 KB
/
main_pretrain.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
# Copyright 2022 solo-learn development team.
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies
# or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import os
from pprint import pprint
from pytorch_lightning import Trainer, seed_everything
from pytorch_lightning.callbacks import LearningRateMonitor
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.strategies.ddp import DDPStrategy
from solo.args.setup import parse_args_pretrain
from solo.methods import METHODS
from solo.utils.auto_resumer import AutoResumer
try:
from solo.utils.dali_dataloader import PretrainDALIDataModule
except ImportError:
_dali_avaliable = False
else:
_dali_avaliable = True
try:
from solo.utils.auto_umap import AutoUMAP
except ImportError:
_umap_available = False
else:
_umap_available = True
from solo.utils.checkpointer import Checkpointer
from solo.utils.classification_dataloader import prepare_data as prepare_data_classification
from solo.utils.misc import make_contiguous
from solo.utils.pretrain_dataloader import (
prepare_dataloader,
prepare_datasets,
prepare_n_crop_transform,
prepare_transform,
)
def main():
seed_everything(5)
args = parse_args_pretrain()
assert args.method in METHODS, f"Choose from {METHODS.keys()}"
if args.num_large_crops != 2:
assert args.method == "wmse"
model = METHODS[args.method](**args.__dict__)
make_contiguous(model)
# validation dataloader for when it is available
if args.dataset == "custom" and (args.no_labels or args.val_data_path is None):
val_loader = None
elif args.dataset in ["imagenet100", "imagenet"] and (args.val_data_path is None):
val_loader = None
else:
if args.data_format == "dali":
val_data_format = "image_folder"
else:
val_data_format = args.data_format
_, val_loader = prepare_data_classification(
args.dataset,
train_data_path=args.train_data_path,
val_data_path=args.val_data_path,
data_format=val_data_format,
batch_size=args.batch_size,
num_workers=args.num_workers,
)
# pretrain dataloader
if args.data_format == "dali":
assert _dali_avaliable, "Dali is not avaiable, please install it first with [dali]."
dali_datamodule = PretrainDALIDataModule(
dataset=args.dataset,
train_data_path=args.train_data_path,
unique_augs=args.unique_augs,
transform_kwargs=args.transform_kwargs,
num_crops_per_aug=args.num_crops_per_aug,
num_large_crops=args.num_large_crops,
num_small_crops=args.num_small_crops,
num_workers=args.num_workers,
batch_size=args.batch_size,
no_labels=args.no_labels,
data_fraction=args.data_fraction,
dali_device=args.dali_device,
encode_indexes_into_labels=args.encode_indexes_into_labels,
)
dali_datamodule.val_dataloader = lambda: val_loader
else:
transform_kwargs = (
args.transform_kwargs if args.unique_augs > 1 else [args.transform_kwargs]
)
transform = prepare_n_crop_transform(
[prepare_transform(args.dataset, **kwargs) for kwargs in transform_kwargs],
num_crops_per_aug=args.num_crops_per_aug,
)
if args.debug_augmentations:
print("Transforms:")
pprint(transform)
train_dataset = prepare_datasets(
args.dataset,
transform,
train_data_path=args.train_data_path,
data_format=args.data_format,
no_labels=args.no_labels,
data_fraction=args.data_fraction,
)
train_loader = prepare_dataloader(
train_dataset, batch_size=args.batch_size, num_workers=args.num_workers
)
# 1.7 will deprecate resume_from_checkpoint, but for the moment
# the argument is the same, but we need to pass it as ckpt_path to trainer.fit
ckpt_path, wandb_run_id = None, None
if args.auto_resume and args.resume_from_checkpoint is None:
auto_resumer = AutoResumer(
checkpoint_dir=os.path.join(args.checkpoint_dir, args.method),
max_hours=args.auto_resumer_max_hours,
)
resume_from_checkpoint, wandb_run_id = auto_resumer.find_checkpoint(args)
if resume_from_checkpoint is not None:
print(
"Resuming from previous checkpoint that matches specifications:",
f"'{resume_from_checkpoint}'",
)
ckpt_path = resume_from_checkpoint
elif args.resume_from_checkpoint is not None:
ckpt_path = args.resume_from_checkpoint
del args.resume_from_checkpoint
callbacks = []
if args.save_checkpoint:
# save checkpoint on last epoch only
ckpt = Checkpointer(
args,
logdir=os.path.join(args.checkpoint_dir, args.method),
frequency=args.checkpoint_frequency,
)
callbacks.append(ckpt)
if args.auto_umap:
assert (
_umap_available
), "UMAP is not currently avaiable, please install it first with [umap]."
auto_umap = AutoUMAP(
args,
logdir=os.path.join(args.auto_umap_dir, args.method),
frequency=args.auto_umap_frequency,
)
callbacks.append(auto_umap)
# wandb logging
if args.wandb:
wandb_logger = WandbLogger(
name=args.name,
project=args.project,
entity=args.entity,
offline=args.offline,
resume="allow" if wandb_run_id else None,
id=wandb_run_id,
)
wandb_logger.watch(model, log="gradients", log_freq=100)
wandb_logger.log_hyperparams(args)
# lr logging
lr_monitor = LearningRateMonitor(logging_interval="step")
callbacks.append(lr_monitor)
trainer = Trainer.from_argparse_args(
args,
logger=wandb_logger if args.wandb else None,
callbacks=callbacks,
enable_checkpointing=False,
strategy=DDPStrategy(find_unused_parameters=False)
if args.strategy == "ddp"
else args.strategy,
)
# fix for incompatibility with nvidia-dali and pytorch lightning
# with dali 1.15 (this will be fixed on 1.16)
# https://github.com/Lightning-AI/lightning/issues/12956
try:
from pytorch_lightning.loops import FitLoop
class WorkaroundFitLoop(FitLoop):
@property
def prefetch_batches(self) -> int:
return 1
trainer.fit_loop = WorkaroundFitLoop(
trainer.fit_loop.min_epochs, trainer.fit_loop.max_epochs
)
except:
pass
if args.data_format == "dali":
trainer.fit(model, ckpt_path=ckpt_path, datamodule=dali_datamodule)
else:
trainer.fit(model, train_loader, val_loader, ckpt_path=ckpt_path)
if __name__ == "__main__":
main()