generated from ashleve/lightning-hydra-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcallbacks.py
40 lines (32 loc) · 1.53 KB
/
callbacks.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
import logging
import os
import pickle
from glob import glob
from weakref import proxy
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.utilities.warnings import WarningCache
log = logging.getLogger(__name__)
warning_cache = WarningCache()
class SetFitModelCheckpoint(ModelCheckpoint):
"""This class is created to save the model head, if model_head is sklearn class."""
def _save_checkpoint(self, trainer: "pl.Trainer", filepath: str) -> None:
trainer.save_checkpoint(filepath, self.save_weights_only)
if not trainer.model.is_torch_model_head:
with open(os.path.splitext(filepath)[0] + "_head.pickle", "wb") as p:
pickle.dump(trainer.model.model_head, p)
self._last_global_step_saved = trainer.global_step
# notify loggers
if trainer.is_global_zero:
for logger in trainer.loggers:
logger.after_save_checkpoint(proxy(self))
def on_fit_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule"):
if not trainer.model.is_torch_model_head:
checkpoint_file_names = [
os.path.splitext(filepath)[0]
for filepath in glob(os.path.join(self.dirpath, "*.ckpt"))
]
model_head_paths = glob(os.path.join(self.dirpath, "*.pickle"))
for model_head_path in model_head_paths:
if not model_head_path.replace("_head.pickle", "") in checkpoint_file_names:
os.remove(model_head_path)