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
142 changes: 142 additions & 0 deletions tests/test_scheduler_monitor.py
Original file line number Diff line number Diff line change
@@ -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)
12 changes: 8 additions & 4 deletions torchTextClassifiers/model/lightning.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def __init__(
scheduler,
scheduler_params,
scheduler_interval="epoch",
scheduler_monitor="train_loss",
**kwargs,
):
"""
Expand All @@ -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"])
Expand Down Expand Up @@ -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:
"""
Expand Down Expand Up @@ -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]
Expand Down
33 changes: 28 additions & 5 deletions torchTextClassifiers/torchTextClassifiers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import inspect
import logging
import pickle
import time
Expand Down Expand Up @@ -437,16 +438,38 @@ 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__", ""
):
# 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,
)
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)
Expand Down Expand Up @@ -490,13 +513,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",
),
Expand Down
Loading