Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions docs/source/api/configs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ Configuration for training process.
.. attribute:: scheduler
:type: Optional[Type[torch.optim.lr_scheduler._LRScheduler]]

Learning rate scheduler class (optional).
Learning rate scheduler class (optional). Schedulers are stepped once per
epoch. ``ReduceLROnPlateau`` reduces the learning rate when the metric set by
:attr:`scheduler_monitor` stops improving.

.. attribute:: accelerator
:type: str
Expand All @@ -134,7 +136,15 @@ Configuration for training process.
.. attribute:: patience_early_stopping
:type: int

Early stopping patience in epochs (default: 3).
Early stopping patience in epochs (default: 3). Early stopping and model
checkpointing monitor ``"val_loss"`` when a validation set is given,
``"train_loss"`` otherwise.

With ``ReduceLROnPlateau``, its ``patience`` (in :attr:`scheduler_params`)
must be lower than this value, otherwise training stops before the learning
rate is ever reduced. A warning is logged in that case. Note that PyTorch's
default ``patience`` for ``ReduceLROnPlateau`` is 10, which is higher than
the default early stopping patience of 3.

.. attribute:: dataloader_params
:type: Optional[dict]
Expand All @@ -156,6 +166,15 @@ Configuration for training process.

Additional scheduler parameters (optional).

.. attribute:: scheduler_monitor
:type: Optional[str]

Metric monitored by ``ReduceLROnPlateau`` (ignored by other schedulers).
Default (``None``): the same metric as early stopping and checkpointing,
i.e. ``"val_loss"`` when a validation set is given, ``"train_loss"`` otherwise.
Set to ``"train_loss"`` to reduce the learning rate on the training loss even
when a validation set is available.

Example
~~~~~~~

Expand Down Expand Up @@ -186,6 +205,17 @@ Example
scheduler_params={"T_max": 50}
)

# Reduce the learning rate when the validation loss plateaus
config = TrainingConfig(
num_epochs=50,
batch_size=64,
lr=1e-3,
scheduler=optim.lr_scheduler.ReduceLROnPlateau,
scheduler_params={"patience": 2, "factor": 0.5}, # patience < early stopping
patience_early_stopping=5,
# scheduler_monitor="train_loss", # uncomment to watch the training loss instead
)

See Also
--------

Expand Down
5 changes: 4 additions & 1 deletion docs/source/api/model.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,10 @@ PyTorch Lightning LightningModule for automated training.

- Automated training/validation/test steps
- Metrics tracking (accuracy)
- Optimizer and scheduler management
- Optimizer and scheduler management (``ReduceLROnPlateau`` monitors the
metric given by ``scheduler_monitor``, default ``"train_loss"``; pass
``scheduler_monitor="val_loss"`` when training with a validation set.
``torchTextClassifiers.train`` sets it automatically.)
- Logging integration
- PyTorch Lightning callbacks support

Expand Down
24 changes: 24 additions & 0 deletions tests/test_scheduler_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,30 @@ def test_falls_back_to_train_loss_without_validation_set(
)
assert ttc.lightning_module.scheduler_monitor == "train_loss"

def test_user_can_keep_train_loss_with_validation_set(
self, tmp_path, sample_text_data, sample_labels
):
ttc = _classifier(sample_text_data)
config = _training_config(tmp_path)
config.scheduler_monitor = "train_loss"
ttc.train(
X_train=sample_text_data,
y_train=sample_labels,
X_val=sample_text_data,
y_val=sample_labels,
training_config=config,
)
assert ttc.lightning_module.scheduler_monitor == "train_loss"

def test_val_monitor_without_validation_set_raises(
self, tmp_path, sample_text_data, sample_labels
):
ttc = _classifier(sample_text_data)
config = _training_config(tmp_path)
config.scheduler_monitor = "val_loss"
with pytest.raises(ValueError, match="requires a validation set"):
ttc.train(X_train=sample_text_data, y_train=sample_labels, training_config=config)

@pytest.mark.parametrize("scheduler_patience, warns", [(3, True), (2, False)])
def test_warns_when_scheduler_patience_not_below_early_stopping(
self, tmp_path, caplog, sample_text_data, sample_labels, scheduler_patience, warns
Expand Down
11 changes: 10 additions & 1 deletion torchTextClassifiers/torchTextClassifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ class TrainingConfig:
trainer_params: Optional[dict] = None
optimizer_params: Optional[dict] = None
scheduler_params: Optional[dict] = None
# Metric watched by ReduceLROnPlateau. None: same as early stopping / checkpointing
# ("val_loss" if a validation set is given, else "train_loss").
scheduler_monitor: Optional[str] = None
save_path: Optional[str] = "my_ttc"

def to_dict(self) -> Dict[str, Any]:
Expand Down Expand Up @@ -441,6 +444,12 @@ def train(
# Early stopping, checkpointing and ReduceLROnPlateau all watch the same metric
has_validation = X_val is not None and y_val is not None
monitor = "val_loss" if has_validation else "train_loss"
scheduler_monitor = training_config.scheduler_monitor or monitor
if scheduler_monitor.startswith("val_") and not has_validation:
raise ValueError(
f"scheduler_monitor='{scheduler_monitor}' requires a validation set "
"(X_val and y_val)."
)

scheduler_params = training_config.scheduler_params or {}
if training_config.scheduler is not None and "ReduceLROnPlateau" in getattr(
Expand Down Expand Up @@ -469,7 +478,7 @@ def train(
scheduler=training_config.scheduler,
scheduler_params=scheduler_params,
scheduler_interval="epoch",
scheduler_monitor=monitor,
scheduler_monitor=scheduler_monitor,
)

self.pytorch_model.to(self.device)
Expand Down
Loading