callbacks.py 19.6 KB
Newer Older
J
jrzaurin 已提交
1
"""
2 3 4
Code here is mostly based on the code from the torchsample and Keras packages

CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS
J
jrzaurin 已提交
5
"""
6 7 8
import os
import datetime
import warnings
9 10 11
from copy import deepcopy

import numpy as np
12 13
import torch

14
from .wdtypes import *
15

16 17 18 19

def _get_current_time():
    return datetime.datetime.now().strftime("%B %d, %Y - %I:%M%p")

20

21 22 23 24
class CallbackContainer(object):
    """
    Container holding a list of callbacks.
    """
J
jrzaurin 已提交
25 26

    def __init__(self, callbacks: Optional[List] = None, queue_length: int = 10):
27 28 29
        instantiated_callbacks = []
        if callbacks is not None:
            for callback in callbacks:
J
jrzaurin 已提交
30 31 32 33
                if isinstance(callback, type):
                    instantiated_callbacks.append(callback())
                else:
                    instantiated_callbacks.append(callback)
34 35 36 37 38 39 40
        self.callbacks = [c for c in instantiated_callbacks]
        self.queue_length = queue_length

    def set_params(self, params):
        for callback in self.callbacks:
            callback.set_params(params)

J
jrzaurin 已提交
41
    def set_model(self, model: Any):
42 43 44 45
        self.model = model
        for callback in self.callbacks:
            callback.set_model(model)

J
jrzaurin 已提交
46
    def on_epoch_begin(self, epoch: int, logs: Optional[Dict] = None):
47 48 49 50
        logs = logs or {}
        for callback in self.callbacks:
            callback.on_epoch_begin(epoch, logs)

J
jrzaurin 已提交
51
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
52 53 54 55
        logs = logs or {}
        for callback in self.callbacks:
            callback.on_epoch_end(epoch, logs)

J
jrzaurin 已提交
56
    def on_batch_begin(self, batch: int, logs: Optional[Dict] = None):
57 58 59 60
        logs = logs or {}
        for callback in self.callbacks:
            callback.on_batch_begin(batch, logs)

J
jrzaurin 已提交
61
    def on_batch_end(self, batch: int, logs: Optional[Dict] = None):
62 63 64 65
        logs = logs or {}
        for callback in self.callbacks:
            callback.on_batch_end(batch, logs)

J
jrzaurin 已提交
66
    def on_train_begin(self, logs: Optional[Dict] = None):
67
        logs = logs or {}
J
jrzaurin 已提交
68
        logs["start_time"] = _get_current_time()
69 70 71
        for callback in self.callbacks:
            callback.on_train_begin(logs)

J
jrzaurin 已提交
72
    def on_train_end(self, logs: Optional[Dict] = None):
73
        logs = logs or {}
74 75 76
        # logs['final_loss'] = self.model.history.epoch_losses[-1],
        # logs['best_loss'] = min(self.model.history.epoch_losses),
        # logs['stop_time'] = _get_current_time()
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
        for callback in self.callbacks:
            callback.on_train_end(logs)


class Callback(object):
    """
    Abstract base class used to build new callbacks.
    """

    def __init__(self):
        pass

    def set_params(self, params):
        self.params = params

J
jrzaurin 已提交
92
    def set_model(self, model: Any):
93 94
        self.model = model

J
jrzaurin 已提交
95
    def on_epoch_begin(self, epoch: int, logs: Optional[Dict] = None):
96 97
        pass

J
jrzaurin 已提交
98
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
99 100
        pass

J
jrzaurin 已提交
101
    def on_batch_begin(self, batch: int, logs: Optional[Dict] = None):
102 103
        pass

J
jrzaurin 已提交
104
    def on_batch_end(self, batch: int, logs: Optional[Dict] = None):
105 106
        pass

J
jrzaurin 已提交
107
    def on_train_begin(self, logs: Optional[Dict] = None):
108 109
        pass

J
jrzaurin 已提交
110
    def on_train_end(self, logs: Optional[Dict] = None):
111 112 113 114
        pass


class History(Callback):
115
    r"""Callback that records events into a :obj:`History` object.
116

117 118 119
    This callback runs by default within :obj:`WideDeep`. See
    :class:`pytorch_widedeep.models.wide_deep.WideDeep`. Documentation ss
    included here for completion.
120 121
    """

J
jrzaurin 已提交
122
    def on_train_begin(self, logs: Optional[Dict] = None):
J
jrzaurin 已提交
123 124
        self.epoch: List[int] = []
        self._history: Dict[str, List[float]] = {}
125

J
jrzaurin 已提交
126
    def on_epoch_begin(self, epoch: int, logs: Optional[Dict] = None):
127 128 129 130 131
        # avoid mutation during epoch run
        logs = deepcopy(logs) or {}
        for k, v in logs.items():
            self._history.setdefault(k, []).append(v)

J
jrzaurin 已提交
132
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
133 134 135
        logs = logs or {}
        self.epoch.append(epoch)
        for k, v in logs.items():
J
jrzaurin 已提交
136
            self._history.setdefault(k, []).append(v)
137 138


139
class LRHistory(Callback):
140 141 142 143 144
    r"""Saves the learning rates during training.

    The saving procedure is a bit convoluted given the fact that non-cyclic
    learning rates and cyclic learning rates are called at different stages
    during training.
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

    Parameters
    ----------
    n_epochs: int
        number of epochs durint training. This is neccesary because different
        logging routines for different schedulers are used on epoch begin and
        on epoch end

    Examples
    --------

    Callbacks are passed as input parameters when calling ``compile``. see
    :class:`pytorch_widedeep.models.wide_deep.WideDeep`

    >>> # Do not run
    >>> model.compile(callbacks=[LRHistory(n_epochs=10)])
161
    """
J
jrzaurin 已提交
162

163 164 165
    def __init__(self, n_epochs):
        super(LRHistory, self).__init__()
        self.n_epochs = n_epochs
166

J
jrzaurin 已提交
167 168
    def on_epoch_begin(self, epoch: int, logs: Optional[Dict] = None):
        if epoch == 0 and self.model.lr_scheduler:
169 170
            # If is the first epoch and we use a scheduler, define the
            # lr_history Dict and save
171
            self.model.lr_history = {}
J
jrzaurin 已提交
172
            if self.model.lr_scheduler.__class__.__name__ == "MultipleLRScheduler":
173 174
                # if we use multiple schedulers, we save the learning rate for
                # each param_group of the optimizer.
175
                for model_name, opt in self.model.optimizer._optimizers.items():
176 177 178
                    if model_name in self.model.lr_scheduler._schedulers:
                        for group_idx, group in enumerate(opt.param_groups):
                            self.model.lr_history.setdefault(
J
jrzaurin 已提交
179 180
                                ("_").join(["lr", model_name, str(group_idx)]), []
                            ).append(group["lr"])
181
            elif not self.model.cyclic:
182 183
                # if we use one lr_scheduler and is not cyclic, save the
                # learning rate for each param_group of the optimizer.
184 185
                for group_idx, group in enumerate(self.model.optimizer.param_groups):
                    self.model.lr_history.setdefault(
J
jrzaurin 已提交
186 187
                        ("_").join(["lr", str(group_idx)]), []
                    ).append(group["lr"])
188

J
jrzaurin 已提交
189
    def on_batch_end(self, batch: int, logs: Optional[Dict] = None):
190
        if self.model.lr_scheduler:
J
jrzaurin 已提交
191
            if self.model.lr_scheduler.__class__.__name__ == "MultipleLRScheduler":
192 193
                # if we use multiple schedulers, we save the learning rate for
                # each param_group of the optimizer IF IS CYCLIC
194
                for model_name, opt in self.model.optimizer._optimizers.items():
195
                    if model_name in self.model.lr_scheduler._schedulers:
J
jrzaurin 已提交
196 197 198 199 200 201
                        if (
                            "cycl"
                            in self.model.lr_scheduler._schedulers[
                                model_name
                            ].__class__.__name__.lower()
                        ):
202 203
                            for group_idx, group in enumerate(opt.param_groups):
                                self.model.lr_history.setdefault(
J
jrzaurin 已提交
204 205
                                    ("_").join(["lr", model_name, str(group_idx)]), []
                                ).append(group["lr"])
206
            elif self.model.cyclic:
207 208
                # if we use one lr_scheduler and IS CYCLIC, save the
                # learning rate for each param_group of the optimizer.
209 210
                for group_idx, group in enumerate(self.model.optimizer.param_groups):
                    self.model.lr_history.setdefault(
J
jrzaurin 已提交
211 212
                        ("_").join(["lr", str(group_idx)]), []
                    ).append(group["lr"])
213

J
jrzaurin 已提交
214 215 216
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
        if epoch != (self.n_epochs - 1) and self.model.lr_scheduler:
            if self.model.lr_scheduler.__class__.__name__ == "MultipleLRScheduler":
217 218
                # if we use multiple schedulers, we save the learning rate for
                # each param_group of the optimizer IF IS NOT CYCLIC
219
                for model_name, opt in self.model.optimizer._optimizers.items():
220
                    if model_name in self.model.lr_scheduler._schedulers:
J
jrzaurin 已提交
221 222 223 224 225 226
                        if (
                            "cycl"
                            not in self.model.lr_scheduler._schedulers[
                                model_name
                            ].__class__.__name__.lower()
                        ):
227 228
                            for group_idx, group in enumerate(opt.param_groups):
                                self.model.lr_history.setdefault(
J
jrzaurin 已提交
229 230
                                    ("_").join(["lr", model_name, str(group_idx)]), []
                                ).append(group["lr"])
231
            elif not self.model.cyclic:
232 233
                # if we use one lr_scheduler and IS NOT CYCLIC, save the
                # learning rate for each param_group of the optimizer.
234 235
                for group_idx, group in enumerate(self.model.optimizer.param_groups):
                    self.model.lr_history.setdefault(
J
jrzaurin 已提交
236 237
                        ("_").join(["lr", str(group_idx)]), []
                    ).append(group["lr"])
238 239


240
class ModelCheckpoint(Callback):
241 242 243
    r"""Saves the model after every epoch.

    This class is almost identical to the corresponding keras class.
244
    Therefore, **credit** to the Keras Team.
245 246 247

    Parameters
    ----------
248
    filepath: str
249
        Full path to save the output weights. It must contain only the root of
250 251 252 253 254 255 256 257 258
        the filenames. Epoch number and ``.pt`` extension (for pytorch) will
        be added. e.g. ``filepath="path/to/output_weights/weights_out"`` And
        the saved files in that directory will be named: ``weights_out_1.pt,
        weights_out_2.pt, ...``
    monitor: str, Default='val_loss'
        quantity to monitor. :obj:`ModelCheckpoint` will infer if this is a
        loss (i.e. contains the str `'loss'`) or a metric (i.e. contains the
        str `'acc'` or starts with `'fmeasure'`).
    verbose:int, Default=0,
259
        verbosity mode
260
    save_best_only: bool, Default=False,
261 262
        the latest best model according to the quantity monitored will not be
        overwritten.
263
    mode: str, Default='auto',
264
        If ``save_best_only=True``, the decision to overwrite the current save
265
        file is made based on either the maximization or the minimization of
266 267 268 269
        the monitored quantity. For `'val_acc'`, this should be `'max'`, for
        `'val_loss'` this should be `'min'`, etc. In `'auto'` mode, the
        direction is automatically inferred from the name of the monitored
        quantity.
270
    period: int, Default=1,
271
        Interval (number of epochs) between checkpoints.
272
    max_save: int, Default=-1
273 274 275 276 277 278 279 280 281 282
        Maximum number of outputs to save. If -1 will save all outputs

    Examples
    --------

    Callbacks are passed as input parameters when calling ``compile``. see
    :class:`pytorch_widedeep.models.wide_deep.WideDeep`

    >>> # Do not run
    >>> model.compile(callbacks=[ModelCheckpoint()])
283
    """
J
jrzaurin 已提交
284 285 286 287 288 289 290 291 292 293 294

    def __init__(
        self,
        filepath: str,
        monitor: str = "val_loss",
        verbose: int = 0,
        save_best_only: bool = False,
        mode: str = "auto",
        period: int = 1,
        max_save: int = -1,
    ):
295 296 297 298 299 300 301 302 303
        super(ModelCheckpoint, self).__init__()
        self.monitor = monitor
        self.verbose = verbose
        self.filepath = filepath
        self.save_best_only = save_best_only
        self.period = period
        self.epochs_since_last_save = 0
        self.max_save = max_save

J
jrzaurin 已提交
304
        root_dir = ("/").join(filepath.split("/")[:-1])
305 306 307
        if not os.path.exists(root_dir):
            os.makedirs(root_dir)

308
        if self.max_save > 0:
J
jrzaurin 已提交
309
            self.old_files: List[str] = []
310

J
jrzaurin 已提交
311 312 313 314 315 316 317 318
        if mode not in ["auto", "min", "max"]:
            warnings.warn(
                "ModelCheckpoint mode %s is unknown, "
                "fallback to auto mode." % (mode),
                RuntimeWarning,
            )
            mode = "auto"
        if mode == "min":
319 320
            self.monitor_op = np.less
            self.best = np.Inf
J
jrzaurin 已提交
321
        elif mode == "max":
322 323 324
            self.monitor_op = np.greater
            self.best = -np.Inf
        else:
J
jrzaurin 已提交
325
            if "acc" in self.monitor or self.monitor.startswith("fmeasure"):
326 327 328 329 330 331
                self.monitor_op = np.greater
                self.best = -np.Inf
            else:
                self.monitor_op = np.less
                self.best = np.Inf

J
jrzaurin 已提交
332
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
333 334 335 336
        logs = logs or {}
        self.epochs_since_last_save += 1
        if self.epochs_since_last_save >= self.period:
            self.epochs_since_last_save = 0
J
jrzaurin 已提交
337
            filepath = "{}_{}.p".format(self.filepath, epoch + 1)
338 339 340
            if self.save_best_only:
                current = logs.get(self.monitor)
                if current is None:
J
jrzaurin 已提交
341 342 343 344 345
                    warnings.warn(
                        "Can save best model only with %s available, "
                        "skipping." % (self.monitor),
                        RuntimeWarning,
                    )
346 347 348
                else:
                    if self.monitor_op(current, self.best):
                        if self.verbose > 0:
J
jrzaurin 已提交
349 350 351 352 353 354 355 356 357 358 359
                            print(
                                "\nEpoch %05d: %s improved from %0.5f to %0.5f,"
                                " saving model to %s"
                                % (
                                    epoch + 1,
                                    self.monitor,
                                    self.best,
                                    current,
                                    filepath,
                                )
                            )
360 361 362 363 364 365 366 367 368
                        self.best = current
                        torch.save(self.model.state_dict(), filepath)
                        if self.max_save > 0:
                            if len(self.old_files) == self.max_save:
                                try:
                                    os.remove(self.old_files[0])
                                except:
                                    pass
                                self.old_files = self.old_files[1:]
369
                            self.old_files.append(filepath)
370 371
                    else:
                        if self.verbose > 0:
J
jrzaurin 已提交
372 373 374 375
                            print(
                                "\nEpoch %05d: %s did not improve from %0.5f"
                                % (epoch + 1, self.monitor, self.best)
                            )
376 377
            else:
                if self.verbose > 0:
J
jrzaurin 已提交
378
                    print("\nEpoch %05d: saving model to %s" % (epoch + 1, filepath))
379 380 381 382 383 384 385 386
                torch.save(self.model.state_dict(), filepath)
                if self.max_save > 0:
                    if len(self.old_files) == self.max_save:
                        try:
                            os.remove(self.old_files[0])
                        except:
                            pass
                        self.old_files = self.old_files[1:]
387
                    self.old_files.append(filepath)
388 389 390


class EarlyStopping(Callback):
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    r"""Stop training when a monitored quantity has stopped improving.

    This class is almost identical to the corresponding keras class.
    Therefore, credit to the Keras Team.

    Parameters
    -----------
    monitor: str, default='val_loss'.
        Quantity to be monitored.
    min_delta: float, default=0.
        minimum change in the monitored quantity to qualify as an
        improvement, i.e. an absolute change of less than min_delta, will
        count as no improvement.
    patience: int, default=10.
        Number of epochs that produced the monitored quantity with no
        improvement after which training will be stopped.
    verbose: int.
        verbosity mode.
    mode: str, default='auto'
        one of {'`auto`', '`min`', '`max`'}. In `'min'` mode, training will
        stop when the quantity monitored has stopped decreasing; in `'max'`
        mode it will stop when the quantity monitored has stopped increasing;
        in `'auto'` mode, the direction is automatically inferred from the
        name of the monitored quantity.
    baseline: float, Optional. default=None.
        Baseline value for the monitored quantity to reach. Training will
        stop if the model does not show improvement over the baseline.
    restore_best_weights: bool, default=None
        Whether to restore model weights from the epoch with the best
        value of the monitored quantity. If ``False``, the model weights
        obtained at the last step of training are used.

    Examples
    --------

    Callbacks are passed as input parameters when calling ``compile``. see
    :class:`pytorch_widedeep.models.wide_deep.WideDeep`

    >>> # Do not run
    >>> model.compile(callbacks=[EarlyStopping()])
431 432
    """

J
jrzaurin 已提交
433 434 435 436 437 438 439 440 441 442 443 444
    def __init__(
        self,
        monitor: str = "val_loss",
        min_delta: float = 0.0,
        patience: int = 10,
        verbose: int = 0,
        mode: str = "auto",
        baseline: Optional[float] = None,
        restore_best_weights: bool = False,
    ):

        super(EarlyStopping, self).__init__()
445 446 447 448 449 450 451 452 453 454 455

        self.monitor = monitor
        self.baseline = baseline
        self.patience = patience
        self.verbose = verbose
        self.min_delta = min_delta
        self.wait = 0
        self.stopped_epoch = 0
        self.restore_best_weights = restore_best_weights
        self.state_dict = None

J
jrzaurin 已提交
456 457 458 459 460 461
        if mode not in ["auto", "min", "max"]:
            warnings.warn(
                "EarlyStopping mode %s is unknown, " "fallback to auto mode." % mode,
                RuntimeWarning,
            )
            mode = "auto"
462

J
jrzaurin 已提交
463
        if mode == "min":
464
            self.monitor_op = np.less
J
jrzaurin 已提交
465
        elif mode == "max":
466 467
            self.monitor_op = np.greater
        else:
J
jrzaurin 已提交
468
            if "acc" in self.monitor:
469 470 471 472 473 474 475 476 477
                self.monitor_op = np.greater
            else:
                self.monitor_op = np.less

        if self.monitor_op == np.greater:
            self.min_delta *= 1
        else:
            self.min_delta *= -1

J
jrzaurin 已提交
478
    def on_train_begin(self, logs: Optional[Dict] = None):
479 480 481 482 483 484 485 486
        # Allow instances to be re-used
        self.wait = 0
        self.stopped_epoch = 0
        if self.baseline is not None:
            self.best = self.baseline
        else:
            self.best = np.Inf if self.monitor_op == np.less else -np.Inf

J
jrzaurin 已提交
487
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
        current = self.get_monitor_value(logs)
        if current is None:
            return

        if self.monitor_op(current - self.min_delta, self.best):
            self.best = current
            self.wait = 0
            if self.restore_best_weights:
                self.state_dict = self.model.state_dict()
        else:
            self.wait += 1
            if self.wait >= self.patience:
                self.stopped_epoch = epoch
                self.model.early_stop = True
                if self.restore_best_weights:
                    if self.verbose > 0:
J
jrzaurin 已提交
504 505 506
                        print(
                            "Restoring model weights from the end of " "the best epoch"
                        )
507 508
                    self.model.load_state_dict(self.state_dict)

J
jrzaurin 已提交
509
    def on_train_end(self, logs: Optional[Dict] = None):
510
        if self.stopped_epoch > 0 and self.verbose > 0:
J
jrzaurin 已提交
511
            print("Epoch %05d: early stopping" % (self.stopped_epoch + 1))
512 513 514 515

    def get_monitor_value(self, logs):
        monitor_value = logs.get(self.monitor)
        if monitor_value is None:
J
jrzaurin 已提交
516 517 518 519 520
            warnings.warn(
                "Early stopping conditioned on metric `%s` "
                "which is not available. Available metrics are: %s"
                % (self.monitor, ",".join(list(logs.keys()))),
                RuntimeWarning,
521
            )
J
jrzaurin 已提交
522
        return monitor_value