From 31095ca3b9b732b1d4c209c82b1dc54b70f3fd62 Mon Sep 17 00:00:00 2001 From: meilame-tayebjee Date: Wed, 25 Nov 2026 16:22:56 +0000 Subject: [PATCH 1/2] Make ReduceLROnPlateau monitor val_loss when a validation set is given ReduceLROnPlateau was hard-coded to monitor train_loss while EarlyStopping and ModelCheckpoint monitor val_loss. Train loss keeps decreasing while val loss plateaus, so early stopping fired before the LR was ever reduced. - TextClassificationModule gets a scheduler_monitor argument (default "train_loss", unchanged for direct users). - train() computes one monitor metric and shares it between the scheduler, ModelCheckpoint and EarlyStopping. - Warn when ReduceLROnPlateau patience (PyTorch default: 10) is not lower than patience_early_stopping (default: 3). Co-Authored-By: Claude Opus 5.5 --- tests/test_scheduler_monitor.py | 142 +++++++++++++++++++ torchTextClassifiers/model/lightning.py | 12 +- torchTextClassifiers/torchTextClassifiers.py | 31 +++- 3 files changed, 176 insertions(+), 9 deletions(-) create mode 100644 tests/test_scheduler_monitor.py diff --git a/tests/test_scheduler_monitor.py b/tests/test_scheduler_monitor.py new file mode 100644 index 0000000..ba7778e --- /dev/null +++ b/tests/test_scheduler_monitor.py @@ -0,0 +1,142 @@ +"""ReduceLROnPlateau must monitor the same metric as early stopping / checkpointing.""" + +import logging + +import pytest +import torch + +from torchTextClassifiers import ModelConfig, TrainingConfig, torchTextClassifiers +from torchTextClassifiers.model import TextClassificationModule +from torchTextClassifiers.tokenizers import NGramTokenizer + + +class DummyClassificationModel(torch.nn.Module): + def __init__(self, num_classes): + super().__init__() + self.num_classes = num_classes + self.linear = torch.nn.Linear(2, num_classes) + + def forward(self, input_ids, attention_mask=None, categorical_vars=None, **kwargs): + return self.linear(input_ids) + + +def _build_module(scheduler, **kwargs): + return TextClassificationModule( + model=DummyClassificationModel(num_classes=2), + loss=torch.nn.CrossEntropyLoss(), + optimizer=torch.optim.Adam, + optimizer_params={"lr": 1e-3}, + scheduler=scheduler, + scheduler_params={}, + **kwargs, + ) + + +class TestConfigureOptimizers: + def test_plateau_defaults_to_train_loss(self): + _, [config] = _build_module( + torch.optim.lr_scheduler.ReduceLROnPlateau + ).configure_optimizers() + assert config["monitor"] == "train_loss" + + def test_plateau_uses_given_monitor(self): + module = _build_module( + torch.optim.lr_scheduler.ReduceLROnPlateau, scheduler_monitor="val_loss" + ) + _, [config] = module.configure_optimizers() + assert config["monitor"] == "val_loss" + + def test_non_plateau_scheduler_has_no_monitor(self): + module = TextClassificationModule( + model=DummyClassificationModel(num_classes=2), + loss=torch.nn.CrossEntropyLoss(), + optimizer=torch.optim.Adam, + optimizer_params={"lr": 1e-3}, + scheduler=torch.optim.lr_scheduler.StepLR, + scheduler_params={"step_size": 1}, + scheduler_monitor="val_loss", + ) + _, [scheduler] = module.configure_optimizers() + assert isinstance(scheduler, torch.optim.lr_scheduler.StepLR) + + +def _classifier(texts): + tokenizer = NGramTokenizer( + min_count=1, min_n=2, max_n=4, num_tokens=50, len_word_ngrams=2, output_dim=20 + ) + tokenizer.train(list(texts)) + return torchTextClassifiers( + tokenizer=tokenizer, model_config=ModelConfig(embedding_dim=8, num_classes=2) + ) + + +def _training_config(tmp_path, scheduler_patience=1, early_stopping_patience=3): + return TrainingConfig( + num_epochs=2, + batch_size=4, + lr=1e-3, + num_workers=0, + raw_labels=False, + scheduler=torch.optim.lr_scheduler.ReduceLROnPlateau, + scheduler_params={"patience": scheduler_patience}, + patience_early_stopping=early_stopping_patience, + trainer_params={"default_root_dir": str(tmp_path), "enable_progress_bar": False}, + ) + + +class TestTrainSchedulerMonitor: + def test_monitors_val_loss_with_validation_set(self, tmp_path, sample_text_data, sample_labels): + ttc = _classifier(sample_text_data) + ttc.train( + X_train=sample_text_data, + y_train=sample_labels, + X_val=sample_text_data, + y_val=sample_labels, + training_config=_training_config(tmp_path), + ) + assert ttc.lightning_module.scheduler_monitor == "val_loss" + + def test_falls_back_to_train_loss_without_validation_set( + self, tmp_path, sample_text_data, sample_labels + ): + ttc = _classifier(sample_text_data) + ttc.train( + X_train=sample_text_data, + y_train=sample_labels, + training_config=_training_config(tmp_path), + ) + assert ttc.lightning_module.scheduler_monitor == "train_loss" + + @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 + ): + ttc = _classifier(sample_text_data) + with caplog.at_level(logging.WARNING, logger="torchTextClassifiers"): + ttc.train( + X_train=sample_text_data, + y_train=sample_labels, + X_val=sample_text_data, + y_val=sample_labels, + training_config=_training_config( + tmp_path, scheduler_patience=scheduler_patience, early_stopping_patience=3 + ), + ) + assert any("ReduceLROnPlateau patience" in r.message for r in caplog.records) is warns + + def test_warns_with_default_scheduler_patience( + self, tmp_path, caplog, sample_text_data, sample_labels + ): + # No 'patience' given: PyTorch's default (10) is not below early stopping (3) + ttc = _classifier(sample_text_data) + config = _training_config(tmp_path) + config.scheduler_params = None + with caplog.at_level(logging.WARNING, logger="torchTextClassifiers"): + ttc.train( + X_train=sample_text_data, + y_train=sample_labels, + X_val=sample_text_data, + y_val=sample_labels, + training_config=config, + ) + assert any("ReduceLROnPlateau patience (10)" in r.message for r in caplog.records) diff --git a/torchTextClassifiers/model/lightning.py b/torchTextClassifiers/model/lightning.py index dea98dc..f23ba92 100644 --- a/torchTextClassifiers/model/lightning.py +++ b/torchTextClassifiers/model/lightning.py @@ -24,6 +24,7 @@ def __init__( scheduler, scheduler_params, scheduler_interval="epoch", + scheduler_monitor="train_loss", **kwargs, ): """ @@ -37,6 +38,10 @@ def __init__( scheduler: Scheduler. scheduler_params: Scheduler parameters. scheduler_interval: Scheduler interval. + scheduler_monitor: Metric monitored by metric-based schedulers such as + ``ReduceLROnPlateau``. Use ``"val_loss"`` when a validation set is + available (this is what ``torchTextClassifiers.train`` does), so that + the scheduler and early stopping watch the same signal. """ super().__init__() self.save_hyperparameters(ignore=["model", "loss"]) @@ -68,6 +73,7 @@ def __init__( self.scheduler = scheduler self.scheduler_params = scheduler_params self.scheduler_interval = scheduler_interval + self.scheduler_monitor = scheduler_monitor def forward(self, batch) -> torch.Tensor: """ @@ -156,14 +162,12 @@ def configure_optimizers(self): if self.scheduler is None: return optimizer - # Only use scheduler if it's not ReduceLROnPlateau or if we can ensure val_loss is available - # For complex training setups, sometimes val_loss is not available every epoch if hasattr(self.scheduler, "__name__") and "ReduceLROnPlateau" in self.scheduler.__name__: - # For ReduceLROnPlateau, use train_loss as it's always available + # ReduceLROnPlateau needs a metric to monitor scheduler = self.scheduler(optimizer, **self.scheduler_params) scheduler_config = { "scheduler": scheduler, - "monitor": "train_loss", + "monitor": self.scheduler_monitor, "interval": self.scheduler_interval, } return [optimizer], [scheduler_config] diff --git a/torchTextClassifiers/torchTextClassifiers.py b/torchTextClassifiers/torchTextClassifiers.py index 4da2f09..2a0c627 100644 --- a/torchTextClassifiers/torchTextClassifiers.py +++ b/torchTextClassifiers/torchTextClassifiers.py @@ -1,3 +1,4 @@ +import inspect import logging import pickle import time @@ -437,16 +438,36 @@ def train( "⚠️ You have set ragged_multilabel to True but are using CrossEntropyLoss. We would recommend to use torch.nn.BCEWithLogitsLoss for multilabel classification tasks." ) + # 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_params = training_config.scheduler_params or {} + if training_config.scheduler is not None and "ReduceLROnPlateau" in getattr( + training_config.scheduler, "__name__", "" + ): + # Fall back to the scheduler's own default patience when none is given + plateau_patience = scheduler_params.get( + "patience", + inspect.signature(training_config.scheduler).parameters["patience"].default, + ) + if plateau_patience >= training_config.patience_early_stopping: + logger.warning( + f"⚠️ ReduceLROnPlateau patience ({plateau_patience}) is not lower than " + f"patience_early_stopping ({training_config.patience_early_stopping}): " + "training will stop before the learning rate is ever reduced. Set a " + "smaller 'patience' in scheduler_params." + ) + self.lightning_module = TextClassificationModule( model=self.pytorch_model, loss=training_config.loss, optimizer=training_config.optimizer, optimizer_params=optimizer_params, scheduler=training_config.scheduler, - scheduler_params=training_config.scheduler_params - if training_config.scheduler_params - else {}, + scheduler_params=scheduler_params, scheduler_interval="epoch", + scheduler_monitor=monitor, ) self.pytorch_model.to(self.device) @@ -490,13 +511,13 @@ def train( # Setup trainer callbacks = [ ModelCheckpoint( - monitor="val_loss" if val_dataloader is not None else "train_loss", + monitor=monitor, save_top_k=1, save_last=False, mode="min", ), EarlyStopping( - monitor="val_loss" if val_dataloader is not None else "train_loss", + monitor=monitor, patience=training_config.patience_early_stopping, mode="min", ), From dc9017a1fe8e73ea61fef135152939025e298848 Mon Sep 17 00:00:00 2001 From: meilame-tayebjee Date: Wed, 25 Nov 2026 16:23:05 +0000 Subject: [PATCH 2/2] Comment that ReduceLROnPlateau default patience is 10 in PyTorch Co-Authored-By: Claude Opus 5.5 --- torchTextClassifiers/torchTextClassifiers.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/torchTextClassifiers/torchTextClassifiers.py b/torchTextClassifiers/torchTextClassifiers.py index 2a0c627..8452062 100644 --- a/torchTextClassifiers/torchTextClassifiers.py +++ b/torchTextClassifiers/torchTextClassifiers.py @@ -446,7 +446,9 @@ def train( if training_config.scheduler is not None and "ReduceLROnPlateau" in getattr( training_config.scheduler, "__name__", "" ): - # Fall back to the scheduler's own default patience when none is given + # No 'patience' in scheduler_params: use the scheduler's own default, read from + # its signature (10 for torch.optim.lr_scheduler.ReduceLROnPlateau) rather than + # hard-coding it, so we warn on exactly the value PyTorch will use. plateau_patience = scheduler_params.get( "patience", inspect.signature(training_config.scheduler).parameters["patience"].default,