-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlightning_main.py
More file actions
284 lines (236 loc) · 10.6 KB
/
Copy pathlightning_main.py
File metadata and controls
284 lines (236 loc) · 10.6 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import os
import traceback
os.environ["NO_ALBUMENTATIONS_UPDATE"] = "1"
from training_utils.lightning_cli_sliding_windows import LightningCLISlidingWindow
from typing import List, TYPE_CHECKING, Union
import submitit
import sys
from algorithms.models import *
from lightning.pytorch.trainer.states import TrainerStatus
from lightning.pytorch.loggers import WandbLogger
import numpy as np
from sklearn.metrics import f1_score, precision_score, recall_score
if TYPE_CHECKING:
from lightning_data_modules.deepfake_detection_datamodule import (
DeepfakeDetectionDatamodule,
)
class CheckpointableTrainingSlidingWindows:
"""
Used to support checkpointing in SLURM (using submitit) when running a multi-window training.
This class is used to run the training in a loop, where each iteration corresponds to a sliding window.
The class is designed to be used with the LightningCLI, which is a command-line interface for PyTorch Lightning.
"""
def __init__(self):
self.experiment_resume_arguments = None
self.cli = None # transient, not stored in the checkpoint
self.trainer = None # transient, not stored in the checkpoint
def __call__(self, args=None, experiment_resume_arguments=None):
cli_args = [] if args is None else args
cli_args = sys.argv[1:] + cli_args
sys.argv = sys.argv[:1]
if experiment_resume_arguments is not None:
self.experiment_resume_arguments = experiment_resume_arguments
else:
self.experiment_resume_arguments = []
self.cli = LightningCLISlidingWindow(
run=True,
args=cli_args + self.experiment_resume_arguments,
save_config_kwargs={"overwrite": True},
)
action = self.cli.subcommand # "fit", "test", "validate", "predict"
is_evaluation = self.cli.is_evaluation
is_multiwindow_evaluation = self.cli.is_multiwindow_evaluation
self._print_timeline(self.cli)
if experiment_resume_arguments is not None:
assert (
experiment_resume_arguments == self.cli.experiment_resume_arguments
), "Experiment resume arguments are not the same as the ones passed to the CLI"
self.experiment_resume_arguments = self.cli.experiment_resume_arguments
experiment_id: Union[int, str] = self.cli.experiment_id
current_window: int = self.cli.window_id
n_timeline_windows: int = len(self.cli.datamodule.windows_timeline)
if is_multiwindow_evaluation:
n_windows = self.cli.count_completed_windows()
if n_windows != n_timeline_windows:
print(
"Note: the evaluation will be done on",
n_windows,
"windows of the",
n_timeline_windows,
"total windows.",
)
else:
print(
"Note: the evaluation will be done on all",
n_timeline_windows,
"windows.",
)
else:
n_windows = n_timeline_windows
# If num_sanity_val_steps was > 0 in the config, let it run the sanity check
# in the first iteration, but not in the next ones (it's quite a waste of time...)
cli_args += ["--trainer.num_sanity_val_steps", "0"]
print()
print("-" * 20, "Experiment ID:", experiment_id, "-" * 20)
print("IMPORTANT: In case of a crash/pause/preemption, you will be able to:")
print("resume this experiment by re-executing the same command and adding")
print("the following arguments to the command line:")
for resume_cli_arg in self.experiment_resume_arguments:
print(resume_cli_arg, end=" ")
print()
success = True
executed_once = False
while (
(is_multiwindow_evaluation and current_window < n_windows)
or (
is_evaluation
and (not is_multiwindow_evaluation)
and (not executed_once)
)
or ((not is_evaluation) and current_window < n_windows)
) and success:
print(f"Running '{action}' on window {current_window}")
executed_once = True
# Create a new CLI object (will be used to obtain the parameters for the next window)
if self.cli is None:
self.cli = LightningCLISlidingWindow(
run=True,
args=cli_args + self.experiment_resume_arguments,
save_config_kwargs={"overwrite": True},
)
assert experiment_id == self.cli.experiment_id
assert current_window == self.cli.window_id
# Keep track of the trainer: it's needed for the checkpointing
# and for the logger
self.trainer = self.cli.trainer
# Actually runs the action (fit, test, validate, predict)
self.cli.proceed_with_subcommand()
success = self.trainer.state.status == TrainerStatus.FINISHED
# If training, we need to mark the current window as completed.
# Needed to make it clear that the current window is done and should not be resumed
# as it were paused due to preemption.
if success:
if self.cli.is_evaluation:
print(
"Evaluation for window",
current_window,
"finished successfully.",
)
else:
print(
"Training for window",
current_window,
"finished successfully.",
)
self.cli.mark_current_window_done(self.trainer.global_step)
current_window += 1
has_wandb = False
for logger in self.trainer.loggers:
logger.finalize("success")
if isinstance(logger, WandbLogger):
has_wandb = True
if has_wandb:
try:
import wandb
wandb.finish(exit_code=0)
except Exception as e:
print("Error while finishing wandb:", e)
pass
try:
prediction_type = (
"validate" if action in {"fit", "validate"} else "test"
)
predictions_file = (
self.cli.window_folder
/ f"predictions_{prediction_type}_all.npz"
)
preds_all = np.load(predictions_file)
labels = preds_all["label"]
preds = preds_all["prediction"]
print("Finding best threshold...")
thr, score = find_best_threshold(
y_true=labels,
y_probs=preds,
metric=f1_score,
)
print("Best threshold (F1):", thr)
print("Best score (F1):", score)
print(
"Precision:",
precision_score(labels, preds >= thr),
)
print(
"Recall:",
recall_score(labels, preds >= thr),
)
print(
"F1 score:",
f1_score(labels, preds >= thr),
)
print(
"Accuracy:",
np.mean(labels == (preds >= thr).astype(int)),
)
threshold_path = self.cli.window_folder / "best_threshold.txt"
with open(threshold_path, "w") as f:
f.write(str(thr))
except Exception as e:
print("Could not get the best threshold.")
traceback.print_exc()
# Release references
self.cli = None
self.trainer = None
else:
print(
"Window",
current_window,
"did not finish successfully. Exiting sliding windows loop.",
)
print("Window loop finished with success =", success)
def checkpoint(
self, args=None, experiment_resume_arguments=None
) -> submitit.helpers.DelayedSubmission:
print("Got checkpoint signal.")
print("The default root dir is", self.trainer.default_root_dir)
if self.cli is not None and self.cli.is_evaluation:
pass
else:
if self.trainer is not None:
hpc_save_path = self.trainer._checkpoint_connector.hpc_save_path(
self.trainer.default_root_dir
)
self.trainer.save_checkpoint(hpc_save_path)
if self.trainer is not None:
# Save to make sure we get all the metrics
for logger in self.trainer.loggers:
logger.finalize("finished")
if experiment_resume_arguments is None:
experiment_resume_arguments = self.experiment_resume_arguments
self.cli = None # Prevent the CLI from being pickled
self.trainer = None # Prevent the trainer from being pickled
self.experiment_resume_arguments = None # No need to keep this
return submitit.helpers.DelayedSubmission(
self, args=args, experiment_resume_arguments=experiment_resume_arguments
) # submits to requeuing
@staticmethod
def _print_timeline(cli: LightningCLISlidingWindow):
datamodule: "DeepfakeDetectionDatamodule" = cli.datamodule
windows: List[List[str]] = (
datamodule.windows_timeline
) # Each sub-list is the list of generator in that window
n_windows = len(windows)
print("Will run training across", n_windows, "sliding windows")
print("Generators order:")
for i, window in enumerate(windows):
print(i, window)
def find_best_threshold(y_true, y_probs, metric=f1_score):
thresholds = np.linspace(0, 1, 1000)
scores = []
for t in thresholds:
y_pred = (y_probs >= t).astype(int)
score = metric(y_true, y_pred)
scores.append(score)
best_index = np.argmax(scores)
return thresholds[best_index], scores[best_index]
if __name__ == "__main__":
CheckpointableTrainingSlidingWindows()()