callbacks.py 20.7 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 *  # noqa: F403
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)

46 47 48 49 50
    def set_trainer(self, trainer: Any):
        self.trainer = trainer
        for callback in self.callbacks:
            callback.set_trainer(trainer)

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

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

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

J
jrzaurin 已提交
66
    def on_batch_end(self, batch: int, logs: Optional[Dict] = None):
67 68 69 70
        logs = logs or {}
        for callback in self.callbacks:
            callback.on_batch_end(batch, logs)

J
jrzaurin 已提交
71
    def on_train_begin(self, logs: Optional[Dict] = None):
72
        logs = logs or {}
J
jrzaurin 已提交
73
        logs["start_time"] = _get_current_time()
74 75 76
        for callback in self.callbacks:
            callback.on_train_begin(logs)

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


class Callback(object):
    """
88
    Base class used to build new callbacks.
89 90 91 92 93 94 95 96
    """

    def __init__(self):
        pass

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

J
jrzaurin 已提交
97
    def set_model(self, model: Any):
98 99
        self.model = model

100 101 102
    def set_trainer(self, trainer: Any):
        self.trainer = trainer

J
jrzaurin 已提交
103
    def on_epoch_begin(self, epoch: int, logs: Optional[Dict] = None):
104 105
        pass

J
jrzaurin 已提交
106
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
107 108
        pass

J
jrzaurin 已提交
109
    def on_batch_begin(self, batch: int, logs: Optional[Dict] = None):
110 111
        pass

J
jrzaurin 已提交
112
    def on_batch_end(self, batch: int, logs: Optional[Dict] = None):
113 114
        pass

J
jrzaurin 已提交
115
    def on_train_begin(self, logs: Optional[Dict] = None):
116 117
        pass

J
jrzaurin 已提交
118
    def on_train_end(self, logs: Optional[Dict] = None):
119 120 121 122
        pass


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

125
    This callback runs by default within :obj:`WideDeep`. See
126
    :class:`pytorch_widedeep.models.wide_deep.WideDeep`. Documentation is
127
    included here for completion.
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

    Examples
    --------

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

    >>> from pytorch_widedeep.callbacks import History
    >>> from pytorch_widedeep.models import DeepDense, Wide, WideDeep
    >>>
    >>> embed_input = [(u, i, j) for u, i, j in zip(["a", "b", "c"][:4], [4] * 3, [8] * 3)]
    >>> deep_column_idx = {k: v for v, k in enumerate(["a", "b", "c"])}
    >>> wide = Wide(10, 1)
    >>> deep = DeepDense(hidden_layers=[8, 4], deep_column_idx=deep_column_idx, embed_input=embed_input)
    >>> model = WideDeep(wide, deep)
    >>> model.compile(method="regression", callbacks=[History()])
144 145
    """

J
jrzaurin 已提交
146
    def on_train_begin(self, logs: Optional[Dict] = None):
147 148
        self.trainer.epoch = []
        self.trainer.history = {}
149

J
jrzaurin 已提交
150
    def on_epoch_begin(self, epoch: int, logs: Optional[Dict] = None):
151 152 153
        # avoid mutation during epoch run
        logs = deepcopy(logs) or {}
        for k, v in logs.items():
154
            self.trainer.history.setdefault(k, []).append(v)
155

J
jrzaurin 已提交
156
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
157
        logs = logs or {}
158
        self.trainer.epoch.append(epoch)
159
        for k, v in logs.items():
160
            self.trainer.history.setdefault(k, []).append(v)
161 162


163
class LRHistory(Callback):
164 165 166 167 168
    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.
169 170 171 172 173 174 175 176 177 178 179 180 181 182

    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`

183 184 185 186 187 188 189 190 191
    >>> from pytorch_widedeep.callbacks import LRHistory
    >>> from pytorch_widedeep.models import DeepDense, Wide, WideDeep
    >>>
    >>> embed_input = [(u, i, j) for u, i, j in zip(["a", "b", "c"][:4], [4] * 3, [8] * 3)]
    >>> deep_column_idx = {k: v for v, k in enumerate(["a", "b", "c"])}
    >>> wide = Wide(10, 1)
    >>> deep = DeepDense(hidden_layers=[8, 4], deep_column_idx=deep_column_idx, embed_input=embed_input)
    >>> model = WideDeep(wide, deep)
    >>> model.compile(method="regression", callbacks=[LRHistory(n_epochs=10)])
192
    """
J
jrzaurin 已提交
193

194
    def __init__(self, n_epochs: int):
195 196
        super(LRHistory, self).__init__()
        self.n_epochs = n_epochs
197

J
jrzaurin 已提交
198
    def on_epoch_begin(self, epoch: int, logs: Optional[Dict] = None):
199 200
        if epoch == 0 and self.trainer.lr_scheduler is not None:
            self.trainer.lr_history = {}
201 202
            if self._multiple_scheduler():
                self._save_group_lr_mulitple_scheduler(step_location="on_epoch_begin")
203 204
            elif not self.trainer.cyclic_lr:
                self._save_group_lr(self.trainer.optimizer)
205

J
jrzaurin 已提交
206
    def on_batch_end(self, batch: int, logs: Optional[Dict] = None):
207
        if self.trainer.lr_scheduler is not None:
208 209
            if self._multiple_scheduler():
                self._save_group_lr_mulitple_scheduler(step_location="on_batch_end")
210 211
            elif self.trainer.cyclic_lr:
                self._save_group_lr(self.trainer.optimizer)
212

J
jrzaurin 已提交
213
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
214
        if epoch != (self.n_epochs - 1) and self.trainer.lr_scheduler is not None:
215 216
            if self._multiple_scheduler():
                self._save_group_lr_mulitple_scheduler(step_location="on_epoch_end")
217 218
            elif not self.trainer.cyclic_lr:
                self._save_group_lr(self.trainer.optimizer)
219 220

    def _save_group_lr_mulitple_scheduler(self, step_location: str):
221
        for model_name, opt in self.trainer.optimizer._optimizers.items():
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
            if step_location == "on_epoch_begin":
                self._save_group_lr(opt, model_name)
            if step_location == "on_batch_end":
                if self._is_cyclic(model_name):
                    self._save_group_lr(opt, model_name)
            if step_location == "on_epoch_end":
                if not self._is_cyclic(model_name):
                    self._save_group_lr(opt, model_name)

    def _save_group_lr(self, opt: Optimizer, model_name: Optional[str] = None):
        for group_idx, group in enumerate(opt.param_groups):
            if model_name is not None:
                group_name = ("_").join(["lr", model_name, str(group_idx)])
            else:
                group_name = ("_").join(["lr", str(group_idx)])
237
            self.trainer.lr_history.setdefault(group_name, []).append(group["lr"])
238 239

    def _multiple_scheduler(self):
240
        return self.trainer.lr_scheduler.__class__.__name__ == "MultipleLRScheduler"
241 242 243 244 245

    def _is_cyclic(self, model_name: str):
        return (
            self._has_scheduler(model_name)
            and "cycl"
246
            in self.trainer.lr_scheduler._schedulers[
247 248 249 250 251
                model_name
            ].__class__.__name__.lower()
        )

    def _has_scheduler(self, model_name: str):
252
        return model_name in self.trainer.lr_scheduler._schedulers
253 254


255
class ModelCheckpoint(Callback):
256 257 258
    r"""Saves the model after every epoch.

    This class is almost identical to the corresponding keras class.
259
    Therefore, **credit** to the Keras Team.
260 261 262

    Parameters
    ----------
263
    filepath: str
264
        Full path to save the output weights. It must contain only the root of
265 266 267 268 269 270 271 272 273
        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,
274
        verbosity mode
275
    save_best_only: bool, Default=False,
276 277
        the latest best model according to the quantity monitored will not be
        overwritten.
278
    mode: str, Default='auto',
279
        If ``save_best_only=True``, the decision to overwrite the current save
280
        file is made based on either the maximization or the minimization of
281 282 283 284
        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.
285
    period: int, Default=1,
286
        Interval (number of epochs) between checkpoints.
287
    max_save: int, Default=-1
288 289 290 291 292 293 294 295
        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`

296 297 298 299 300 301 302 303 304
    >>> from pytorch_widedeep.callbacks import ModelCheckpoint
    >>> from pytorch_widedeep.models import DeepDense, Wide, WideDeep
    >>>
    >>> embed_input = [(u, i, j) for u, i, j in zip(["a", "b", "c"][:4], [4] * 3, [8] * 3)]
    >>> deep_column_idx = {k: v for v, k in enumerate(["a", "b", "c"])}
    >>> wide = Wide(10, 1)
    >>> deep = DeepDense(hidden_layers=[8, 4], deep_column_idx=deep_column_idx, embed_input=embed_input)
    >>> model = WideDeep(wide, deep)
    >>> model.compile(method="regression", callbacks=[ModelCheckpoint(filepath='checkpoints/weights_out')])
305
    """
J
jrzaurin 已提交
306 307 308 309 310 311 312 313 314 315 316

    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,
    ):
317

318
        super(ModelCheckpoint, self).__init__()
319 320

        self.filepath = filepath
321 322 323
        self.monitor = monitor
        self.verbose = verbose
        self.save_best_only = save_best_only
324
        self.mode = mode
325 326 327
        self.period = period
        self.max_save = max_save

328 329 330
        self.epochs_since_last_save = 0

        if len(self.filepath.split("/")[:-1]) == 0:
331 332 333 334 335
            raise ValueError(
                "'filepath' must be the full path to save the output weights,"
                " including the root of the filenames. e.g. 'checkpoints/weights_out'"
            )

336
        root_dir = ("/").join(self.filepath.split("/")[:-1])
337 338 339
        if not os.path.exists(root_dir):
            os.makedirs(root_dir)

340
        if self.max_save > 0:
J
jrzaurin 已提交
341
            self.old_files: List[str] = []
342

343
        if self.mode not in ["auto", "min", "max"]:
J
jrzaurin 已提交
344 345
            warnings.warn(
                "ModelCheckpoint mode %s is unknown, "
346
                "fallback to auto mode." % (self.mode),
J
jrzaurin 已提交
347 348
                RuntimeWarning,
            )
349 350
            self.mode = "auto"
        if self.mode == "min":
351 352
            self.monitor_op = np.less
            self.best = np.Inf
353
        elif self.mode == "max":
354 355 356
            self.monitor_op = np.greater
            self.best = -np.Inf
        else:
J
jrzaurin 已提交
357
            if "acc" in self.monitor or self.monitor.startswith("fmeasure"):
358 359 360 361 362 363
                self.monitor_op = np.greater
                self.best = -np.Inf
            else:
                self.monitor_op = np.less
                self.best = np.Inf

364
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):  # noqa: C901
365 366 367 368
        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 已提交
369
            filepath = "{}_{}.p".format(self.filepath, epoch + 1)
370 371 372
            if self.save_best_only:
                current = logs.get(self.monitor)
                if current is None:
J
jrzaurin 已提交
373 374 375 376 377
                    warnings.warn(
                        "Can save best model only with %s available, "
                        "skipping." % (self.monitor),
                        RuntimeWarning,
                    )
378 379 380
                else:
                    if self.monitor_op(current, self.best):
                        if self.verbose > 0:
J
jrzaurin 已提交
381 382 383 384 385 386 387 388 389 390 391
                            print(
                                "\nEpoch %05d: %s improved from %0.5f to %0.5f,"
                                " saving model to %s"
                                % (
                                    epoch + 1,
                                    self.monitor,
                                    self.best,
                                    current,
                                    filepath,
                                )
                            )
392 393 394 395 396 397
                        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])
398
                                except FileNotFoundError:
399 400
                                    pass
                                self.old_files = self.old_files[1:]
401
                            self.old_files.append(filepath)
402 403
                    else:
                        if self.verbose > 0:
J
jrzaurin 已提交
404 405 406 407
                            print(
                                "\nEpoch %05d: %s did not improve from %0.5f"
                                % (epoch + 1, self.monitor, self.best)
                            )
408 409
            else:
                if self.verbose > 0:
J
jrzaurin 已提交
410
                    print("\nEpoch %05d: saving model to %s" % (epoch + 1, filepath))
411 412 413 414 415
                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])
416
                        except FileNotFoundError:
417 418
                            pass
                        self.old_files = self.old_files[1:]
419
                    self.old_files.append(filepath)
420 421 422


class EarlyStopping(Callback):
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    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`

461 462 463 464 465 466 467 468 469
    >>> from pytorch_widedeep.callbacks import EarlyStopping
    >>> from pytorch_widedeep.models import DeepDense, Wide, WideDeep
    >>>
    >>> embed_input = [(u, i, j) for u, i, j in zip(["a", "b", "c"][:4], [4] * 3, [8] * 3)]
    >>> deep_column_idx = {k: v for v, k in enumerate(["a", "b", "c"])}
    >>> wide = Wide(10, 1)
    >>> deep = DeepDense(hidden_layers=[8, 4], deep_column_idx=deep_column_idx, embed_input=embed_input)
    >>> model = WideDeep(wide, deep)
    >>> model.compile(method="regression", callbacks=[EarlyStopping(patience=10)])
470 471
    """

J
jrzaurin 已提交
472 473 474 475 476 477 478 479 480 481 482 483
    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__()
484 485

        self.monitor = monitor
486
        self.min_delta = min_delta
487 488
        self.patience = patience
        self.verbose = verbose
489 490 491 492
        self.mode = mode
        self.baseline = baseline
        self.restore_best_weights = restore_best_weights

493 494 495 496
        self.wait = 0
        self.stopped_epoch = 0
        self.state_dict = None

497
        if self.mode not in ["auto", "min", "max"]:
J
jrzaurin 已提交
498
            warnings.warn(
499 500
                "EarlyStopping mode %s is unknown, "
                "fallback to auto mode." % self.mode,
J
jrzaurin 已提交
501 502
                RuntimeWarning,
            )
503
            self.mode = "auto"
504

505
        if self.mode == "min":
506
            self.monitor_op = np.less
507
        elif self.mode == "max":
508 509
            self.monitor_op = np.greater
        else:
J
jrzaurin 已提交
510
            if "acc" in self.monitor:
511 512 513 514 515 516 517 518 519
                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 已提交
520
    def on_train_begin(self, logs: Optional[Dict] = None):
521 522 523 524 525 526 527 528
        # 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 已提交
529
    def on_epoch_end(self, epoch: int, logs: Optional[Dict] = None):
530 531 532 533 534 535 536 537 538 539 540 541 542
        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
543
                self.trainer.early_stop = True
544 545
                if self.restore_best_weights:
                    if self.verbose > 0:
J
jrzaurin 已提交
546 547 548
                        print(
                            "Restoring model weights from the end of " "the best epoch"
                        )
549 550
                    self.model.load_state_dict(self.state_dict)

J
jrzaurin 已提交
551
    def on_train_end(self, logs: Optional[Dict] = None):
552
        if self.stopped_epoch > 0 and self.verbose > 0:
J
jrzaurin 已提交
553
            print("Epoch %05d: early stopping" % (self.stopped_epoch + 1))
554 555 556 557

    def get_monitor_value(self, logs):
        monitor_value = logs.get(self.monitor)
        if monitor_value is None:
J
jrzaurin 已提交
558 559 560 561 562
            warnings.warn(
                "Early stopping conditioned on metric `%s` "
                "which is not available. Available metrics are: %s"
                % (self.monitor, ",".join(list(logs.keys()))),
                RuntimeWarning,
563
            )
J
jrzaurin 已提交
564
        return monitor_value