Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(mlflow): Enabling multiple callbacks for checkpoint reporting #20585

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

HarryAnkers
Copy link

@HarryAnkers HarryAnkers commented Feb 11, 2025

What does this PR do?

Fixes #20584

Currently if the below code is run it will only ever save one checkpoint if both use callbacks and both use param save_top_k. This works if log_model='all' but not when log_model=True. If you flip the order of callbacks this works fine however. I have tried to raise a fix for this. Let me know what you think.

import os
import pytorch_lightning as pl
from pytorch_lightning.loggers import MLFlowLogger
from pytorch_lightning.callbacks import ModelCheckpoint
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

# Change these as wanted
os.environ["MLFLOW_TRACKING_USERNAME"] = ""
os.environ["MLFLOW_TRACKING_PASSWORD"] = ""


class SimpleModel(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(10, 1)

    def forward(self, x):
        return self.fc(x)

    def training_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self(x)
        loss = nn.MSELoss()(y_hat, y)
        self.log("train_loss", loss)
        return loss

    def validation_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self(x)
        loss = nn.MSELoss()(y_hat, y)
        self.log("val_loss", loss)

    def configure_optimizers(self):
        return optim.SGD(self.parameters(), lr=0.01)


def train():
    URI = ""

    mlflow_logger = MLFlowLogger(
        experiment_name="harry-test",
        tracking_uri=URI,
        run_name="harry-test1",
        log_model=True,
    )

    x_train, y_train = torch.randn(100, 10), torch.randn(100, 1)
    train_dataset = TensorDataset(x_train, y_train)
    train_loader = DataLoader(train_dataset, batch_size=32)

    x_val, y_val = torch.randn(20, 10), torch.randn(20, 1)
    val_dataset = TensorDataset(x_val, y_val)
    val_loader = DataLoader(val_dataset, batch_size=32)

    model = SimpleModel()

    checkpoint_callback_val = ModelCheckpoint(
        dirpath="/home/harryankers/Documents/Checkpoints/val_checkpoints",
        monitor="val_loss",
        filename="best_val_model-{epoch:02d}-{val_loss:.2f}",
        save_top_k=2,
        mode="min",
    )

    checkpoint_callback_train = ModelCheckpoint(
        dirpath="/home/harryankers/Documents/Checkpoints/train_checkpoints",
        monitor="train_loss",
        filename="best_train_model-{epoch:02d}-{train_loss:.2f}",
        save_top_k=2,
        mode="min",
    )

    trainer = pl.Trainer(
        max_epochs=20,
        logger=mlflow_logger,
        callbacks=[checkpoint_callback_train, checkpoint_callback_val],
        val_check_interval=3,
    )

    trainer.fit(model, train_loader, val_loader)


if __name__ == "__main__":
    train()
Before submitting
  • Was this discussed/agreed via a GitHub issue? (not for typos and docs)
  • Did you read the contributor guideline, Pull Request section?
  • Did you make sure your PR does only one thing, instead of bundling different changes together?
  • Did you make sure to update the documentation with your changes? (if necessary)
  • Did you write any new necessary tests? (not for typos and docs)
    Yes wrote a test for this behaviour
  • Did you verify new and existing tests pass locally with your changes?
  • Did you list all the breaking changes introduced by this pull request?
  • Did you update the CHANGELOG? (not for typos, docs, test updates, or minor internal changes/refactors)

PR review

Anyone in the community is welcome to review the PR.
Before you start reviewing, make sure you have read the review guidelines. In short, see the following bullet-list:

Reviewer checklist
  • Is this pull request ready for review? (if not, please submit in draft mode)
  • Check that all items from Before submitting are resolved
  • Make sure the title is self-explanatory and the description concisely explains the PR
  • Add labels and milestones (and optionally projects) to the PR so it can be classified

📚 Documentation preview 📚: https://pytorch-lightning--20585.org.readthedocs.build/en/20585/

@github-actions github-actions bot added the pl Generic label for PyTorch Lightning package label Feb 11, 2025
Copy link

codecov bot commented Feb 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 79%. Comparing base (ea59e40) to head (51da02e).
Report is 1 commits behind head on master.

❗ There is a different number of reports uploaded between BASE (ea59e40) and HEAD (51da02e). Click for more details.

HEAD has 2247 uploads less than BASE
Flag BASE (ea59e40) HEAD (51da02e)
cpu 525 24
lightning_fabric 67 0
pytest 266 0
python3.9 132 6
lightning 394 18
python3.10 66 3
python3.11 132 6
python3.12.7 195 9
gpu 2 0
pytorch2.1 99 9
pytest-full 261 24
pytorch2.2.2 33 3
pytorch_lightning 66 6
pytorch2.3 33 3
pytorch2.4.1 31 3
pytorch2.5.1 65 6
Additional details and impacted files
@@            Coverage Diff            @@
##           master   #20585     +/-   ##
=========================================
- Coverage      88%      79%     -9%     
=========================================
  Files         267      264      -3     
  Lines       23380    23326     -54     
=========================================
- Hits        20481    18367   -2114     
- Misses       2899     4959   +2060     

@Borda Borda added logger Related to the Loggers 3rd party Related to a 3rd-party community This PR is from the community labels Feb 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3rd party Related to a 3rd-party community This PR is from the community logger Related to the Loggers pl Generic label for PyTorch Lightning package
Projects
None yet
Development

Successfully merging this pull request may close these issues.

MLFlow logger - save top k to server on N epochs
2 participants