From 71c21b99292e185f7152e181b5caef191a36d6a6 Mon Sep 17 00:00:00 2001 From: meilame-tayebjee Date: Wed, 25 Nov 2026 16:34:25 +0000 Subject: [PATCH] Let users choose the metric monitored by ReduceLROnPlateau Follow-up to #120. TrainingConfig gets scheduler_monitor (default None: same metric as early stopping, i.e. val_loss with a validation set, train_loss otherwise). Setting it to "train_loss" keeps the previous behaviour. Asking for a val_* metric without a validation set raises a clear ValueError instead of an obscure Lightning error. Docs: document scheduler_monitor, which metric early stopping and checkpointing watch, the patience constraint with ReduceLROnPlateau (PyTorch default patience is 10), and add a ReduceLROnPlateau example. Co-Authored-By: Claude Opus 5.5 --- docs/source/api/configs.rst | 34 ++++++++++++++++++-- docs/source/api/model.rst | 5 ++- tests/test_scheduler_monitor.py | 24 ++++++++++++++ torchTextClassifiers/torchTextClassifiers.py | 11 ++++++- 4 files changed, 70 insertions(+), 4 deletions(-) diff --git a/docs/source/api/configs.rst b/docs/source/api/configs.rst index b0812d9..b0983f2 100644 --- a/docs/source/api/configs.rst +++ b/docs/source/api/configs.rst @@ -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 @@ -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] @@ -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 ~~~~~~~ @@ -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 -------- diff --git a/docs/source/api/model.rst b/docs/source/api/model.rst index 16690a4..25d56a3 100644 --- a/docs/source/api/model.rst +++ b/docs/source/api/model.rst @@ -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 diff --git a/tests/test_scheduler_monitor.py b/tests/test_scheduler_monitor.py index ba7778e..0937d9b 100644 --- a/tests/test_scheduler_monitor.py +++ b/tests/test_scheduler_monitor.py @@ -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 diff --git a/torchTextClassifiers/torchTextClassifiers.py b/torchTextClassifiers/torchTextClassifiers.py index 8452062..7a24d16 100644 --- a/torchTextClassifiers/torchTextClassifiers.py +++ b/torchTextClassifiers/torchTextClassifiers.py @@ -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]: @@ -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( @@ -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)