diff --git a/README.md b/README.md
index af5f4ff..8ba88c6 100644
--- a/README.md
+++ b/README.md
@@ -435,7 +435,7 @@ Have a question? Found a bug? Missing a specific feature? Ran into a problem? Fe
Every run is initialized by [run.py](run.py) file. All PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config:
```yaml
-_target_: src.models.mnist_model.MNISTLitModel
+_target_: src.models.mnist_model.MNISTLitModule
input_size: 784
lin1_size: 256
lin2_size: 256
@@ -470,8 +470,8 @@ It also specifies everything that shouldn't be managed by experiment configurati
# specify here default training configuration
defaults:
- trainer: default.yaml
- - model: mnist_model.yaml
- - datamodule: mnist_datamodule.yaml
+ - model: mnist.yaml
+ - datamodule: mnist.yaml
- callbacks: default.yaml # set this to null if you don't want to use callbacks
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
@@ -515,8 +515,8 @@ Experiment configurations allow you to overwrite parameters from main project co
defaults:
- override /mode: exp.yaml
- override /trainer: default.yaml
- - override /model: mnist_model.yaml
- - override /datamodule: mnist_datamodule.yaml
+ - override /model: mnist.yaml
+ - override /datamodule: mnist.yaml
- override /callbacks: default.yaml
- override /logger: null
@@ -576,7 +576,7 @@ trainer:
gradient_clip_val: 0.5
model:
- _target_: src.models.mnist_model.MNISTLitModel
+ _target_: src.models.mnist_module.MNISTLitModule
lr: 0.001
weight_decay: 0.00005
input_size: 784
@@ -639,8 +639,8 @@ hydra:
### Workflow
-1. Write your PyTorch Lightning model (see [mnist_model.py](src/models/mnist_model.py) for example)
-2. Write your PyTorch Lightning datamodule (see [mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example)
+1. Write your PyTorch Lightning module (see [models/mnist_module.py](src/models/mnist_module.py) for example)
+2. Write your PyTorch Lightning datamodule (see [datamodules/mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example)
3. Write your experiment config, containing paths to your model and datamodule
4. Run training with chosen experiment config: `python run.py experiment=experiment_name`
@@ -721,7 +721,7 @@ You can use many of them at once (see [configs/logger/many_loggers.yaml](configs
You can also write your own logger.
-Lightning provides convenient method for logging custom metrics from inside LightningModule. Read the docs [here](https://pytorch-lightning.readthedocs.io/en/latest/extensions/logging.html#automatic-logging) or take a look at [MNIST example](src/models/mnist_model.py).
+Lightning provides convenient method for logging custom metrics from inside LightningModule. Read the docs [here](https://pytorch-lightning.readthedocs.io/en/latest/extensions/logging.html#automatic-logging) or take a look at [MNIST example](src/models/mnist_module.py).
@@ -807,7 +807,7 @@ The following code is an example of loading model from checkpoint and running pr
from PIL import Image
from torchvision import transforms
-from src.models.mnist_model import MNISTLitModel
+from src.models.mnist_module import MNISTLitModule
def predict():
@@ -822,7 +822,7 @@ def predict():
# 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)
+ trained_model = MNISTLitModule.load_from_checkpoint(checkpoint_path=CKPT_PATH)
# print model hyperparameters
print(trained_model.hparams)
@@ -1325,7 +1325,7 @@ pip install git+git://github.com/YourGithubName/your-repo-name.git --upgrade
So any file can be easily imported into any other file like so:
```python
-from project_name.models.mnist_model import MNISTLitModel
+from project_name.models.mnist_module import MNISTLitModule
from project_name.datamodules.mnist_datamodule import MNISTDataModule
```
diff --git a/configs/config.yaml b/configs/config.yaml
index 5936043..f76d671 100644
--- a/configs/config.yaml
+++ b/configs/config.yaml
@@ -4,8 +4,8 @@
defaults:
- _self_
- trainer: default.yaml
- - model: mnist_model.yaml
- - datamodule: mnist_datamodule.yaml
+ - model: mnist.yaml
+ - datamodule: mnist.yaml
- callbacks: default.yaml
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
diff --git a/configs/datamodule/mnist_datamodule.yaml b/configs/datamodule/mnist.yaml
similarity index 100%
rename from configs/datamodule/mnist_datamodule.yaml
rename to configs/datamodule/mnist.yaml
diff --git a/configs/experiment/example_full.yaml b/configs/experiment/example_full.yaml
index aa44939..7f01662 100644
--- a/configs/experiment/example_full.yaml
+++ b/configs/experiment/example_full.yaml
@@ -32,7 +32,7 @@ trainer:
num_sanity_val_steps: 0
model:
- _target_: src.models.mnist_model.MNISTLitModel
+ _target_: src.models.mnist_module.MNISTLitModule
input_size: 784
lin1_size: 256
lin2_size: 256
diff --git a/configs/experiment/example_simple.yaml b/configs/experiment/example_simple.yaml
index 5c28ce6..bc2a67b 100644
--- a/configs/experiment/example_simple.yaml
+++ b/configs/experiment/example_simple.yaml
@@ -6,8 +6,8 @@
defaults:
- override /mode: exp.yaml
- override /trainer: default.yaml
- - override /model: mnist_model.yaml
- - override /datamodule: mnist_datamodule.yaml
+ - override /model: mnist.yaml
+ - override /datamodule: mnist.yaml
- override /callbacks: default.yaml
- override /logger: null
diff --git a/configs/mode/debug.yaml b/configs/mode/debug.yaml
index 7d7a498..1e09905 100644
--- a/configs/mode/debug.yaml
+++ b/configs/mode/debug.yaml
@@ -14,7 +14,7 @@ hydra:
# https://hydra.cc/docs/tutorials/basic/running_your_app/logging/
# use this to set level of only chosen command line loggers to 'DEBUG'
- # verbose: [src.train, src.utils.utils]
+ # verbose: [src.train, src.utils]
# sets output paths for all file logs to 'logs/debug/'
run:
diff --git a/configs/model/mnist_model.yaml b/configs/model/mnist.yaml
similarity index 68%
rename from configs/model/mnist_model.yaml
rename to configs/model/mnist.yaml
index 907ae6e..78338c0 100644
--- a/configs/model/mnist_model.yaml
+++ b/configs/model/mnist.yaml
@@ -1,4 +1,4 @@
-_target_: src.models.mnist_model.MNISTLitModel
+_target_: src.models.mnist_module.MNISTLitModule
input_size: 784
lin1_size: 256
diff --git a/run.py b/run.py
index ad76882..339b76a 100644
--- a/run.py
+++ b/run.py
@@ -13,7 +13,7 @@ def main(config: DictConfig):
# Imports can be nested inside @hydra.main to optimize tab completion
# https://github.com/facebookresearch/hydra/issues/934
from src.train import train
- from src.utils import utils
+ from src import utils
# A couple of optional utilities:
# - disabling python warnings
diff --git a/src/datamodules/mnist_datamodule.py b/src/datamodules/mnist_datamodule.py
index c737ecf..1b705a2 100644
--- a/src/datamodules/mnist_datamodule.py
+++ b/src/datamodules/mnist_datamodule.py
@@ -36,7 +36,6 @@ class MNISTDataModule(LightningDataModule):
super().__init__()
# this line allows to access init params with 'self.hparams' attribute
- # it also ensures init params will be stored in ckpt
self.save_hyperparameters(logger=False)
# data transformations
diff --git a/src/models/modules/__init__.py b/src/models/components/__init__.py
similarity index 100%
rename from src/models/modules/__init__.py
rename to src/models/components/__init__.py
diff --git a/src/models/modules/simple_dense_net.py b/src/models/components/simple_dense_net.py
similarity index 100%
rename from src/models/modules/simple_dense_net.py
rename to src/models/components/simple_dense_net.py
diff --git a/src/models/mnist_model.py b/src/models/mnist_module.py
similarity index 97%
rename from src/models/mnist_model.py
rename to src/models/mnist_module.py
index 6100315..30f1dfc 100644
--- a/src/models/mnist_model.py
+++ b/src/models/mnist_module.py
@@ -5,10 +5,10 @@ from pytorch_lightning import LightningModule
from torchmetrics import MaxMetric
from torchmetrics.classification.accuracy import Accuracy
-from src.models.modules.simple_dense_net import SimpleDenseNet
+from src.models.components.simple_dense_net import SimpleDenseNet
-class MNISTLitModel(LightningModule):
+class MNISTLitModule(LightningModule):
"""
Example of LightningModule for MNIST classification.
diff --git a/src/train.py b/src/train.py
index 5ee20d1..d1db57b 100644
--- a/src/train.py
+++ b/src/train.py
@@ -11,7 +11,7 @@ from pytorch_lightning import (
)
from pytorch_lightning.loggers import LightningLoggerBase
-from src.utils import utils
+from src import utils
log = utils.get_logger(__name__)
diff --git a/src/utils/__init__.py b/src/utils/__init__.py
index e69de29..b8f6501 100644
--- a/src/utils/__init__.py
+++ b/src/utils/__init__.py
@@ -0,0 +1,171 @@
+import logging
+import warnings
+from typing import List, Sequence
+
+import pytorch_lightning as pl
+import rich.syntax
+import rich.tree
+from omegaconf import DictConfig, OmegaConf
+from pytorch_lightning.utilities import rank_zero_only
+
+
+def get_logger(name=__name__) -> logging.Logger:
+ """Initializes multi-GPU-friendly python command line logger."""
+
+ logger = logging.getLogger(name)
+
+ # this ensures all logging levels get marked with the rank zero decorator
+ # otherwise logs would get multiplied for each GPU process in multi-GPU setup
+ for level in (
+ "debug",
+ "info",
+ "warning",
+ "error",
+ "exception",
+ "fatal",
+ "critical",
+ ):
+ setattr(logger, level, rank_zero_only(getattr(logger, level)))
+
+ return logger
+
+
+def extras(config: DictConfig) -> None:
+ """A couple of optional utilities, controlled by main config file:
+ - disabling warnings
+ - forcing debug friendly configuration
+ - verifying experiment name is set when running in experiment mode
+
+ Modifies DictConfig in place.
+
+ Args:
+ config (DictConfig): Configuration composed by Hydra.
+ """
+
+ log = get_logger(__name__)
+
+ # disable python warnings if
+ if config.get("ignore_warnings"):
+ log.info("Disabling python warnings! ")
+ warnings.filterwarnings("ignore")
+
+ # verify experiment name is set when running in experiment mode
+ if config.get("experiment_mode") and not config.get("name"):
+ log.info(
+ "Running in experiment mode without the experiment name specified! "
+ "Use `python run.py mode=exp name=experiment_name`"
+ )
+ log.info("Exiting...")
+ exit()
+
+ # force debugger friendly configuration if
+ # debuggers don't like GPUs and multiprocessing
+ if config.trainer.get("fast_dev_run"):
+ log.info("Forcing debugger friendly configuration! ")
+ if config.trainer.get("gpus"):
+ config.trainer.gpus = 0
+ if config.datamodule.get("pin_memory"):
+ config.datamodule.pin_memory = False
+ if config.datamodule.get("num_workers"):
+ config.datamodule.num_workers = 0
+
+
+@rank_zero_only
+def print_config(
+ config: DictConfig,
+ fields: Sequence[str] = (
+ "trainer",
+ "model",
+ "datamodule",
+ "callbacks",
+ "logger",
+ "test_after_training",
+ "seed",
+ "name",
+ ),
+ resolve: bool = True,
+) -> None:
+ """Prints content of DictConfig using Rich library and its tree structure.
+
+ Args:
+ 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 = rich.tree.Tree("CONFIG", style=style, guide_style=style)
+
+ for field in fields:
+ branch = tree.add(field, style=style, guide_style=style)
+
+ config_section = config.get(field)
+ branch_content = str(config_section)
+ if isinstance(config_section, DictConfig):
+ branch_content = OmegaConf.to_yaml(config_section, resolve=resolve)
+
+ branch.add(rich.syntax.Syntax(branch_content, "yaml"))
+
+ rich.print(tree)
+
+ with open("config_tree.log", "w") as fp:
+ rich.print(tree, file=fp)
+
+
+@rank_zero_only
+def log_hyperparameters(
+ config: DictConfig,
+ model: pl.LightningModule,
+ datamodule: pl.LightningDataModule,
+ trainer: pl.Trainer,
+ callbacks: List[pl.Callback],
+ logger: List[pl.loggers.LightningLoggerBase],
+) -> None:
+ """This method controls which parameters from Hydra config are saved by Lightning loggers.
+
+ Additionaly saves:
+ - number of model parameters
+ """
+
+ hparams = {}
+
+ # choose which parts of hydra config will be saved to loggers
+ hparams["trainer"] = config["trainer"]
+ hparams["model"] = config["model"]
+ hparams["datamodule"] = config["datamodule"]
+
+ if "seed" in config:
+ hparams["seed"] = config["seed"]
+ if "callbacks" in config:
+ hparams["callbacks"] = config["callbacks"]
+
+ # save number of model parameters
+ hparams["model/params/total"] = sum(p.numel() for p in model.parameters())
+ hparams["model/params/trainable"] = sum(
+ p.numel() for p in model.parameters() if p.requires_grad
+ )
+ hparams["model/params/non_trainable"] = sum(
+ p.numel() for p in model.parameters() if not p.requires_grad
+ )
+
+ # send hparams to all loggers
+ trainer.logger.log_hyperparams(hparams)
+
+
+def finish(
+ config: DictConfig,
+ model: pl.LightningModule,
+ datamodule: pl.LightningDataModule,
+ trainer: pl.Trainer,
+ callbacks: List[pl.Callback],
+ logger: List[pl.loggers.LightningLoggerBase],
+) -> None:
+ """Makes sure everything closed properly."""
+
+ # without this sweeps with wandb logger might crash!
+ for lg in logger:
+ if isinstance(lg, pl.loggers.wandb.WandbLogger):
+ import wandb
+
+ wandb.finish()
diff --git a/src/utils/utils.py b/src/utils/utils.py
deleted file mode 100644
index b8f6501..0000000
--- a/src/utils/utils.py
+++ /dev/null
@@ -1,171 +0,0 @@
-import logging
-import warnings
-from typing import List, Sequence
-
-import pytorch_lightning as pl
-import rich.syntax
-import rich.tree
-from omegaconf import DictConfig, OmegaConf
-from pytorch_lightning.utilities import rank_zero_only
-
-
-def get_logger(name=__name__) -> logging.Logger:
- """Initializes multi-GPU-friendly python command line logger."""
-
- logger = logging.getLogger(name)
-
- # this ensures all logging levels get marked with the rank zero decorator
- # otherwise logs would get multiplied for each GPU process in multi-GPU setup
- for level in (
- "debug",
- "info",
- "warning",
- "error",
- "exception",
- "fatal",
- "critical",
- ):
- setattr(logger, level, rank_zero_only(getattr(logger, level)))
-
- return logger
-
-
-def extras(config: DictConfig) -> None:
- """A couple of optional utilities, controlled by main config file:
- - disabling warnings
- - forcing debug friendly configuration
- - verifying experiment name is set when running in experiment mode
-
- Modifies DictConfig in place.
-
- Args:
- config (DictConfig): Configuration composed by Hydra.
- """
-
- log = get_logger(__name__)
-
- # disable python warnings if
- if config.get("ignore_warnings"):
- log.info("Disabling python warnings! ")
- warnings.filterwarnings("ignore")
-
- # verify experiment name is set when running in experiment mode
- if config.get("experiment_mode") and not config.get("name"):
- log.info(
- "Running in experiment mode without the experiment name specified! "
- "Use `python run.py mode=exp name=experiment_name`"
- )
- log.info("Exiting...")
- exit()
-
- # force debugger friendly configuration if
- # debuggers don't like GPUs and multiprocessing
- if config.trainer.get("fast_dev_run"):
- log.info("Forcing debugger friendly configuration! ")
- if config.trainer.get("gpus"):
- config.trainer.gpus = 0
- if config.datamodule.get("pin_memory"):
- config.datamodule.pin_memory = False
- if config.datamodule.get("num_workers"):
- config.datamodule.num_workers = 0
-
-
-@rank_zero_only
-def print_config(
- config: DictConfig,
- fields: Sequence[str] = (
- "trainer",
- "model",
- "datamodule",
- "callbacks",
- "logger",
- "test_after_training",
- "seed",
- "name",
- ),
- resolve: bool = True,
-) -> None:
- """Prints content of DictConfig using Rich library and its tree structure.
-
- Args:
- 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 = rich.tree.Tree("CONFIG", style=style, guide_style=style)
-
- for field in fields:
- branch = tree.add(field, style=style, guide_style=style)
-
- config_section = config.get(field)
- branch_content = str(config_section)
- if isinstance(config_section, DictConfig):
- branch_content = OmegaConf.to_yaml(config_section, resolve=resolve)
-
- branch.add(rich.syntax.Syntax(branch_content, "yaml"))
-
- rich.print(tree)
-
- with open("config_tree.log", "w") as fp:
- rich.print(tree, file=fp)
-
-
-@rank_zero_only
-def log_hyperparameters(
- config: DictConfig,
- model: pl.LightningModule,
- datamodule: pl.LightningDataModule,
- trainer: pl.Trainer,
- callbacks: List[pl.Callback],
- logger: List[pl.loggers.LightningLoggerBase],
-) -> None:
- """This method controls which parameters from Hydra config are saved by Lightning loggers.
-
- Additionaly saves:
- - number of model parameters
- """
-
- hparams = {}
-
- # choose which parts of hydra config will be saved to loggers
- hparams["trainer"] = config["trainer"]
- hparams["model"] = config["model"]
- hparams["datamodule"] = config["datamodule"]
-
- if "seed" in config:
- hparams["seed"] = config["seed"]
- if "callbacks" in config:
- hparams["callbacks"] = config["callbacks"]
-
- # save number of model parameters
- hparams["model/params/total"] = sum(p.numel() for p in model.parameters())
- hparams["model/params/trainable"] = sum(
- p.numel() for p in model.parameters() if p.requires_grad
- )
- hparams["model/params/non_trainable"] = sum(
- p.numel() for p in model.parameters() if not p.requires_grad
- )
-
- # send hparams to all loggers
- trainer.logger.log_hyperparams(hparams)
-
-
-def finish(
- config: DictConfig,
- model: pl.LightningModule,
- datamodule: pl.LightningDataModule,
- trainer: pl.Trainer,
- callbacks: List[pl.Callback],
- logger: List[pl.loggers.LightningLoggerBase],
-) -> None:
- """Makes sure everything closed properly."""
-
- # without this sweeps with wandb logger might crash!
- for lg in logger:
- if isinstance(lg, pl.loggers.wandb.WandbLogger):
- import wandb
-
- wandb.finish()