Release/0.9 (#141)
* add flake8 and prettier to pre-commit-config * add setup.cfg * add workers=True to seed_everything() * update lightning badge logo * bump package versions * update README.md * add __init__.py files * add more logger configs parameters * add default Dockerfile * change .env.template to .env.example * move inference example to readme * remove img_dataset.py * simplify names of wandb callbacks * remove wandb test marker * format files with prettier
This commit is contained in:
1 parent
023d4bdecc
commit
70ab061f75
49 files changed
+473
-415
No files matched your search
@@ -1 +0,0 @@
|
||||
#
|
||||
Whitespace-only changes.
@@ -28,8 +28,8 @@ def get_wandb_logger(trainer: Trainer) -> WandbLogger:
|
||||
)
|
||||
|
||||
|
||||
class WatchModelWithWandb(Callback):
|
||||
"""Make WandbLogger watch model at the beginning of the run."""
|
||||
class WatchModel(Callback):
|
||||
"""Make wandb watch model at the beginning of the run."""
|
||||
|
||||
def __init__(self, log: str = "gradients", log_freq: int = 100):
|
||||
self.log = log
|
||||
@@ -40,7 +40,7 @@ class WatchModelWithWandb(Callback):
|
||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
||||
|
||||
|
||||
class UploadCodeToWandbAsArtifact(Callback):
|
||||
class UploadCodeAsArtifact(Callback):
|
||||
"""Upload all *.py files to wandb as an artifact, at the beginning of the run."""
|
||||
|
||||
def __init__(self, code_dir: str):
|
||||
@@ -57,7 +57,7 @@ class UploadCodeToWandbAsArtifact(Callback):
|
||||
experiment.use_artifact(code)
|
||||
|
||||
|
||||
class UploadCheckpointsToWandbAsArtifact(Callback):
|
||||
class UploadCheckpointsAsArtifact(Callback):
|
||||
"""Upload checkpoints to wandb as an artifact, at the end of run."""
|
||||
|
||||
def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
|
||||
@@ -79,7 +79,7 @@ class UploadCheckpointsToWandbAsArtifact(Callback):
|
||||
experiment.use_artifact(ckpts)
|
||||
|
||||
|
||||
class LogConfusionMatrixToWandb(Callback):
|
||||
class LogConfusionMatrix(Callback):
|
||||
"""Generate confusion matrix every epoch and send it to wandb.
|
||||
Expects validation step to return predictions and targets.
|
||||
"""
|
||||
@@ -137,7 +137,7 @@ class LogConfusionMatrixToWandb(Callback):
|
||||
self.targets.clear()
|
||||
|
||||
|
||||
class LogF1PrecRecHeatmapToWandb(Callback):
|
||||
class LogF1PrecRecHeatmap(Callback):
|
||||
"""Generate f1, precision, recall heatmap every epoch and send it to wandb.
|
||||
Expects validation step to return predictions and targets.
|
||||
"""
|
||||
@@ -200,7 +200,7 @@ class LogF1PrecRecHeatmapToWandb(Callback):
|
||||
self.targets.clear()
|
||||
|
||||
|
||||
class ImagePredictionLogger(Callback):
|
||||
class LogImagePredictions(Callback):
|
||||
"""Logs a validation batch and their predictions to wandb.
|
||||
Example adapted from:
|
||||
https://wandb.ai/wandb/wandb-lightning/reports/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY
|
||||
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -1,25 +0,0 @@
|
||||
import os
|
||||
from typing import Callable, Optional
|
||||
|
||||
from PIL import Image
|
||||
from torch.utils.data import Dataset
|
||||
|
||||
|
||||
class ImgDataset(Dataset):
|
||||
"""Example dataset class for loading images from folder."""
|
||||
|
||||
def __init__(self, dir: str, transform: Optional[Callable] = None):
|
||||
self.transform = transform
|
||||
self.images = [os.path.join(dir, fname) for fname in os.listdir(dir)]
|
||||
|
||||
def __getitem__(self, idx: int):
|
||||
image = Image.open(self.images[idx]).convert("L") # convert to black and white
|
||||
# image = Image.open(self.images[idx]).convert("RGB")
|
||||
|
||||
if self.transform:
|
||||
image = self.transform(image)
|
||||
|
||||
return image
|
||||
|
||||
def __len__(self):
|
||||
return len(self.images)
|
||||
Whitespace-only changes.
Whitespace-only changes.
+9
-5
@@ -1,11 +1,15 @@
|
||||
from typing import List, Optional
|
||||
|
||||
from pytorch_lightning import LightningModule, LightningDataModule, Callback, Trainer
|
||||
from pytorch_lightning.loggers import LightningLoggerBase
|
||||
from pytorch_lightning import seed_everything
|
||||
|
||||
import hydra
|
||||
from omegaconf import DictConfig
|
||||
from pytorch_lightning import (
|
||||
Callback,
|
||||
LightningDataModule,
|
||||
LightningModule,
|
||||
Trainer,
|
||||
seed_everything,
|
||||
)
|
||||
from pytorch_lightning.loggers import LightningLoggerBase
|
||||
|
||||
from src.utils import utils
|
||||
|
||||
@@ -25,7 +29,7 @@ def train(config: DictConfig) -> Optional[float]:
|
||||
|
||||
# Set seed for random number generators in pytorch, numpy and python.random
|
||||
if "seed" in config:
|
||||
seed_everything(config.seed)
|
||||
seed_everything(config.seed, workers=True)
|
||||
|
||||
# Init Lightning datamodule
|
||||
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
|
||||
|
||||
Whitespace-only changes.
@@ -1,49 +0,0 @@
|
||||
from PIL import Image
|
||||
from torchvision import transforms
|
||||
|
||||
from src.models.mnist_model import MNISTLitModel
|
||||
|
||||
|
||||
def predict():
|
||||
"""Example of inference with trained model.
|
||||
It loads trained image classification model from checkpoint.
|
||||
Then it loads example image and predicts its label.
|
||||
"""
|
||||
|
||||
# ckpt can be also a URL!
|
||||
CKPT_PATH = "last.ckpt"
|
||||
|
||||
# load model from checkpoint
|
||||
# model __init__ parameters will be loaded from ckpt automatically
|
||||
# you can also pass some parameter explicitly to override it
|
||||
trained_model = MNISTLitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
|
||||
|
||||
# print model hyperparameters
|
||||
print(trained_model.hparams)
|
||||
|
||||
# switch to evaluation mode
|
||||
trained_model.eval()
|
||||
trained_model.freeze()
|
||||
|
||||
# load data
|
||||
img = Image.open("data/example_img.png").convert("L") # convert to black and white
|
||||
# img = Image.open("data/example_img.png").convert("RGB") # convert to RGB
|
||||
|
||||
# preprocess
|
||||
mnist_transforms = transforms.Compose(
|
||||
[
|
||||
transforms.ToTensor(),
|
||||
transforms.Resize((28, 28)),
|
||||
transforms.Normalize((0.1307,), (0.3081,)),
|
||||
]
|
||||
)
|
||||
img = mnist_transforms(img)
|
||||
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
|
||||
|
||||
# inference
|
||||
output = trained_model(img)
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
predict()
|
||||
+26
-26
@@ -3,17 +3,16 @@ import warnings
|
||||
from typing import List, Sequence
|
||||
|
||||
import pytorch_lightning as pl
|
||||
import rich
|
||||
import rich.syntax
|
||||
import rich.tree
|
||||
import wandb
|
||||
from omegaconf import DictConfig, OmegaConf
|
||||
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||
from pytorch_lightning.utilities import rank_zero_only
|
||||
from rich.syntax import Syntax
|
||||
from rich.tree import Tree
|
||||
|
||||
|
||||
def get_logger(name=__name__, level=logging.INFO):
|
||||
"""Initializes python logger."""
|
||||
def get_logger(name=__name__, level=logging.INFO) -> logging.Logger:
|
||||
"""Initializes multi-GPU-friendly python logger."""
|
||||
|
||||
logger = logging.getLogger(name)
|
||||
logger.setLevel(level)
|
||||
@@ -26,25 +25,27 @@ def get_logger(name=__name__, level=logging.INFO):
|
||||
return logger
|
||||
|
||||
|
||||
log = get_logger()
|
||||
|
||||
|
||||
def extras(config: DictConfig) -> None:
|
||||
"""A couple of optional utilities, controlled by main config file.
|
||||
- disabling warnings
|
||||
- easier access to debug mode
|
||||
- forcing debug friendly configuration
|
||||
- forcing multi-gpu friendly configuration
|
||||
"""A couple of optional utilities, controlled by main config file:
|
||||
- disabling warnings
|
||||
- easier access to debug mode
|
||||
- forcing debug friendly configuration
|
||||
- forcing multi-gpu friendly configuration
|
||||
|
||||
Modifies DictConfig in place.
|
||||
|
||||
Args:
|
||||
config (DictConfig): [description]
|
||||
config (DictConfig): Configuration composed by Hydra.
|
||||
"""
|
||||
|
||||
log = get_logger()
|
||||
|
||||
# enable adding new keys to config
|
||||
OmegaConf.set_struct(config, False)
|
||||
|
||||
# disable python warnings if <config.ignore_warnings=True>
|
||||
if config.get("ignore_warnings"):
|
||||
log.info(f"Disabling python warnings! <config.ignore_warnings=True>")
|
||||
log.info("Disabling python warnings! <config.ignore_warnings=True>")
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
# set <config.trainer.fast_dev_run=True> if <config.debug=True>
|
||||
@@ -64,9 +65,9 @@ def extras(config: DictConfig) -> None:
|
||||
config.datamodule.num_workers = 0
|
||||
|
||||
# force multi-gpu friendly configuration if <config.trainer.accelerator=ddp>
|
||||
if config.trainer.get("accelerator") in ["ddp", "ddp_spawn", "dp", "ddp2"]:
|
||||
log.info("Forcing ddp friendly configuration! <config.trainer.accelerator=ddp>")
|
||||
# ddp doesn't like num_workers>0 or pin_memory=True
|
||||
accelerator = config.trainer.get("accelerator")
|
||||
if accelerator in ["ddp", "ddp_spawn", "dp", "ddp2"]:
|
||||
log.info(f"Forcing ddp friendly configuration! <config.trainer.accelerator={accelerator}>")
|
||||
if config.datamodule.get("num_workers"):
|
||||
config.datamodule.num_workers = 0
|
||||
if config.datamodule.get("pin_memory"):
|
||||
@@ -92,14 +93,14 @@ def print_config(
|
||||
"""Prints content of DictConfig using Rich library and its tree structure.
|
||||
|
||||
Args:
|
||||
config (DictConfig): Config.
|
||||
fields (Sequence[str], optional): Determines which main fields from config will be printed
|
||||
and in what order.
|
||||
config (DictConfig): Configuration composed by Hydra.
|
||||
fields (Sequence[str], optional): Determines which main fields from config will
|
||||
be printed and in what order.
|
||||
resolve (bool, optional): Whether to resolve reference fields of DictConfig.
|
||||
"""
|
||||
|
||||
style = "dim"
|
||||
tree = Tree(f":gear: CONFIG", style=style, guide_style=style)
|
||||
tree = rich.tree.Tree(":gear: CONFIG", style=style, guide_style=style)
|
||||
|
||||
for field in fields:
|
||||
branch = tree.add(field, style=style, guide_style=style)
|
||||
@@ -109,7 +110,7 @@ def print_config(
|
||||
if isinstance(config_section, DictConfig):
|
||||
branch_content = OmegaConf.to_yaml(config_section, resolve=resolve)
|
||||
|
||||
branch.add(Syntax(branch_content, "yaml"))
|
||||
branch.add(rich.syntax.Syntax(branch_content, "yaml"))
|
||||
|
||||
rich.print(tree)
|
||||
|
||||
@@ -139,8 +140,6 @@ def log_hyperparameters(
|
||||
hparams["trainer"] = config["trainer"]
|
||||
hparams["model"] = config["model"]
|
||||
hparams["datamodule"] = config["datamodule"]
|
||||
if "optimizer" in config:
|
||||
hparams["optimizer"] = config["optimizer"]
|
||||
if "callbacks" in config:
|
||||
hparams["callbacks"] = config["callbacks"]
|
||||
|
||||
@@ -157,7 +156,8 @@ def log_hyperparameters(
|
||||
trainer.logger.log_hyperparams(hparams)
|
||||
|
||||
# disable logging any more hyperparameters for all loggers
|
||||
# (this is just a trick to prevent trainer from logging hparams of model, since we already did that above)
|
||||
# this is just a trick to prevent trainer from logging hparams of model,
|
||||
# since we already did that above
|
||||
trainer.logger.log_hyperparams = empty
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user