Giter Site home page Giter Site logo

ashleve / lightning-hydra-template Goto Github PK

View Code? Open in Web Editor NEW
3.9K 27.0 612.0 3.69 MB

PyTorch Lightning + Hydra. A very user-friendly template for ML experimentation. ⚑πŸ”₯⚑

Python 98.42% Shell 0.34% Makefile 1.24%
pytorch-lightning project-structure config deep-learning hydra template pytorch reproducibility best-practices mlops

lightning-hydra-template's Introduction

Lightning-Hydra-Template

python pytorch lightning hydra black isort
tests code-quality codecov
license PRs contributors

A clean template to kickstart your deep learning project πŸš€βš‘πŸ”₯
Click on Use this template to initialize new repository.

Suggestions are always welcome!


πŸ“ŒΒ Β Introduction

Why you might want to use it:

βœ… Save on boilerplate
Easily add new models, datasets, tasks, experiments, and train on different accelerators, like multi-GPU, TPU or SLURM clusters.

βœ… Education
Thoroughly commented. You can use this repo as a learning resource.

βœ… Reusability
Collection of useful MLOps tools, configs, and code snippets. You can use this repo as a reference for various utilities.

Why you might not want to use it:

❌ Things break from time to time
Lightning and Hydra are still evolving and integrate many libraries, which means sometimes things break. For the list of currently known problems visit this page.

❌ Not adjusted for data engineering
Template is not really adjusted for building data pipelines that depend on each other. It's more efficient to use it for model prototyping on ready-to-use data.

❌ Overfitted to simple use case
The configuration setup is built with simple lightning training in mind. You might need to put some effort to adjust it for different use cases, e.g. lightning fabric.

❌ Might not support your workflow
For example, you can't resume hydra-based multirun or hyperparameter search.

Note: Keep in mind this is unofficial community project.


Main Technologies

PyTorch Lightning - a lightweight PyTorch wrapper for high-performance AI research. Think of it as a framework for organizing your PyTorch code.

Hydra - a framework for elegantly configuring complex applications. The key feature is the ability to dynamically create a hierarchical configuration by composition and override it through config files and the command line.


Main Ideas

  • Rapid Experimentation: thanks to hydra command line superpowers
  • Minimal Boilerplate: thanks to automating pipelines with config instantiation
  • Main Configs: allow you to specify default training configuration
  • Experiment Configs: allow you to override chosen hyperparameters and version control experiments
  • Workflow: comes down to 4 simple steps
  • Experiment Tracking: Tensorboard, W&B, Neptune, Comet, MLFlow and CSVLogger
  • Logs: all logs (checkpoints, configs, etc.) are stored in a dynamically generated folder structure
  • Hyperparameter Search: simple search is effortless with Hydra plugins like Optuna Sweeper
  • Tests: generic, easy-to-adapt smoke tests for speeding up the development
  • Continuous Integration: automatically test and lint your repo with Github Actions
  • Best Practices: a couple of recommended tools, practices and standards

Project Structure

The directory structure of new project looks like this:

β”œβ”€β”€ .github                   <- Github Actions workflows
β”‚
β”œβ”€β”€ configs                   <- Hydra configs
β”‚   β”œβ”€β”€ callbacks                <- Callbacks configs
β”‚   β”œβ”€β”€ data                     <- Data configs
β”‚   β”œβ”€β”€ debug                    <- Debugging configs
β”‚   β”œβ”€β”€ experiment               <- Experiment configs
β”‚   β”œβ”€β”€ extras                   <- Extra utilities configs
β”‚   β”œβ”€β”€ hparams_search           <- Hyperparameter search configs
β”‚   β”œβ”€β”€ hydra                    <- Hydra configs
β”‚   β”œβ”€β”€ local                    <- Local configs
β”‚   β”œβ”€β”€ logger                   <- Logger configs
β”‚   β”œβ”€β”€ model                    <- Model configs
β”‚   β”œβ”€β”€ paths                    <- Project paths configs
β”‚   β”œβ”€β”€ trainer                  <- Trainer configs
β”‚   β”‚
β”‚   β”œβ”€β”€ eval.yaml             <- Main config for evaluation
β”‚   └── train.yaml            <- Main config for training
β”‚
β”œβ”€β”€ data                   <- Project data
β”‚
β”œβ”€β”€ logs                   <- Logs generated by hydra and lightning loggers
β”‚
β”œβ”€β”€ notebooks              <- Jupyter notebooks. Naming convention is a number (for ordering),
β”‚                             the creator's initials, and a short `-` delimited description,
β”‚                             e.g. `1.0-jqp-initial-data-exploration.ipynb`.
β”‚
β”œβ”€β”€ scripts                <- Shell scripts
β”‚
β”œβ”€β”€ src                    <- Source code
β”‚   β”œβ”€β”€ data                     <- Data scripts
β”‚   β”œβ”€β”€ models                   <- Model scripts
β”‚   β”œβ”€β”€ utils                    <- Utility scripts
β”‚   β”‚
β”‚   β”œβ”€β”€ eval.py                  <- Run evaluation
β”‚   └── train.py                 <- Run training
β”‚
β”œβ”€β”€ tests                  <- Tests of any kind
β”‚
β”œβ”€β”€ .env.example              <- Example of file for storing private environment variables
β”œβ”€β”€ .gitignore                <- List of files ignored by git
β”œβ”€β”€ .pre-commit-config.yaml   <- Configuration of pre-commit hooks for code formatting
β”œβ”€β”€ .project-root             <- File for inferring the position of project root directory
β”œβ”€β”€ environment.yaml          <- File for installing conda environment
β”œβ”€β”€ Makefile                  <- Makefile with commands like `make train` or `make test`
β”œβ”€β”€ pyproject.toml            <- Configuration options for testing and linting
β”œβ”€β”€ requirements.txt          <- File for installing python dependencies
β”œβ”€β”€ setup.py                  <- File for installing project as a package
└── README.md

πŸš€Β Β Quickstart

# clone project
git clone https://github.com/ashleve/lightning-hydra-template
cd lightning-hydra-template

# [OPTIONAL] create conda environment
conda create -n myenv python=3.9
conda activate myenv

# install pytorch according to instructions
# https://pytorch.org/get-started/

# install requirements
pip install -r requirements.txt

Template contains example with MNIST classification.
When running python src/train.py you should see something like this:

⚑  Your Superpowers

Override any config parameter from command line
python train.py trainer.max_epochs=20 model.optimizer.lr=1e-4

Note: You can also add new parameters with + sign.

python train.py +model.new_param="owo"
Train on CPU, GPU, multi-GPU and TPU
# train on CPU
python train.py trainer=cpu

# train on 1 GPU
python train.py trainer=gpu

# train on TPU
python train.py +trainer.tpu_cores=8

# train with DDP (Distributed Data Parallel) (4 GPUs)
python train.py trainer=ddp trainer.devices=4

# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
python train.py trainer=ddp trainer.devices=4 trainer.num_nodes=2

# simulate DDP on CPU processes
python train.py trainer=ddp_sim trainer.devices=2

# accelerate training on mac
python train.py trainer=mps

Warning: Currently there are problems with DDP mode, read this issue to learn more.

Train with mixed precision
# train with pytorch native automatic mixed precision (AMP)
python train.py trainer=gpu +trainer.precision=16
Train model with any logger available in PyTorch Lightning, like W&B or Tensorboard
# set project and entity names in `configs/logger/wandb`
wandb:
  project: "your_project_name"
  entity: "your_wandb_team_name"
# train model with Weights&Biases (link to wandb dashboard should appear in the terminal)
python train.py logger=wandb

Note: Lightning provides convenient integrations with most popular logging frameworks. Learn more here.

Note: Using wandb requires you to setup account first. After that just complete the config as below.

Note: Click here to see example wandb dashboard generated with this template.

Train model with chosen experiment config
python train.py experiment=example

Note: Experiment configs are placed in configs/experiment/.

Attach some callbacks to run
python train.py callbacks=default

Note: Callbacks can be used for things such as as model checkpointing, early stopping and many more.

Note: Callbacks configs are placed in configs/callbacks/.

Use different tricks available in Pytorch Lightning
# gradient clipping may be enabled to avoid exploding gradients
python train.py +trainer.gradient_clip_val=0.5

# run validation loop 4 times during a training epoch
python train.py +trainer.val_check_interval=0.25

# accumulate gradients
python train.py +trainer.accumulate_grad_batches=10

# terminate training after 12 hours
python train.py +trainer.max_time="00:12:00:00"

Note: PyTorch Lightning provides about 40+ useful trainer flags.

Easily debug
# runs 1 epoch in default debugging mode
# changes logging directory to `logs/debugs/...`
# sets level of all command line loggers to 'DEBUG'
# enforces debug-friendly configuration
python train.py debug=default

# run 1 train, val and test loop, using only 1 batch
python train.py debug=fdr

# print execution time profiling
python train.py debug=profiler

# try overfitting to 1 batch
python train.py debug=overfit

# raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf
python train.py +trainer.detect_anomaly=true

# use only 20% of the data
python train.py +trainer.limit_train_batches=0.2 \
+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2

Note: Visit configs/debug/ for different debugging configs.

Resume training from checkpoint
python train.py ckpt_path="/path/to/ckpt/name.ckpt"

Note: Checkpoint can be either path or URL.

Note: Currently loading ckpt doesn't resume logger experiment, but it will be supported in future Lightning release.

Evaluate checkpoint on test dataset
python eval.py ckpt_path="/path/to/ckpt/name.ckpt"

Note: Checkpoint can be either path or URL.

Create a sweep over hyperparameters
# this will run 6 experiments one after the other,
# each with different combination of batch_size and learning rate
python train.py -m data.batch_size=32,64,128 model.lr=0.001,0.0005

Note: Hydra composes configs lazily at job launch time. If you change code or configs after launching a job/sweep, the final composed configs might be impacted.

Create a sweep over hyperparameters with Optuna
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
# over chosen experiment config
python train.py -m hparams_search=mnist_optuna experiment=example

Note: Using Optuna Sweeper doesn't require you to add any boilerplate to your code, everything is defined in a single config file.

Warning: Optuna sweeps are not failure-resistant (if one job crashes then the whole sweep crashes).

Execute all experiments from folder
python train.py -m 'experiment=glob(*)'

Note: Hydra provides special syntax for controlling behavior of multiruns. Learn more here. The command above executes all experiments from configs/experiment/.

Execute run for multiple different seeds
python train.py -m seed=1,2,3,4,5 trainer.deterministic=True logger=csv tags=["benchmark"]

Note: trainer.deterministic=True makes pytorch more deterministic but impacts the performance.

Execute sweep on a remote AWS cluster

Note: This should be achievable with simple config using Ray AWS launcher for Hydra. Example is not implemented in this template.

Use Hydra tab completion

Note: Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing tab key. Read the docs.

Apply pre-commit hooks
pre-commit run -a

Note: Apply pre-commit hooks to do things like auto-formatting code and configs, performing code analysis or removing output from jupyter notebooks. See # Best Practices for more.

Update pre-commit hook versions in .pre-commit-config.yaml with:

pre-commit autoupdate
Run tests
# run all tests
pytest

# run tests from specific file
pytest tests/test_train.py

# run all tests except the ones marked as slow
pytest -k "not slow"
Use tags

Each experiment should be tagged in order to easily filter them across files or in logger UI:

python train.py tags=["mnist","experiment_X"]

Note: You might need to escape the bracket characters in your shell with python train.py tags=\["mnist","experiment_X"\].

If no tags are provided, you will be asked to input them from command line:

>>> python train.py tags=[]
[2022-07-11 15:40:09,358][src.utils.utils][INFO] - Enforcing tags! <cfg.extras.enforce_tags=True>
[2022-07-11 15:40:09,359][src.utils.rich_utils][WARNING] - No tags provided in config. Prompting user to input tags...
Enter a list of comma separated tags (dev):

If no tags are provided for multirun, an error will be raised:

>>> python train.py -m +x=1,2,3 tags=[]
ValueError: Specify tags before launching a multirun!

Note: Appending lists from command line is currently not supported in hydra :(


❀️  Contributions

This project exists thanks to all the people who contribute.

Contributors

Have a question? Found a bug? Missing a specific feature? Feel free to file a new issue, discussion or PR with respective title and description.

Before making an issue, please verify that:

  • The problem still exists on the current main branch.
  • Your python dependencies are updated to recent versions.

Suggestions for improvements are always welcome!


How It Works

All PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config:

_target_: src.models.mnist_model.MNISTLitModule
lr: 0.001
net:
  _target_: src.models.components.simple_dense_net.SimpleDenseNet
  input_size: 784
  lin1_size: 256
  lin2_size: 256
  lin3_size: 256
  output_size: 10

Using this config we can instantiate the object with the following line:

model = hydra.utils.instantiate(config.model)

This allows you to easily iterate over new models! Every time you create a new one, just specify its module path and parameters in appropriate config file.

Switch between models and datamodules with command line arguments:

python train.py model=mnist

Example pipeline managing the instantiation logic: src/train.py.


Main Config

Location: configs/train.yaml
Main project config contains default training configuration.
It determines how config is composed when simply executing command python train.py.

Show main project config
# order of defaults determines the order in which configs override each other
defaults:
  - _self_
  - data: mnist.yaml
  - model: mnist.yaml
  - callbacks: default.yaml
  - logger: null # set logger here or use command line (e.g. `python train.py logger=csv`)
  - trainer: default.yaml
  - paths: default.yaml
  - extras: default.yaml
  - hydra: default.yaml

  # experiment configs allow for version control of specific hyperparameters
  # e.g. best hyperparameters for given model and datamodule
  - experiment: null

  # config for hyperparameter optimization
  - hparams_search: null

  # optional local config for machine/user specific settings
  # it's optional since it doesn't need to exist and is excluded from version control
  - optional local: default.yaml

  # debugging config (enable through command line, e.g. `python train.py debug=default)
  - debug: null

# task name, determines output directory path
task_name: "train"

# tags to help you identify your experiments
# you can overwrite this in experiment configs
# overwrite from command line with `python train.py tags="[first_tag, second_tag]"`
# appending lists from command line is currently not supported :(
# https://github.com/facebookresearch/hydra/issues/1547
tags: ["dev"]

# set False to skip model training
train: True

# evaluate on test set, using best model weights achieved during training
# lightning chooses best weights based on the metric specified in checkpoint callback
test: True

# simply provide checkpoint path to resume training
ckpt_path: null

# seed for random number generators in pytorch, numpy and python.random
seed: null

Experiment Config

Location: configs/experiment
Experiment configs allow you to overwrite parameters from main config.
For example, you can use them to version control best hyperparameters for each combination of model and dataset.

Show example experiment config
# @package _global_

# to execute this experiment run:
# python train.py experiment=example

defaults:
  - override /data: mnist.yaml
  - override /model: mnist.yaml
  - override /callbacks: default.yaml
  - override /trainer: default.yaml

# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters

tags: ["mnist", "simple_dense_net"]

seed: 12345

trainer:
  min_epochs: 10
  max_epochs: 10
  gradient_clip_val: 0.5

model:
  optimizer:
    lr: 0.002
  net:
    lin1_size: 128
    lin2_size: 256
    lin3_size: 64

data:
  batch_size: 64

logger:
  wandb:
    tags: ${tags}
    group: "mnist"

Workflow

Basic workflow

  1. Write your PyTorch Lightning module (see models/mnist_module.py for example)
  2. Write your PyTorch Lightning datamodule (see data/mnist_datamodule.py for example)
  3. Write your experiment config, containing paths to model and datamodule
  4. Run training with chosen experiment config:
    python src/train.py experiment=experiment_name.yaml

Experiment design

Say you want to execute many runs to plot how accuracy changes in respect to batch size.

  1. Execute the runs with some config parameter that allows you to identify them easily, like tags:

    python train.py -m logger=csv data.batch_size=16,32,64,128 tags=["batch_size_exp"]
  2. Write a script or notebook that searches over the logs/ folder and retrieves csv logs from runs containing given tags in config. Plot the results.


Logs

Hydra creates new output directory for every executed run.

Default logging structure:

β”œβ”€β”€ logs
β”‚   β”œβ”€β”€ task_name
β”‚   β”‚   β”œβ”€β”€ runs                        # Logs generated by single runs
β”‚   β”‚   β”‚   β”œβ”€β”€ YYYY-MM-DD_HH-MM-SS       # Datetime of the run
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ .hydra                  # Hydra logs
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ csv                     # Csv logs
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ wandb                   # Weights&Biases logs
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ checkpoints             # Training checkpoints
β”‚   β”‚   β”‚   β”‚   └── ...                     # Any other thing saved during training
β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”‚
β”‚   β”‚   └── multiruns                   # Logs generated by multiruns
β”‚   β”‚       β”œβ”€β”€ YYYY-MM-DD_HH-MM-SS       # Datetime of the multirun
β”‚   β”‚       β”‚   β”œβ”€β”€1                        # Multirun job number
β”‚   β”‚       β”‚   β”œβ”€β”€2
β”‚   β”‚       β”‚   └── ...
β”‚   β”‚       └── ...
β”‚   β”‚
β”‚   └── debugs                          # Logs generated when debugging config is attached
β”‚       └── ...

You can change this structure by modifying paths in hydra configuration.


Experiment Tracking

PyTorch Lightning supports many popular logging frameworks: Weights&Biases, Neptune, Comet, MLFlow, Tensorboard.

These tools help you keep track of hyperparameters and output metrics and allow you to compare and visualize results. To use one of them simply complete its configuration in configs/logger and run:

python train.py logger=logger_name

You can use many of them at once (see configs/logger/many_loggers.yaml for example).

You can also write your own logger.

Lightning provides convenient method for logging custom metrics from inside LightningModule. Read the docs or take a look at MNIST example.


Tests

Template comes with generic tests implemented with pytest.

# run all tests
pytest

# run tests from specific file
pytest tests/test_train.py

# run all tests except the ones marked as slow
pytest -k "not slow"

Most of the implemented tests don't check for any specific output - they exist to simply verify that executing some commands doesn't end up in throwing exceptions. You can execute them once in a while to speed up the development.

Currently, the tests cover cases like:

  • running 1 train, val and test step
  • running 1 epoch on 1% of data, saving ckpt and resuming for the second epoch
  • running 2 epochs on 1% of data, with DDP simulated on CPU

And many others. You should be able to modify them easily for your use case.

There is also @RunIf decorator implemented, that allows you to run tests only if certain conditions are met, e.g. GPU is available or system is not windows. See the examples.


Hyperparameter Search

You can define hyperparameter search by adding new config file to configs/hparams_search.

Show example hyperparameter search config
# @package _global_

defaults:
  - override /hydra/sweeper: optuna

# choose metric which will be optimized by Optuna
# make sure this is the correct name of some metric logged in lightning module!
optimized_metric: "val/acc_best"

# here we define Optuna hyperparameter search
# it optimizes for value returned from function with @hydra.main decorator
hydra:
  sweeper:
    _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper

    # 'minimize' or 'maximize' the objective
    direction: maximize

    # total number of runs that will be executed
    n_trials: 20

    # choose Optuna hyperparameter sampler
    # docs: https://optuna.readthedocs.io/en/stable/reference/samplers.html
    sampler:
      _target_: optuna.samplers.TPESampler
      seed: 1234
      n_startup_trials: 10 # number of random sampling runs before optimization starts

    # define hyperparameter search space
    params:
      model.optimizer.lr: interval(0.0001, 0.1)
      data.batch_size: choice(32, 64, 128, 256)
      model.net.lin1_size: choice(64, 128, 256)
      model.net.lin2_size: choice(64, 128, 256)
      model.net.lin3_size: choice(32, 64, 128, 256)

Next, execute it with: python train.py -m hparams_search=mnist_optuna

Using this approach doesn't require adding any boilerplate to code, everything is defined in a single config file. The only necessary thing is to return the optimized metric value from the launch file.

You can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad.

The optimization_results.yaml will be available under logs/task_name/multirun folder.

This approach doesn't support resuming interrupted search and advanced techniques like prunning - for more sophisticated search and workflows, you should probably write a dedicated optimization task (without multirun feature).


Continuous Integration

Template comes with CI workflows implemented in Github Actions:

  • .github/workflows/test.yaml: running all tests with pytest
  • .github/workflows/code-quality-main.yaml: running pre-commits on main branch for all files
  • .github/workflows/code-quality-pr.yaml: running pre-commits on pull requests for modified files only

Distributed Training

Lightning supports multiple ways of doing distributed training. The most common one is DDP, which spawns separate process for each GPU and averages gradients between them. To learn about other approaches read the lightning docs.

You can run DDP on mnist example with 4 GPUs like this:

python train.py trainer=ddp

Note: When using DDP you have to be careful how you write your models - read the docs.


Accessing Datamodule Attributes In Model

The simplest way is to pass datamodule attribute directly to model on initialization:

# ./src/train.py
datamodule = hydra.utils.instantiate(config.data)
model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)

Note: Not a very robust solution, since it assumes all your datamodules have some_param attribute available.

Similarly, you can pass a whole datamodule config as an init parameter:

# ./src/train.py
model = hydra.utils.instantiate(config.model, dm_conf=config.data, _recursive_=False)

You can also pass a datamodule config parameter to your model through variable interpolation:

# ./configs/model/my_model.yaml
_target_: src.models.my_module.MyLitModule
lr: 0.01
some_param: ${data.some_param}

Another approach is to access datamodule in LightningModule directly through Trainer:

# ./src/models/mnist_module.py
def on_train_start(self):
  self.some_param = self.trainer.datamodule.some_param

Note: This only works after the training starts since otherwise trainer won't be yet available in LightningModule.


Best Practices

Use Miniconda

It's usually unnecessary to install full anaconda environment, miniconda should be enough (weights around 80MB).

Big advantage of conda is that it allows for installing packages without requiring certain compilers or libraries to be available in the system (since it installs precompiled binaries), so it often makes it easier to install some dependencies e.g. cudatoolkit for GPU support.

It also allows you to access your environments globally which might be more convenient than creating new local environment for every project.

Example installation:

wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh

Update conda:

conda update -n base -c defaults conda

Create new conda environment:

conda create -n myenv python=3.10
conda activate myenv
Use automatic code formatting

Use pre-commit hooks to standardize code formatting of your project and save mental energy.
Simply install pre-commit package with:

pip install pre-commit

Next, install hooks from .pre-commit-config.yaml:

pre-commit install

After that your code will be automatically reformatted on every new commit.

To reformat all files in the project use command:

pre-commit run -a

To update hook versions in .pre-commit-config.yaml use:

pre-commit autoupdate
Set private environment variables in .env file

System specific variables (e.g. absolute paths to datasets) should not be under version control or it will result in conflict between different users. Your private keys also shouldn't be versioned since you don't want them to be leaked.

Template contains .env.example file, which serves as an example. Create a new file called .env (this name is excluded from version control in .gitignore). You should use it for storing environment variables like this:

MY_VAR=/home/user/my_system_path

All variables from .env are loaded in train.py automatically.

Hydra allows you to reference any env variable in .yaml configs like this:

path_to_data: ${oc.env:MY_VAR}
Name metrics using '/' character

Depending on which logger you're using, it's often useful to define metric name with / character:

self.log("train/loss", loss)

This way loggers will treat your metrics as belonging to different sections, which helps to get them organised in UI.

Use torchmetrics

Use official torchmetrics library to ensure proper calculation of metrics. This is especially important for multi-GPU training!

For example, instead of calculating accuracy by yourself, you should use the provided Accuracy class like this:

from torchmetrics.classification.accuracy import Accuracy


class LitModel(LightningModule):
    def __init__(self)
        self.train_acc = Accuracy()
        self.val_acc = Accuracy()

    def training_step(self, batch, batch_idx):
        ...
        acc = self.train_acc(predictions, targets)
        self.log("train/acc", acc)
        ...

    def validation_step(self, batch, batch_idx):
        ...
        acc = self.val_acc(predictions, targets)
        self.log("val/acc", acc)
        ...

Make sure to use different metric instance for each step to ensure proper value reduction over all GPU processes.

Torchmetrics provides metrics for most use cases, like F1 score or confusion matrix. Read documentation for more.

Follow PyTorch Lightning style guide

The style guide is available here.

  1. Be explicit in your init. Try to define all the relevant defaults so that the user doesn’t have to guess. Provide type hints. This way your module is reusable across projects!

    class LitModel(LightningModule):
        def __init__(self, layer_size: int = 256, lr: float = 0.001):
  2. Preserve the recommended method order.

    class LitModel(LightningModule):
    
        def __init__():
            ...
    
        def forward():
            ...
    
        def training_step():
            ...
    
        def training_step_end():
            ...
    
        def on_train_epoch_end():
            ...
    
        def validation_step():
            ...
    
        def validation_step_end():
            ...
    
        def on_validation_epoch_end():
            ...
    
        def test_step():
            ...
    
        def test_step_end():
            ...
    
        def on_test_epoch_end():
            ...
    
        def configure_optimizers():
            ...
    
        def any_extra_hook():
            ...
Version control your data and models with DVC

Use DVC to version control big files, like your data or trained ML models.
To initialize the dvc repository:

dvc init

To start tracking a file or directory, use dvc add:

dvc add data/MNIST

DVC stores information about the added file (or a directory) in a special .dvc file named data/MNIST.dvc, a small text file with a human-readable format. This file can be easily versioned like source code with Git, as a placeholder for the original data:

git add data/MNIST.dvc data/.gitignore
git commit -m "Add raw data"
Support installing project as a package

It allows other people to easily use your modules in their own projects. Change name of the src folder to your project name and complete the setup.py file.

Now your project can be installed from local files:

pip install -e .

Or directly from git repository:

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:

from project_name.models.mnist_module import MNISTLitModule
from project_name.data.mnist_datamodule import MNISTDataModule
Keep local configs out of code versioning

Some configurations are user/machine/installation specific (e.g. configuration of local cluster, or harddrive paths on a specific machine). For such scenarios, a file configs/local/default.yaml can be created which is automatically loaded but not tracked by Git.

For example, you can use it for a SLURM cluster config:

# @package _global_

defaults:
  - override /hydra/launcher@_here_: submitit_slurm

data_dir: /mnt/scratch/data/

hydra:
  launcher:
    timeout_min: 1440
    gpus_per_task: 1
    gres: gpu:1
  job:
    env_set:
      MY_VAR: /home/user/my/system/path
      MY_KEY: asdgjhawi8y23ihsghsueity23ihwd

Resources

This template was inspired by:

Other useful repositories:


License

Lightning-Hydra-Template is licensed under the MIT License.

MIT License

Copyright (c) 2021 ashleve

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.




DELETE EVERYTHING ABOVE FOR YOUR PROJECT


Your Project Name

PyTorch Lightning Config: Hydra Template
Paper Conference

Description

What it does

Installation

Pip

# clone project
git clone https://github.com/YourGithubName/your-repo-name
cd your-repo-name

# [OPTIONAL] create conda environment
conda create -n myenv python=3.9
conda activate myenv

# install pytorch according to instructions
# https://pytorch.org/get-started/

# install requirements
pip install -r requirements.txt

Conda

# clone project
git clone https://github.com/YourGithubName/your-repo-name
cd your-repo-name

# create conda environment and install dependencies
conda env create -f environment.yaml -n myenv

# activate conda environment
conda activate myenv

How to run

Train model with default configuration

# train on CPU
python src/train.py trainer=cpu

# train on GPU
python src/train.py trainer=gpu

Train model with chosen experiment configuration from configs/experiment/

python src/train.py experiment=experiment_name.yaml

You can override any parameter from command line like this

python src/train.py trainer.max_epochs=20 data.batch_size=64

lightning-hydra-template's People

Contributors

adizx12 avatar amorehead avatar ashleve avatar atong01 avatar binlee52 avatar caplett avatar cauliyang avatar charlesbmi avatar charlesgaydon avatar colobas avatar dependabot[bot] avatar dreaquil avatar elisim avatar eungbean avatar gscriva avatar gxinhu avatar hotthoughts avatar johnnynunez avatar luciennnnnnn avatar nils-werner avatar phimos avatar sirtris avatar steve-tod avatar tbazin avatar tesfaldet avatar yipliu avatar yongtae723 avatar yu-xiang-wang avatar yucao16 avatar zhengyu-yang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lightning-hydra-template's Issues

Optuna sweep stop hparams search study after some trails

My Optuna sweep always stops hparams search study after some trials, can you help me?
I run my code in 5 fold cross-validation style:

def train():
  acc = []
  for fold in range(fold_num):
    # init model, logger...
    train_model()
    test_model()
    acc.append(val/acc)

  return mean(acc)

And the sweep YAML file is following:

defaults:
  - override /hydra/sweeper: optuna
  
 optimized_metric: "val/mean_acc"

hydra:
  sweeper:
      _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper
      storage: null
      study_name: null
      n_jobs: 1
  direction: maximize
  n_trials: 500

  sampler:
        _target_: optuna.samplers.TPESampler
        seed: 2021
        consider_prior: true
        prior_weight: 1.0
        consider_magic_clip: true
        consider_endpoints: false
        n_startup_trials: 10
        n_ei_candidates: 24
        multivariate: false
        warn_independent_sampling: true

How to load configurations of the previous experiment?

Say I have run multiple experiments and each saves config.yaml, hydra.yaml, and overrides.yaml. Now I want to rerun the best one. It seems that the config path is fixed in run.py, so I wonder there is an easy way to reload the specified configurations without need to modify run.py?

adding a linter

Hi,

Thank you for the great work.
Do you consider adding pylint to this template?

It might be really useful.

Thank you

is it possible to loop through wandb sweep?

Hi @ashleve ,

I'm wondering if it's possible to loop through sweeps.

For example, I have 2 datasets: A, and B.
according to ur solution here
I must sweep these 2 dataset individually by launching 2 wandb agents.

Is there any workaround where I can just call wandb sweep <config.yaml> once, and it will sweep these 2 datasets sequentially?

Thanks for your help!

Custom Callbacks

hi,
I am trying to write a custom callback.
Where and how does the callback object actually get instantiated?
Or more specifically how can I pass arguments to the callback?

My callback looks like this:

class ImagePredictionLogger(Callback):
    def __init__(self, val_samples, num_samples=32):
        super().__init__()
        self.num_samples = num_samples
        self.val_imgs, self.val_labels = val_samples

    def on_validation_epoch_end(self, trainer, pl_module):
        ...

When I run the code I get:
TypeError: Error instantiating 'src.callbacks.wandb_callbacks.ImageLogger' : __init__() missing 1 required positional argument: 'val_samples'

Which I guess makes sense but how can I pass the argument to the callback?
Thanks

"Release" versions for this template?

Great work on the updates! I'm wondering if you'd consider tagging stable releases. With all the commits recently, I'm not sure what features are still in development and what's ready to be used. Thanks!

Horovod error: TypeError: __init__() missing 2 required positional arguments: 'named_parameters' and 'compression'

Reproduce command

mpirun -np 2 python run.py +trainer.accelerator=horovod

the error is raised during trainer.test().

the full error info is below

Error executing job with overrides: ['+trainer.accelerator=horovod']
Traceback (most recent call last):
  File "run.py", line 31, in main
    return train(config)
  File "/home/user/code/lightning-hydra-template/src/train.py", line 82, in train
    trainer.test()
  File "/home/user/.conda/envs/torch18/lib/python3.8/site-packages/pytorch_lightning/trainer/trainer.py", line 579, in test
    results = self._run(model)
  File "/home/user/.conda/envs/torch18/lib/python3.8/site-packages/pytorch_lightning/trainer/trainer.py", line 753, in _run
    self.pre_dispatch()
  File "/home/user/.conda/envs/torch18/lib/python3.8/site-packages/pytorch_lightning/trainer/trainer.py", line 778, in pre_dispatch
    self.accelerator.pre_dispatch(self)
  File "/home/user/.conda/envs/torch18/lib/python3.8/site-packages/pytorch_lightning/accelerators/accelerator.py", line 108, in pre_dispatch
    self.training_type_plugin.pre_dispatch()
  File "/home/user/.conda/envs/torch18/lib/python3.8/site-packages/pytorch_lightning/plugins/training_type/horovod.py", line 93, in pre_dispatch
    optimizers = [
  File "/home/user/.conda/envs/torch18/lib/python3.8/site-packages/pytorch_lightning/plugins/training_type/horovod.py", line 94, in <listcomp>
    hvd.DistributedOptimizer(
  File "/home/user/.conda/envs/torch18/lib/python3.8/site-packages/horovod/torch/optimizer.py", line 585, in DistributedOptimizer
    return cls(optimizer.param_groups, named_parameters, compression, backward_passes_per_step, op,
  File "/home/user/.conda/envs/torch18/lib/python3.8/site-packages/horovod/torch/optimizer.py", line 41, in __init__
    super(self.__class__, self).__init__(params)
TypeError: __init__() missing 2 required positional arguments: 'named_parameters' and 'compression'

Conda setup script failes for CUDA11.1

Installing cudatoolkit=11.1 requires adding '-c nvidia'. See https://pytorch.org/get-started/locally/

I suggest the following addition:
`

Install pytorch

if [ "$cuda_version" == "none" ]; then
conda install -y pytorch=$pytorch_version torchvision torchaudio cpuonly -c pytorch
elif [ "$cuda_version" == "10.2" ]; then
conda install -y pytorch=$pytorch_version torchvision torchaudio cudatoolkit=$cuda_version -c pytorch
else
conda install -y pytorch=$pytorch_version torchvision torchaudio cudatoolkit=$cuda_version -c pytorch -c nvidia
`

BR Christian

ps. The template is awesome! ;)

Multi-GPU training on DDP mode will log multiple times

I notice when I use +trainer.accelerator="ddp", the log file have repeated logs(The number of repeats is equal to the number of GPUs), refer to official docs, "Lightning implementation of DDP calls your script under the hood multiple times with the correct environment variables:".
So we need a solution to handle this problem since DDP mode is much faster than DDP_spawn.

Resubmit on slurm environment

I run experiments on a slurm environment with a time limit. I want to re-submit my job if it is not completed. Pytorch Lightning handles this by reload the weight. I test the code in this repo but find that resubmit on slurm is not supported.

I wonder how to enable resubmit in slurm environment. This is a great repo and I hope it can be further improved.

Thanks in advance.

Add ability to resume training from latest checkpoint without specifying path

Add some kind of method to recursively go over everything in logs/, and find the latest saved checkpoint (find by date saved).
Add config flag for resuming training from the latest checkpoint:

resume_latest: True

Useful when we want to quickly resume our latest run without specifying ckpt path.

Should be added as an enhancement to utils.extras().

Could also automatically override the whole config with the correct one from .hydra folder.

Thoughts on making run.py more generic for calling other scripts?

Hi, thanks for this awesome template, its super clean!

I was thinking about what might be a good way to add more tasks to the config other than just training a pytorch lightning model, yet, aim to keep things clean, (more on that below). Some tasks could be:

  • evaluating a trained model
  • training a tokenizer
  • building a dataset (downloading, or doing preprocessing , etc)

About keeping things clean:

In the project https://github.com/Erlemar/pytorch_tempest, the author uses multiple scripts for different tasks, e.g., train.py. train_ner.py, predict.py... but I don't like the idea of placing many scripts in the top level directory. Also, placing them all in a scripts/ directory would make it awkward to work with code in src/ without pip installing that code. I like that in your template everything can be run without packaging the code in src, and how there's only a single script in the top level directory of the project. So, I'm thinking I'd like to try and extend run.py to support more tasks.

I'm wondering if you have any thoughts on how to structure the config in a way such that run.py could be generalized for performing more tasks? Example usage might be something like:

python run.py task=train_pl_model <TAB>

and hydra would suggest all the valid options that apply to the "train_pl_model" task.

Would this mean all the existing config files would need to be grouped together in a new sub directory corresponding to that task?

I'm new to hydra and learning as I go, so just thought I'd ask for your thoughts to see if it makes sense or if there is any plan to take this template in a similar direction in the future already. Thanks!

get_wandb_logger fails to retrieve WandbLogger when debug=True

Firstly, I love this repo - really great job!!
Maybe this not really a bug, but more of a "watch out for this"-kinda thing, which can be documented somewhere in the README.

Error:
Exception: You are using wandb related callback, but WandbLogger was not found for some reason...
This error occures when calling the function src.callbacks.wandb_callbacks.get_wandb_logger().

How to reproduce:

  1. Clone repo
  2. python run.py debug=True logger=wandb callbacks=wandb

Relevant information
pytorch_lightning==1.4.0

The problem
When setting debug=True, the Trainer is passed fast_dev_run=True.
In this mode, pytorch_lightning disables all logger(s), which causes get_wandb_logger() to fail.
https://pytorch-lightning.readthedocs.io/en/latest/common/debugging.html
Upon inspection of the trainer object. The trainer.logger is of type pytorch_lightning.loggers.base.DummyLogger, which I assume is the placeholder logger that lightning uses with fast_dev_run=True.
https://pytorch-lightning.readthedocs.io/en/latest/api/pytorch_lightning.loggers.base.html#pytorch_lightning.loggers.base.DummyLogger

I assume this is one of the reasons you have made a debug.yaml which uses fast_dev_run=False. My suggestion is to mention this as an option in the debugging section of the README.

This repo is awesome!

Hey @hobogalaxy , this template/boilerplate is spectacular! It's exactly what I've been looking for for the past couple of years. No issues to report, just wanted to say keep up the good work :) Thanks so much for your useful contribution.

TF2.0 template

Hi!
Thanks for an awesome work
I wanted to ask, if there is anything similar to this template but for TF2.0 + Hydra bundle?
Didn't manage to find anything relevant on the GitHub

Best regards

How to disable hydra logging if run with debug=True?

Not sure how to achieve this -- in the utils.py file, I see you are modifying the config object, but I am not sure how we can control the hydra configuration if run with debug flag since it is deleted from the config by hydra automatically.

[Bug] Top level config has to be OmegaConf DictConfig, plain dict, or a Structured Config class or instance

πŸ› Bug

Description

I am creating a Multilingual Text Classifier using PyTorch Lightning and Hydra. I am using this template as reference for the project. However when I try to run the run.py file I keep getting an error.

Relevant Files

run.py

import dotenv
import hydra
from hydra.core.hydra_config import HydraConfig
from omegaconf import DictConfig
from pathlib import Path

dotenv.load_dotenv(override = True)

import sys
sys.path.append("/workspace/data/multilingual-text-classifier/src")

@hydra.main(config_path="/workspace/data/multilingual-text-classifier/configs/", config_name="config.yaml")
def main(config: DictConfig):

    # Imports should be nested inside @hydra.main to optimize tab completion
    # Read more here: https://github.com/facebookresearch/hydra/issues/934
    
    hydra_dir = Path(HydraConfig.get().run.dir)
    
    from train import train

    # Train model
    return train(config)

if __name__ == "__main__":
    main()

train.py

import hydra
from omegaconf import DictConfig
from pytorch_lightning import (
                        LightningDataModule,
                        LightningModule,
                        Trainer,
                        seed_everything
                    )

from datamodules.datamodule import JigsawDataModule

# Lightning
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from pytorch_lightning.loggers import TensorBoardLogger

from models.model import BERTModel

from termcolor import colored
import time

from typing import Optional

def train(config: DictConfig) -> Optional[float]:
       
    model: LightningModule =  hydra.utils.instantiate(config.model)

    logger = TensorBoardLogger("lightning_logs", name="toxic-comments")

    early_stopping_callback = EarlyStopping(monitor='val_loss', patience=2)

    trainer = pl.Trainer(
                logger=logger,
                callbacks=[early_stopping_callback],
                max_epochs=2,
                gpus=[0],
                progress_bar_refresh_rate=30,
                precision= 32
            )

    trainer.fit(model, datamodule = JigsawDataModule)

    trainer.save_checkpoint("/workspace/data/multilingual-text-classifier/model.ckpt")

config.yaml

model: model.yaml

model.yaml

_target_: src.models.model.BERTModel

TRAIN_BATCH_SIZE: 32
VALID_BATCH_SIZE: 64
EPOCHS: 2
LEARNING_RATE: 0.5 * 1e-5

Error

Error executing job with overrides: []
Traceback (most recent call last):
  File "run.py", line 41, in <module>
    main()
  File "/opt/conda/lib/python3.6/site-packages/hydra/main.py", line 53, in decorated_main
    config_name=config_name,
  File "/opt/conda/lib/python3.6/site-packages/hydra/_internal/utils.py", line 368, in _run_hydra
    lambda: hydra.run(
  File "/opt/conda/lib/python3.6/site-packages/hydra/_internal/utils.py", line 214, in run_and_report
    raise ex
  File "/opt/conda/lib/python3.6/site-packages/hydra/_internal/utils.py", line 211, in run_and_report
    return func()
  File "/opt/conda/lib/python3.6/site-packages/hydra/_internal/utils.py", line 371, in <lambda>
    overrides=args.overrides,
  File "/opt/conda/lib/python3.6/site-packages/hydra/_internal/hydra.py", line 110, in run
    _ = ret.return_value
  File "/opt/conda/lib/python3.6/site-packages/hydra/core/utils.py", line 233, in return_value
    raise self._return_value
  File "/opt/conda/lib/python3.6/site-packages/hydra/core/utils.py", line 160, in run_job
    ret.return_value = task_function(task_cfg)
  File "run.py", line 38, in main
    return train(config)
  File "/workspace/data/multilingual-text-classifier/src/train.py", line 41, in train
    model: LightningModule =  hydra.utils.instantiate(config.model)
  File "/opt/conda/lib/python3.6/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 183, in instantiate
    "Top level config has to be OmegaConf DictConfig, plain dict, or a Structured Config class or instance"
hydra.errors.InstantiationException: Top level config has to be OmegaConf DictConfig, plain dict, or a Structured Config class or instance

System information

  • Hydra Version : 1.1.0
  • Python version : 3.6.10
  • Virtual environment type and version : conda 4.8.4
  • Operating system : Windows

Remove WANDB_START_METHOD: thread

In a related issue of hydra I found out that setting WANDB_START_METHOD: thread is no longer required for hydra sweeps and it also affects hydra logging.
If you can confirm that the environment variable has become unnecessary I propose it would be an enhancement to remove it from the configuration. Also thank you for the great template. πŸ‘

trainer `ddp.yaml` doesn't override `default.yaml`?

Hi there,

This template is awesome, and I'm running some examples with it right now.

In configs/config.yaml, I changed

...
# specify here default training configuration
defaults:
  - trainer: default.yaml
...

but when I call python run.py trainer.gpus=4 trainer=ddp it only runs ddp.yaml configs without overriding the default.yaml.

Is this behavior expected? because when I'm reading lightning-transformer , by passing trainer=sharded, it actually overwrites the default.yaml like

trainer:
-  gpus: null
+  gpus: 1
   auto_select_gpus: false
   tpu_cores: null
   log_gpu_memory: null
   ...
   log_every_n_steps: 50
-  accelerator: null
+  accelerator: ddp
   sync_batchnorm: false
-  precision: 32
+  precision: 16
   weights_summary: top
   ....
   terminate_on_nan: false
   auto_scale_batch_size: false
   prepare_data_per_node: true
-  plugins: null
+  plugins:
+    _target_: pytorch_lightning.plugins.DDPShardedPlugin
   amp_backend: native
   amp_level: O2
   move_metrics_to_cpu: false
...

Multi-GPU bugs, AttributeError: Can't pickle local object 'log_hyperparameters.<locals>.<lambda>'

When I use Multi-GPU with 4 3090, I ran into AttributeError: Can't pickle local object 'log_hyperparameters..', it seems due to trainer.logger.log_hyperparams = lambda params: None trick in log_hyperparameters.

Traceback (most recent call last):
File "/ghome/luoxin/projects/liif-lightning-hydra/run.py", line 34, in main
return train(config)
File "/ghome/luoxin/projects/liif-lightning-hydra/src/train.py", line 78, in train
trainer.fit(model=model, datamodule=datamodule)
File "/opt/conda/lib/python3.8/site-packages/pytorch_lightning/trainer/trainer.py", line 499, in fit
self.dispatch()
File "/opt/conda/lib/python3.8/site-packages/pytorch_lightning/trainer/trainer.py", line 546, in dispatch
self.accelerator.start_training(self)
File "/opt/conda/lib/python3.8/site-packages/pytorch_lightning/accelerators/accelerator.py", line 73, in start_training
self.training_type_plugin.start_training(trainer)
File "/opt/conda/lib/python3.8/site-packages/pytorch_lightning/plugins/training_type/ddp_spawn.py", line 108, in start_training
mp.spawn(self.new_process, **self.mp_spawn_kwargs)
File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 230, in spawn
return start_processes(fn, args, nprocs, join, daemon, start_method='spawn')
File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 179, in start_processes
process.start()
File "/opt/conda/lib/python3.8/multiprocessing/process.py", line 121, in start
self._popen = self._Popen(self)
File "/opt/conda/lib/python3.8/multiprocessing/context.py", line 284, in _Popen
return Popen(process_obj)
File "/opt/conda/lib/python3.8/multiprocessing/popen_spawn_posix.py", line 32, in init
super().init(process_obj)
File "/opt/conda/lib/python3.8/multiprocessing/popen_fork.py", line 19, in init
self._launch(process_obj)
File "/opt/conda/lib/python3.8/multiprocessing/popen_spawn_posix.py", line 47, in _launch
reduction.dump(process_obj, fp)
File "/opt/conda/lib/python3.8/multiprocessing/reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'log_hyperparameters..'

access to neptune Run obj error

I find Neptune Run obj has more logging method can be used, like log pandas obj, so I modify the neptune.yaml:

neptune:
#  _target_: pytorch_lightning.loggers.neptune.NeptuneLogger
  _target_: neptune.new.integrations.pytorch_lightning.NeptuneLogger
  api_key: 
  project:

And in your train.py, the logger is a list:

    # Init lightning loggers
    logger: List[LightningLoggerBase] = []
    if "logger" in config:
        for _, lg_conf in config.logger.items():
            if "_target_" in lg_conf:
                log.info(f"Instantiating logger <{lg_conf._target_}>")
                logger.append(hydra.utils.instantiate(lg_conf)

In my LightningModule obj, I access the Run obj by self.logger.experiment[''], but find error:

TypeError: list indices must be integers or slices, not str

Because there is only one logger obj in logger, I fix the error by:

self.logger.experiment[0]['']

Although I fix the error, other logging methods in the logger list my not work, how to solve this problem? Thanks.

val logs are interspersed in training logs

2021/08/16 14:12:09 Β 
2021/08/16 14:12:09 Validation sanity check: 0it [00:00, ?it/s]
2021/08/16 14:12:09 Validation sanity check: 0%| | 0/2 [00:00<?, ?it/s]
2021/08/16 14:12:09 Training: -1it [00:00, ?it/s]
2021/08/16 14:12:09 Training: 0%| | 0/74 [00:00<00:00, 49344.75it/s]
2021/08/16 14:12:10 Epoch 0: 0%| | 0/74 [00:00<00:00, 3792.32it/s]
2021/08/16 14:12:10 Epoch 0: 7%|##3 | 5/74 [00:00<00:10, 6.76it/s]
2021/08/16 14:12:11 Epoch 0: 7%|8 | 5/74 [00:00<00:10, 6.76it/s, loss=1.11, v_num=N-35]
2021/08/16 14:12:11 Epoch 0: 14%|#4 | 10/74 [00:01<00:11, 5.51it/s, loss=1.11, v_num=N-35]
2021/08/16 14:12:12 Epoch 0: 14%|#4 | 10/74 [00:01<00:11, 5.50it/s, loss=1.06, v_num=N-35]
2021/08/16 14:12:12 Epoch 0: 20%|##2 | 15/74 [00:02<00:10, 5.51it/s, loss=1.06, v_num=N-35]
2021/08/16 14:12:13 Epoch 0: 20%|##2 | 15/74 [00:02<00:10, 5.50it/s, loss=1.09, v_num=N-35]
2021/08/16 14:12:13 Epoch 0: 27%|##9 | 20/74 [00:03<00:10, 5.28it/s, loss=1.09, v_num=N-35]
2021/08/16 14:12:14 Epoch 0: 27%|##9 | 20/74 [00:03<00:10, 5.28it/s, loss=1.05, v_num=N-35]
2021/08/16 14:12:14 Epoch 0: 34%|###7 | 25/74 [00:04<00:09, 5.36it/s, loss=1.05, v_num=N-35]
2021/08/16 14:12:15 Epoch 0: 34%|###3 | 25/74 [00:04<00:09, 5.36it/s, loss=0.968, v_num=N-35]
2021/08/16 14:12:15 Epoch 0: 41%|#### | 30/74 [00:05<00:08, 5.25it/s, loss=0.968, v_num=N-35]
2021/08/16 14:12:16 Epoch 0: 41%|#### | 30/74 [00:05<00:08, 5.25it/s, loss=0.948, v_num=N-35]
2021/08/16 14:12:16 Epoch 0: 47%|####7 | 35/74 [00:06<00:07, 5.29it/s, loss=0.948, v_num=N-35]
2021/08/16 14:12:17 Epoch 0: 47%|####7 | 35/74 [00:06<00:07, 5.29it/s, loss=0.851, v_num=N-35]
2021/08/16 14:12:17 Epoch 0: 54%|#####4 | 40/74 [00:07<00:06, 5.26it/s, loss=0.851, v_num=N-35]
2021/08/16 14:12:18 Epoch 0: 54%|#####4 | 40/74 [00:07<00:06, 5.25it/s, loss=0.892, v_num=N-35]
2021/08/16 14:12:18 Epoch 0: 61%|###### | 45/74 [00:08<00:05, 5.22it/s, loss=0.892, v_num=N-35]
2021/08/16 14:12:19 Epoch 0: 61%|###### | 45/74 [00:08<00:05, 5.22it/s, loss=0.879, v_num=N-35]
2021/08/16 14:12:19 Epoch 0: 68%|######7 | 50/74 [00:09<00:04, 5.23it/s, loss=0.879, v_num=N-35]
2021/08/16 14:12:20 Epoch 0: 68%|#######4 | 50/74 [00:09<00:04, 5.23it/s, loss=0.83, v_num=N-35]
2021/08/16 14:12:20 Epoch 0: 74%|########1 | 55/74 [00:10<00:03, 5.19it/s, loss=0.83, v_num=N-35]
2021/08/16 14:12:20 Epoch 0: 74%|#######4 | 55/74 [00:10<00:03, 5.19it/s, loss=0.847, v_num=N-35]
2021/08/16 14:12:20 Epoch 0: 81%|########1 | 60/74 [00:11<00:02, 5.31it/s, loss=0.847, v_num=N-35]
2021/08/16 14:12:21 Validating: 0it [00:00, ?it/s]
2021/08/16 14:12:21 Validating: 0%| | 0/15 [00:00<?, ?it/s]
2021/08/16 14:12:21 Validating: 33%|##########6 | 5/15 [00:00<00:00, 36.64it/s]
2021/08/16 14:12:21 Epoch 0: 88%|########7 | 65/74 [00:11<00:01, 5.68it/s, loss=0.847, v_num=N-35]
2021/08/16 14:12:21 Validating: 67%|####################6 | 10/15 [00:00<00:00, 37.37it/s]
2021/08/16 14:12:21 Epoch 0: 95%|#########4| 70/74 [00:11<00:00, 6.05it/s, loss=0.847, v_num=N-35]
2021/08/16 14:12:23 Validating: 100%|###############################| 15/15 [00:00<00:00, 37.81it/s]
2021/08/16 14:12:23 Epoch 0: 100%|#| 74/74 [00:14<00:00, 5.24it/s, loss=0.827, v_num=N-35, val/loss
2021/08/16 14:12:24 Epoch 0: 0%| | 0/74 [00:00<00:00, 10565.00it/s, loss=0.827, v_num=N-35, val/lo
2021/08/16 14:12:25 Epoch 1: 0%| | 0/74 [00:00<00:00, 474.79it/s, loss=0.827, v_num=N-35, val/loss
2021/08/16 14:12:25 Epoch 1: 7%| | 5/74 [00:00<00:11, 6.04it/s, loss=0.827, v_num=N-35, val/loss=
2021/08/16 14:12:26 Epoch 1: 7%| | 5/74 [00:00<00:11, 6.04it/s, loss=0.828, v_num=N-35, val/loss=
2021/08/16 14:12:26 Epoch 1: 14%|1| 10/74 [00:02<00:12, 5.13it/s, loss=0.828, v_num=N-35, val/loss
2021/08/16 14:12:27 Epoch 1: 14%|1| 10/74 [00:02<00:12, 5.13it/s, loss=0.843, v_num=N-35, val/loss
2021/08/16 14:12:27 Epoch 1: 20%|2| 15/74 [00:03<00:11, 5.26it/s, loss=0.843, v_num=N-35, val/loss
2021/08/16 14:12:28 Epoch 1: 20%|2| 15/74 [00:03<00:11, 5.25it/s, loss=0.885, v_num=N-35, val/loss

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.