Dev (#135)
* remove logging best so far metric values from mnist model * update tests * update README.md * comment out wandb tests
This commit is contained in:
1 parent
4bdf4e62c6
commit
d5da445e8d
7 files changed
+63
-110
No files matched your search
@@ -276,7 +276,7 @@ python run.py trainer.weights_summary="full"
|
|||||||
python run.py +trainer.profiler="simple"
|
python run.py +trainer.profiler="simple"
|
||||||
|
|
||||||
# raise exception, if any of the parameters or the loss are NaN or +/-inf
|
# raise exception, if any of the parameters or the loss are NaN or +/-inf
|
||||||
python run.py trainer.terminate_on_nan=true
|
python run.py +trainer.terminate_on_nan=true
|
||||||
|
|
||||||
# try overfitting to 1 batch
|
# try overfitting to 1 batch
|
||||||
python run.py +trainer.overfit_batches=1 trainer.max_epochs=20
|
python run.py +trainer.overfit_batches=1 trainer.max_epochs=20
|
||||||
@@ -320,7 +320,7 @@ python run.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
|
|||||||
<details>
|
<details>
|
||||||
<summary><b>Create a sweep over hyperparameters with Optuna</b></summary>
|
<summary><b>Create a sweep over hyperparameters with Optuna</b></summary>
|
||||||
|
|
||||||
> Using [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a [single config file](configs/config_optuna.yaml)!
|
> Using [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a [single config file](configs/hparams_search/mnist_optuna.yaml)!
|
||||||
```yaml
|
```yaml
|
||||||
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
|
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
|
||||||
# over chosen experiment config
|
# over chosen experiment config
|
||||||
@@ -435,14 +435,10 @@ defaults:
|
|||||||
- callbacks: default.yaml # set this to null if you don't want to use callbacks
|
- 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`)
|
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
|
||||||
|
|
||||||
- experiment: null
|
|
||||||
- hparams_search: null
|
|
||||||
|
|
||||||
- hydra: default.yaml
|
- hydra: default.yaml
|
||||||
|
|
||||||
# enable color logging
|
- experiment: null
|
||||||
- override hydra/hydra_logging: colorlog
|
- hparams_search: null
|
||||||
- override hydra/job_logging: colorlog
|
|
||||||
|
|
||||||
|
|
||||||
# path to original working directory
|
# path to original working directory
|
||||||
@@ -456,13 +452,6 @@ work_dir: ${hydra:runtime.cwd}
|
|||||||
data_dir: ${work_dir}/data/
|
data_dir: ${work_dir}/data/
|
||||||
|
|
||||||
|
|
||||||
# use `python run.py debug=true` for easy debugging!
|
|
||||||
# this will run 1 train, val and test loop with only 1 batch
|
|
||||||
# equivalent to running `python run.py trainer.fast_dev_run=true`
|
|
||||||
# (this is placed here just for easier access from command line)
|
|
||||||
debug: False
|
|
||||||
|
|
||||||
|
|
||||||
# pretty print config at the start of the run using Rich library
|
# pretty print config at the start of the run using Rich library
|
||||||
print_config: True
|
print_config: True
|
||||||
|
|
||||||
@@ -516,7 +505,7 @@ datamodule:
|
|||||||
|
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary><b>Advanced example</b></summary>
|
<summary><b>Show advanced example</b></summary>
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# to execute this experiment run:
|
# to execute this experiment run:
|
||||||
@@ -642,7 +631,7 @@ defaults:
|
|||||||
|
|
||||||
|
|
||||||
# choose metric which will be optimized by Optuna
|
# choose metric which will be optimized by Optuna
|
||||||
optimized_metric: "val/acc_best"
|
optimized_metric: "val/acc"
|
||||||
|
|
||||||
|
|
||||||
hydra:
|
hydra:
|
||||||
@@ -697,8 +686,8 @@ hydra:
|
|||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
Next, you can execute it with: `python run.py hparams_search=hparams_config_name`. <br>
|
Next, you can execute it with: `python run.py -m hparams_search=mnist_optuna`<br>
|
||||||
Using this approach doesn't require you to add any boilerplate into your pipeline, everything is defined in a single config file! You can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad.
|
Using this approach doesn't require you to add any boilerplate into your pipeline, everything is defined in a single config file. You can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad.
|
||||||
<br><br>
|
<br><br>
|
||||||
|
|
||||||
|
|
||||||
@@ -753,18 +742,6 @@ You can run DDP on mnist example with 4 GPUs like this:
|
|||||||
python run.py trainer.gpus=4 +trainer.accelerator="ddp"
|
python run.py trainer.gpus=4 +trainer.accelerator="ddp"
|
||||||
```
|
```
|
||||||
⚠️ When using DDP you have to be careful how you write your models - learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html).
|
⚠️ When using DDP you have to be careful how you write your models - learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html).
|
||||||
<!--
|
|
||||||
<details>
|
|
||||||
<summary><b>Use metrics api objects</b></summary>
|
|
||||||
|
|
||||||
Use metrics api objects, e.g. `pytorch_lightning.metrics.classification.Accuracy` when logging metrics in `LightningModule`, to ensure proper reduction over multiple GPUs. You can also use `sync_dist` parameter instead with `self.log(..., sync_dist=True)`. Learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#synchronize-validation-and-test-logging).
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
3. Remember `outputs` parameters in hooks like `validation_epoch_end()` will contain only outputs from subset of data processed on given GPU.
|
|
||||||
4. Init tensors using `type_as` and `register_buffer`. Learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#init-tensors-using-type-as-and-register-buffer).
|
|
||||||
5. Make sure your model is pickable. Learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#make-models-pickleable).
|
|
||||||
-->
|
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
@@ -791,27 +768,6 @@ You can easily remove any of those by modifying [run.py](run.py) and [src/train.
|
|||||||
|
|
||||||
## Best Practices
|
## Best Practices
|
||||||
<!--<details>
|
<!--<details>
|
||||||
<summary><b>Write unit tests and smoke tests</b></summary>
|
|
||||||
|
|
||||||
Template comes with example tests implemented with pytest library. <br>
|
|
||||||
To execute them simply run:
|
|
||||||
```yaml
|
|
||||||
# run all tests
|
|
||||||
pytest
|
|
||||||
|
|
||||||
# run tests from specific file
|
|
||||||
pytest tests/smoke_tests/test_commands.py
|
|
||||||
|
|
||||||
# run all tests except the ones using wandb
|
|
||||||
pytest -k "not wandb"
|
|
||||||
```
|
|
||||||
I often find myself running into bugs that come out only in edge cases or on some specific hardware/environment. To speed up the development, I usually constantly execute simple bash scripts that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. Those kind of tests don't check for any specific output - they exists to simply verify that executing some commands doesn't end up in throwing exceptions. You can find them implemented in [tests/smoke_tests](tests/smoke_tests) folder.
|
|
||||||
|
|
||||||
You can easily modify the commands in the scripts for your use case. If even 1 epoch is too much for your model, then you can make it run for a couple of batches instead (by using the right trainer flags).<br>
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary><b>Use Docker</b></summary>
|
<summary><b>Use Docker</b></summary>
|
||||||
|
|
||||||
Docker makes it easy to initialize the whole training environment, e.g. when you want to execute experiments in cloud or on some private computing cluster. You can extend [dockerfiles](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles) provided in the template with your own instructions for building the image.<br>
|
Docker makes it easy to initialize the whole training environment, e.g. when you want to execute experiments in cloud or on some private computing cluster. You can extend [dockerfiles](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles) provided in the template with your own instructions for building the image.<br>
|
||||||
@@ -1051,7 +1007,7 @@ To setup this automation for bash, execute the following line:
|
|||||||
echo "autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
|
echo "autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
|
||||||
```
|
```
|
||||||
|
|
||||||
Now you can add any commands to your `.autoenv` file, e.g. activation of virual environment and hydra tab completion:
|
Now you can add any commands to your `.autoenv` file, e.g. activation of virtual environment and hydra tab completion:
|
||||||
```bash
|
```bash
|
||||||
# activate conda environment
|
# activate conda environment
|
||||||
conda activate myenv
|
conda activate myenv
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ defaults:
|
|||||||
|
|
||||||
|
|
||||||
# choose metric which will be optimized by Optuna
|
# choose metric which will be optimized by Optuna
|
||||||
optimized_metric: "val/acc_best"
|
optimized_metric: "val/acc"
|
||||||
|
|
||||||
|
|
||||||
hydra:
|
hydra:
|
||||||
|
|||||||
@@ -50,13 +50,6 @@ class MNISTLitModel(LightningModule):
|
|||||||
self.val_accuracy = Accuracy()
|
self.val_accuracy = Accuracy()
|
||||||
self.test_accuracy = Accuracy()
|
self.test_accuracy = Accuracy()
|
||||||
|
|
||||||
self.metric_hist = {
|
|
||||||
"train/acc": [],
|
|
||||||
"val/acc": [],
|
|
||||||
"train/loss": [],
|
|
||||||
"val/loss": [],
|
|
||||||
}
|
|
||||||
|
|
||||||
def forward(self, x: torch.Tensor):
|
def forward(self, x: torch.Tensor):
|
||||||
return self.model(x)
|
return self.model(x)
|
||||||
|
|
||||||
@@ -81,11 +74,8 @@ class MNISTLitModel(LightningModule):
|
|||||||
return {"loss": loss, "preds": preds, "targets": targets}
|
return {"loss": loss, "preds": preds, "targets": targets}
|
||||||
|
|
||||||
def training_epoch_end(self, outputs: List[Any]):
|
def training_epoch_end(self, outputs: List[Any]):
|
||||||
# log best so far train acc and train loss
|
# `outputs` is a list of dicts returned from `training_step()`
|
||||||
self.metric_hist["train/acc"].append(self.trainer.callback_metrics["train/acc"])
|
pass
|
||||||
self.metric_hist["train/loss"].append(self.trainer.callback_metrics["train/loss"])
|
|
||||||
self.log("train/acc_best", max(self.metric_hist["train/acc"]), prog_bar=False)
|
|
||||||
self.log("train/loss_best", min(self.metric_hist["train/loss"]), prog_bar=False)
|
|
||||||
|
|
||||||
def validation_step(self, batch: Any, batch_idx: int):
|
def validation_step(self, batch: Any, batch_idx: int):
|
||||||
loss, preds, targets = self.step(batch)
|
loss, preds, targets = self.step(batch)
|
||||||
@@ -98,11 +88,7 @@ class MNISTLitModel(LightningModule):
|
|||||||
return {"loss": loss, "preds": preds, "targets": targets}
|
return {"loss": loss, "preds": preds, "targets": targets}
|
||||||
|
|
||||||
def validation_epoch_end(self, outputs: List[Any]):
|
def validation_epoch_end(self, outputs: List[Any]):
|
||||||
# log best so far val acc and val loss
|
pass
|
||||||
self.metric_hist["val/acc"].append(self.trainer.callback_metrics["val/acc"])
|
|
||||||
self.metric_hist["val/loss"].append(self.trainer.callback_metrics["val/loss"])
|
|
||||||
self.log("val/acc_best", max(self.metric_hist["val/acc"]), prog_bar=False)
|
|
||||||
self.log("val/loss_best", min(self.metric_hist["val/loss"]), prog_bar=False)
|
|
||||||
|
|
||||||
def test_step(self, batch: Any, batch_idx: int):
|
def test_step(self, batch: Any, batch_idx: int):
|
||||||
loss, preds, targets = self.step(batch)
|
loss, preds, targets = self.step(batch)
|
||||||
|
|||||||
@@ -2,6 +2,12 @@ from tests.helpers.run_command import run_command
|
|||||||
from tests.helpers.runif import RunIf
|
from tests.helpers.runif import RunIf
|
||||||
|
|
||||||
|
|
||||||
|
def test_fast_dev_run():
|
||||||
|
"""Run 1 train, val, test batch."""
|
||||||
|
command = ["run.py", "trainer=default", "trainer.fast_dev_run=true"]
|
||||||
|
run_command(command)
|
||||||
|
|
||||||
|
|
||||||
def test_default_cpu():
|
def test_default_cpu():
|
||||||
"""Test default configuration on CPU."""
|
"""Test default configuration on CPU."""
|
||||||
command = ["run.py", "trainer.max_epochs=1", "trainer.gpus=0"]
|
command = ["run.py", "trainer.max_epochs=1", "trainer.gpus=0"]
|
||||||
@@ -20,12 +26,6 @@ def test_default_gpu():
|
|||||||
run_command(command)
|
run_command(command)
|
||||||
|
|
||||||
|
|
||||||
def test_fast_dev_run():
|
|
||||||
"""Run 1 train, val, test batch."""
|
|
||||||
command = ["run.py", "trainer=default", "trainer.fast_dev_run=true"]
|
|
||||||
run_command(command)
|
|
||||||
|
|
||||||
|
|
||||||
def test_experiments():
|
def test_experiments():
|
||||||
"""Train 1 epoch with all experiment configs."""
|
"""Train 1 epoch with all experiment configs."""
|
||||||
command = ["run.py", "-m", "experiment=glob(*)", "trainer.max_epochs=1"]
|
command = ["run.py", "-m", "experiment=glob(*)", "trainer.max_epochs=1"]
|
||||||
|
|||||||
@@ -1,6 +1,14 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
from tests.helpers.run_command import run_command
|
from tests.helpers.run_command import run_command
|
||||||
|
|
||||||
|
"""
|
||||||
|
Use the following command to skip slow tests:
|
||||||
|
pytest -k "not slow"
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.slow
|
||||||
def test_default_sweep():
|
def test_default_sweep():
|
||||||
"""Test default Hydra sweeper."""
|
"""Test default Hydra sweeper."""
|
||||||
command = [
|
command = [
|
||||||
@@ -14,6 +22,7 @@ def test_default_sweep():
|
|||||||
run_command(command)
|
run_command(command)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.slow
|
||||||
def test_optuna_sweep():
|
def test_optuna_sweep():
|
||||||
"""Test Optuna sweeper."""
|
"""Test Optuna sweeper."""
|
||||||
command = [
|
command = [
|
||||||
@@ -26,7 +35,9 @@ def test_optuna_sweep():
|
|||||||
run_command(command)
|
run_command(command)
|
||||||
|
|
||||||
|
|
||||||
# def test_ax_sweep():
|
@pytest.mark.skip(reason="TODO: Add Ax sweep config.")
|
||||||
# """Test Ax sweeper."""
|
@pytest.mark.slow
|
||||||
# command = ["run.py", "-m", "hparams_search=mnist_ax", "trainer.fast_dev_run=true"]
|
def test_ax_sweep():
|
||||||
# run_command(command)
|
"""Test Ax sweeper."""
|
||||||
|
command = ["run.py", "-m", "hparams_search=mnist_ax", "trainer.fast_dev_run=true"]
|
||||||
|
run_command(command)
|
||||||
@@ -8,33 +8,33 @@ Use the following command to skip wandb tests:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.wandb
|
# @pytest.mark.wandb
|
||||||
def test_wandb_optuna_sweep():
|
# def test_wandb_optuna_sweep():
|
||||||
"""Test wandb logging with Optuna sweep."""
|
# """Test wandb logging with Optuna sweep."""
|
||||||
command = [
|
# command = [
|
||||||
"run.py",
|
# "run.py",
|
||||||
"-m",
|
# "-m",
|
||||||
"hparams_search=mnist_optuna",
|
# "hparams_search=mnist_optuna",
|
||||||
"trainer=default",
|
# "trainer=default",
|
||||||
"trainer.max_epochs=10",
|
# "trainer.max_epochs=10",
|
||||||
"trainer.limit_train_batches=20",
|
# "trainer.limit_train_batches=20",
|
||||||
"logger=wandb",
|
# "logger=wandb",
|
||||||
"logger.wandb.project=template-tests",
|
# "logger.wandb.project=template-tests",
|
||||||
"logger.wandb.group=Optuna_SimpleDenseNet_MNIST",
|
# "logger.wandb.group=Optuna_SimpleDenseNet_MNIST",
|
||||||
"hydra.sweeper.n_trials=5",
|
# "hydra.sweeper.n_trials=5",
|
||||||
]
|
# ]
|
||||||
run_command(command)
|
# run_command(command)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.wandb
|
# @pytest.mark.wandb
|
||||||
def test_wandb_callbacks():
|
# def test_wandb_callbacks():
|
||||||
"""Test wandb callbacks."""
|
# """Test wandb callbacks."""
|
||||||
command = [
|
# command = [
|
||||||
"run.py",
|
# "run.py",
|
||||||
"trainer=default",
|
# "trainer=default",
|
||||||
"trainer.max_epochs=3",
|
# "trainer.max_epochs=3",
|
||||||
"logger=wandb",
|
# "logger=wandb",
|
||||||
"logger.wandb.project=template-tests",
|
# "logger.wandb.project=template-tests",
|
||||||
"callbacks=wandb",
|
# "callbacks=wandb",
|
||||||
]
|
# ]
|
||||||
run_command(command)
|
# run_command(command)
|
||||||
@@ -19,7 +19,7 @@ def test_something3(arg1: float):
|
|||||||
assert arg1 > 0
|
assert arg1 > 0
|
||||||
|
|
||||||
|
|
||||||
# use RunIf to skip execution of some tests when not on windows or when no gpus are available
|
# use RunIf to skip execution of some tests, e.g. when not on windows or when no gpus are available
|
||||||
@RunIf(skip_windows=True, min_gpus=1)
|
@RunIf(skip_windows=True, min_gpus=1)
|
||||||
def test_something4():
|
def test_something4():
|
||||||
"""Some test description."""
|
"""Some test description."""
|
||||||
|
|||||||
Reference in new issue
Block a user