13hannes11 commited on
Commit
e2d20e2
β€’
1 Parent(s): 1e6a198

Remove template parameters from repository

Browse files
Files changed (1) hide show
  1. README.md +6 -1398
README.md CHANGED
@@ -12,1412 +12,20 @@ tags:
12
  - pytorch
13
  ---
14
 
15
- <div align="center">
16
 
17
- # Lightning-Hydra-Template
18
-
19
- <a href="https://www.python.org/"><img alt="Python" src="https://img.shields.io/badge/-Python 3.7+-blue?style=for-the-badge&logo=python&logoColor=white"></a>
20
- <a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/-PyTorch 1.8+-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white"></a>
21
- <a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning 1.5+-792ee5?style=for-the-badge&logo=pytorchlightning&logoColor=white"></a>
22
- <a href="https://hydra.cc/"><img alt="Config: hydra" src="https://img.shields.io/badge/config-hydra 1.1-89b8cd?style=for-the-badge&labelColor=gray"></a>
23
- <a href="https://black.readthedocs.io/en/stable/"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge&labelColor=gray"></a>
24
-
25
- A clean and scalable template to kickstart your deep learning project πŸš€βš‘πŸ”₯<br>
26
- Click on [<kbd>Use this template</kbd>](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository.
27
-
28
- _Suggestions are always welcome!_
29
-
30
- </div>
31
-
32
- <br><br>
33
-
34
- ## πŸ“Œ&nbsp;&nbsp;Introduction
35
-
36
- This template tries to be as general as possible. It integrates many different MLOps tools.
37
-
38
- > Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended.
39
-
40
- **Why you should use it:** it allows you to rapidly iterate over new models/datasets and scale your projects from small single experiments to hyperparameter searches on computing clusters, without writing any boilerplate code. To my knowledge, it's one of the most convenient all-in-one technology stack for Deep Learning research. Good starting point for reproducing papers, kaggle competitions or small-team research projects. It's also a collection of best practices for efficient workflow and reproducibility.
41
-
42
- **Why you shouldn't use it:** this template is not fitted to be a production environment, should be used more as a fast experimentation tool. Apart from that, Lightning and Hydra are still evolving and integrate many libraries, which means sometimes things break - for the list of currently known bugs, visit [this page](https://github.com/ashleve/lightning-hydra-template/labels/bug). Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task. See [#Limitations](#limitations) for more.
43
-
44
- ### Why PyTorch Lightning?
45
-
46
- [PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning) is a lightweight PyTorch wrapper for high-performance AI research.
47
- It makes your code neatly organized and provides lots of useful features, like ability to run model on CPU, GPU, multi-GPU cluster and TPU.
48
-
49
- ### Why Hydra?
50
-
51
- [Hydra](https://github.com/facebookresearch/hydra) is an open-source Python framework that simplifies the development of research and other 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. It allows you to conveniently manage experiments and provides many useful plugins, like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) for hyperparameter search, or [Ray Launcher](https://hydra.cc/docs/next/plugins/ray_launcher) for running jobs on a cluster.
52
-
53
- <br>
54
-
55
- ## Main Ideas Of This Template
56
-
57
- - **Predefined Structure**: clean and scalable so that work can easily be extended and replicated | [#Project Structure](#project-structure)
58
- - **Rapid Experimentation**: thanks to automating pipeline with config files and hydra command line superpowers | [#Your Superpowers](#your-superpowers)
59
- - **Reproducibility**: obtaining similar results is supported in multiple ways | [#Reproducibility](#reproducibility)
60
- - **Little Boilerplate**: so pipeline can be easily modified | [#How It Works](#how-it-works)
61
- - **Main Configuration**: main config file specifies default training configuration | [#Main Project Configuration](#main-project-configuration)
62
- - **Experiment Configurations**: can be composed out of smaller configs and override chosen hyperparameters | [#Experiment Configuration](#experiment-configuration)
63
- - **Workflow**: comes down to 4 simple steps | [#Workflow](#workflow)
64
- - **Experiment Tracking**: many logging frameworks can be easily integrated, like Tensorboard, MLFlow or W&B | [#Experiment Tracking](#experiment-tracking)
65
- - **Logs**: all logs (checkpoints, data from loggers, hparams, etc.) are stored in a convenient folder structure imposed by Hydra | [#Logs](#logs)
66
- - **Hyperparameter Search**: made easier with Hydra built-in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) | [#Hyperparameter Search](#hyperparameter-search)
67
- - **Tests**: unit tests and shell/command based tests for speeding up the development | [#Tests](#tests)
68
- - **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility | [#Best Practices](#best-practices)
69
-
70
- <br>
71
-
72
- ## Project Structure
73
-
74
- The directory structure of new project looks like this:
75
-
76
- ```
77
- β”œβ”€β”€ configs <- Hydra configuration files
78
- β”‚ β”œβ”€β”€ callbacks <- Callbacks configs
79
- β”‚ β”œβ”€β”€ datamodule <- Datamodule configs
80
- β”‚ β”œβ”€β”€ debug <- Debugging configs
81
- β”‚ β”œβ”€β”€ experiment <- Experiment configs
82
- β”‚ β”œβ”€β”€ hparams_search <- Hyperparameter search configs
83
- β”‚ β”œβ”€β”€ local <- Local configs
84
- β”‚ β”œβ”€β”€ log_dir <- Logging directory configs
85
- β”‚ β”œβ”€β”€ logger <- Logger configs
86
- β”‚ β”œβ”€β”€ model <- Model configs
87
- β”‚ β”œβ”€β”€ trainer <- Trainer configs
88
- β”‚ β”‚
89
- β”‚ β”œβ”€β”€ test.yaml <- Main config for testing
90
- β”‚ └── train.yaml <- Main config for training
91
- β”‚
92
- β”œβ”€β”€ data <- Project data
93
- β”‚
94
- β”œβ”€β”€ logs <- Logs generated by Hydra and PyTorch Lightning loggers
95
- β”‚
96
- β”œβ”€β”€ notebooks <- Jupyter notebooks. Naming convention is a number (for ordering),
97
- β”‚ the creator's initials, and a short `-` delimited description,
98
- β”‚ e.g. `1.0-jqp-initial-data-exploration.ipynb`.
99
- β”‚
100
- β”œβ”€β”€ scripts <- Shell scripts
101
- β”‚
102
- β”œβ”€β”€ src <- Source code
103
- β”‚ β”œβ”€β”€ datamodules <- Lightning datamodules
104
- β”‚ β”œβ”€β”€ models <- Lightning models
105
- β”‚ β”œβ”€β”€ utils <- Utility scripts
106
- β”‚ β”œβ”€β”€ vendor <- Third party code that cannot be installed using PIP/Conda
107
- β”‚ β”‚
108
- β”‚ β”œβ”€β”€ testing_pipeline.py
109
- β”‚ └── training_pipeline.py
110
- β”‚
111
- β”œβ”€β”€ tests <- Tests of any kind
112
- β”‚ β”œβ”€β”€ helpers <- A couple of testing utilities
113
- β”‚ β”œβ”€β”€ shell <- Shell/command based tests
114
- β”‚ └── unit <- Unit tests
115
- β”‚
116
- β”œβ”€β”€ test.py <- Run testing
117
- β”œβ”€β”€ train.py <- Run training
118
- β”‚
119
- β”œβ”€β”€ .env.example <- Template of the file for storing private environment variables
120
- β”œβ”€β”€ .gitignore <- List of files/folders ignored by git
121
- β”œβ”€β”€ .pre-commit-config.yaml <- Configuration of pre-commit hooks for code formatting
122
- β”œβ”€β”€ requirements.txt <- File for installing python dependencies
123
- β”œβ”€β”€ setup.cfg <- Configuration of linters and pytest
124
- └── README.md
125
- ```
126
-
127
- <br>
128
-
129
- ## πŸš€&nbsp;&nbsp;Quickstart
130
-
131
- ```bash
132
- # clone project
133
- git clone https://github.com/ashleve/lightning-hydra-template
134
- cd lightning-hydra-template
135
-
136
- # [OPTIONAL] create conda environment
137
- conda create -n myenv python=3.8
138
- conda activate myenv
139
-
140
- # install pytorch according to instructions
141
- # https://pytorch.org/get-started/
142
-
143
- # install requirements
144
- pip install -r requirements.txt
145
- ```
146
-
147
- Template contains example with MNIST classification.<br>
148
- When running `python train.py` you should see something like this:
149
-
150
- <div align="center">
151
-
152
- ![](https://github.com/ashleve/lightning-hydra-template/blob/resources/terminal.png)
153
-
154
- </div>
155
-
156
- ### ⚑&nbsp;&nbsp;Your Superpowers
157
-
158
- <details>
159
- <summary><b>Override any config parameter from command line</b></summary>
160
-
161
- > Hydra allows you to easily overwrite any parameter defined in your config.
162
-
163
- ```bash
164
- python train.py trainer.max_epochs=20 model.lr=1e-4
165
- ```
166
-
167
- > You can also add new parameters with `+` sign.
168
-
169
- ```bash
170
- python train.py +model.new_param="uwu"
171
- ```
172
-
173
- </details>
174
-
175
- <details>
176
- <summary><b>Train on CPU, GPU, multi-GPU and TPU</b></summary>
177
-
178
- > PyTorch Lightning makes it easy to train your models on different hardware.
179
-
180
- ```bash
181
- # train on CPU
182
- python train.py trainer.gpus=0
183
-
184
- # train on 1 GPU
185
- python train.py trainer.gpus=1
186
-
187
- # train on TPU
188
- python train.py +trainer.tpu_cores=8
189
-
190
- # train with DDP (Distributed Data Parallel) (4 GPUs)
191
- python train.py trainer.gpus=4 +trainer.strategy=ddp
192
-
193
- # train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
194
- python train.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.strategy=ddp
195
- ```
196
-
197
- </details>
198
-
199
- <details>
200
- <summary><b>Train with mixed precision</b></summary>
201
-
202
- ```bash
203
- # train with pytorch native automatic mixed precision (AMP)
204
- python train.py trainer.gpus=1 +trainer.precision=16
205
- ```
206
-
207
- </details>
208
-
209
- <!-- deepspeed support still in beta
210
- <details>
211
- <summary><b>Optimize large scale models on multiple GPUs with Deepspeed</b></summary>
212
-
213
- ```bash
214
- python train.py +trainer.
215
- ```
216
-
217
- </details>
218
- -->
219
-
220
- <details>
221
- <summary><b>Train model with any logger available in PyTorch Lightning, like Weights&Biases or Tensorboard</b></summary>
222
-
223
- > PyTorch Lightning provides convenient integrations with most popular logging frameworks, like Tensorboard, Neptune or simple csv files. Read more [here](#experiment-tracking). Using wandb requires you to [setup account](https://www.wandb.com/) first. After that just complete the config as below.<br> > **Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.**
224
-
225
- ```bash
226
- # set project and entity names in `configs/logger/wandb`
227
- wandb:
228
- project: "your_project_name"
229
- entity: "your_wandb_team_name"
230
- ```
231
-
232
- ```bash
233
- # train model with Weights&Biases (link to wandb dashboard should appear in the terminal)
234
- python train.py logger=wandb
235
- ```
236
-
237
- </details>
238
-
239
- <details>
240
- <summary><b>Train model with chosen experiment config</b></summary>
241
-
242
- > Experiment configurations are placed in [configs/experiment/](configs/experiment/).
243
-
244
- ```bash
245
- python train.py experiment=example
246
- ```
247
-
248
- </details>
249
-
250
- <details>
251
- <summary><b>Attach some callbacks to run</b></summary>
252
-
253
- > Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).<br>
254
- > Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/).
255
-
256
- ```bash
257
- python train.py callbacks=default
258
- ```
259
-
260
- </details>
261
-
262
- <details>
263
- <summary><b>Use different tricks available in Pytorch Lightning</b></summary>
264
-
265
- > PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags).
266
-
267
- ```yaml
268
- # gradient clipping may be enabled to avoid exploding gradients
269
- python train.py +trainer.gradient_clip_val=0.5
270
-
271
- # stochastic weight averaging can make your models generalize better
272
- python train.py +trainer.stochastic_weight_avg=true
273
-
274
- # run validation loop 4 times during a training epoch
275
- python train.py +trainer.val_check_interval=0.25
276
-
277
- # accumulate gradients
278
- python train.py +trainer.accumulate_grad_batches=10
279
-
280
- # terminate training after 12 hours
281
- python train.py +trainer.max_time="00:12:00:00"
282
- ```
283
-
284
- </details>
285
-
286
- <details>
287
- <summary><b>Easily debug</b></summary>
288
-
289
- > Visit [configs/debug/](configs/debug/) for different debugging configs.
290
-
291
- ```bash
292
- # runs 1 epoch in default debugging mode
293
- # changes logging directory to `logs/debugs/...`
294
- # sets level of all command line loggers to 'DEBUG'
295
- # enables extra trainer flags like tracking gradient norm
296
- # enforces debug-friendly configuration
297
- python train.py debug=default
298
-
299
- # runs test epoch without training
300
- python train.py debug=test_only
301
-
302
- # run 1 train, val and test loop, using only 1 batch
303
- python train.py +trainer.fast_dev_run=true
304
-
305
- # raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf
306
- python train.py +trainer.detect_anomaly=true
307
-
308
- # print execution time profiling after training ends
309
- python train.py +trainer.profiler="simple"
310
-
311
- # try overfitting to 1 batch
312
- python train.py +trainer.overfit_batches=1 trainer.max_epochs=20
313
-
314
- # use only 20% of the data
315
- python train.py +trainer.limit_train_batches=0.2 \
316
- +trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2
317
-
318
- # log second gradient norm of the model
319
- python train.py +trainer.track_grad_norm=2
320
- ```
321
-
322
- </details>
323
-
324
- <details>
325
- <summary><b>Resume training from checkpoint</b></summary>
326
-
327
- > Checkpoint can be either path or URL.
328
-
329
- ```yaml
330
- python train.py trainer.resume_from_checkpoint="/path/to/ckpt/name.ckpt"
331
- ```
332
-
333
- > ⚠️ Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.
334
-
335
- </details>
336
-
337
- <details>
338
- <summary><b>Execute evaluation for a given checkpoint</b></summary>
339
-
340
- > Checkpoint can be either path or URL.
341
-
342
- ```yaml
343
- python test.py ckpt_path="/path/to/ckpt/name.ckpt"
344
- ```
345
-
346
- </details>
347
-
348
- <details>
349
- <summary><b>Create a sweep over hyperparameters</b></summary>
350
-
351
- ```bash
352
- # this will run 6 experiments one after the other,
353
- # each with different combination of batch_size and learning rate
354
- python train.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
355
- ```
356
-
357
- > ⚠️ This sweep is not failure resistant (if one job crashes than the whole sweep crashes).
358
-
359
- </details>
360
-
361
- <details>
362
- <summary><b>Create a sweep over hyperparameters with Optuna</b></summary>
363
-
364
- > 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)!
365
-
366
- ```bash
367
- # this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
368
- # over chosen experiment config
369
- python train.py -m hparams_search=mnist_optuna experiment=example_simple
370
- ```
371
-
372
- > ⚠️ Currently this sweep is not failure resistant (if one job crashes than the whole sweep crashes). Might be supported in future Hydra release.
373
-
374
- </details>
375
-
376
- <details>
377
- <summary><b>Execute all experiments from folder</b></summary>
378
-
379
- > Hydra provides special syntax for controlling behavior of multiruns. Learn more [here](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run). The command below executes all experiments from folder [configs/experiment/](configs/experiment/).
380
-
381
- ```bash
382
- python train.py -m 'experiment=glob(*)'
383
- ```
384
-
385
- </details>
386
-
387
- <details>
388
- <summary><b>Execute sweep on a remote AWS cluster</b></summary>
389
-
390
- > This should be achievable with simple config using [Ray AWS launcher for Hydra](https://hydra.cc/docs/next/plugins/ray_launcher). Example is not yet implemented in this template.
391
-
392
- </details>
393
-
394
- <!-- <details>
395
- <summary><b>Execute sweep on a SLURM cluster</b></summary>
396
-
397
- > This should be achievable with either [the right lightning trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/clouds/cluster.html?highlight=SLURM#slurm-managed-cluster) or simple config using [Submitit launcher for Hydra](https://hydra.cc/docs/plugins/submitit_launcher). Example is not yet implemented in this template.
398
-
399
- </details> -->
400
-
401
- <details>
402
- <summary><b>Use Hydra tab completion</b></summary>
403
-
404
- > Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing `tab` key. Learn more [here](https://hydra.cc/docs/tutorials/basic/running_your_app/tab_completion).
405
-
406
- </details>
407
-
408
- <details>
409
- <summary><b>Apply pre-commit hooks</b></summary>
410
-
411
- > Apply pre-commit hooks to automatically format your code and configs, perform code analysis and remove output from jupyter notebooks. See [# Best Practices](#best-practices) for more.
412
-
413
- ```bash
414
- pre-commit run -a
415
- ```
416
-
417
- </details>
418
-
419
- <br>
420
-
421
- ## ❀️&nbsp;&nbsp;Contributions
422
-
423
- Have a question? Found a bug? Missing a specific feature? Have an idea for improving documentation? Feel free to file a new issue, discussion or PR with respective title and description. If you already found a solution to your problem, don't hesitate to share it. Suggestions for new best practices are always welcome!
424
-
425
- <br>
426
-
427
- ## ℹ️&nbsp;&nbsp;Guide
428
-
429
- ### How To Get Started
430
-
431
- - First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai)
432
- - Next, go through [Hydra quick start guide](https://hydra.cc/docs/intro/) and [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/)
433
-
434
- <br>
435
-
436
- ### How It Works
437
-
438
- All PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config:
439
-
440
- ```yaml
441
- _target_: src.models.mnist_model.MNISTLitModule
442
- input_size: 784
443
- lin1_size: 256
444
- lin2_size: 256
445
- lin3_size: 256
446
- output_size: 10
447
- lr: 0.001
448
- ```
449
-
450
- Using this config we can instantiate the object with the following line:
451
-
452
- ```python
453
- model = hydra.utils.instantiate(config.model)
454
- ```
455
-
456
- 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. <br>
457
-
458
- Switch between models and datamodules with command line arguments:
459
-
460
- ```bash
461
- python train.py model=mnist
462
- ```
463
-
464
- The whole pipeline managing the instantiation logic is placed in [src/training_pipeline.py](src/training_pipeline.py).
465
-
466
- <br>
467
-
468
- ### Main Project Configuration
469
-
470
- Location: [configs/train.yaml](configs/train.yaml) <br>
471
- Main project config contains default training configuration.<br>
472
- It determines how config is composed when simply executing command `python train.py`.<br>
473
-
474
- <details>
475
- <summary><b>Show main project config</b></summary>
476
-
477
- ```yaml
478
- # specify here default training configuration
479
- defaults:
480
- - _self_
481
- - datamodule: mnist.yaml
482
- - model: mnist.yaml
483
- - callbacks: default.yaml
484
- - logger: null # set logger here or use command line (e.g. `python train.py logger=tensorboard`)
485
- - trainer: default.yaml
486
- - log_dir: default.yaml
487
-
488
- # experiment configs allow for version control of specific configurations
489
- # e.g. best hyperparameters for each combination of model and datamodule
490
- - experiment: null
491
-
492
- # debugging config (enable through command line, e.g. `python train.py debug=default)
493
- - debug: null
494
-
495
- # config for hyperparameter optimization
496
- - hparams_search: null
497
-
498
- # optional local config for machine/user specific settings
499
- # it's optional since it doesn't need to exist and is excluded from version control
500
- - optional local: default.yaml
501
-
502
- # enable color logging
503
- - override hydra/hydra_logging: colorlog
504
- - override hydra/job_logging: colorlog
505
-
506
- # path to original working directory
507
- # hydra hijacks working directory by changing it to the new log directory
508
- # https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
509
- original_work_dir: ${hydra:runtime.cwd}
510
-
511
- # path to folder with data
512
- data_dir: ${original_work_dir}/data/
513
-
514
- # pretty print config at the start of the run using Rich library
515
- print_config: True
516
-
517
- # disable python warnings if they annoy you
518
- ignore_warnings: True
519
-
520
- # set False to skip model training
521
- train: True
522
-
523
- # evaluate on test set, using best model weights achieved during training
524
- # lightning chooses best weights based on the metric specified in checkpoint callback
525
- test: True
526
-
527
- # seed for random number generators in pytorch, numpy and python.random
528
- seed: null
529
-
530
- # default name for the experiment, determines logging folder path
531
- # (you can overwrite this name in experiment configs)
532
- name: "default"
533
- ```
534
-
535
- </details>
536
-
537
- <br>
538
-
539
- ### Experiment Configuration
540
-
541
- Location: [configs/experiment](configs/experiment)<br>
542
- Experiment configs allow you to overwrite parameters from main project configuration.<br>
543
- For example, you can use them to version control best hyperparameters for each combination of model and dataset.
544
-
545
- <details>
546
- <summary><b>Show example experiment config</b></summary>
547
-
548
- ```yaml
549
- # to execute this experiment run:
550
- # python train.py experiment=example
551
-
552
- defaults:
553
- - override /datamodule: mnist.yaml
554
- - override /model: mnist.yaml
555
- - override /callbacks: default.yaml
556
- - override /logger: null
557
- - override /trainer: default.yaml
558
-
559
- # all parameters below will be merged with parameters from default configurations set above
560
- # this allows you to overwrite only specified parameters
561
-
562
- # name of the run determines folder name in logs
563
- name: "simple_dense_net"
564
-
565
- seed: 12345
566
-
567
- trainer:
568
- min_epochs: 10
569
- max_epochs: 10
570
- gradient_clip_val: 0.5
571
-
572
- model:
573
- lin1_size: 128
574
- lin2_size: 256
575
- lin3_size: 64
576
- lr: 0.002
577
-
578
- datamodule:
579
- batch_size: 64
580
-
581
- logger:
582
- wandb:
583
- tags: ["mnist", "${name}"]
584
- ```
585
-
586
- </details>
587
-
588
- <br>
589
-
590
- ### Local Configuration
591
-
592
- Location: [configs/local](configs/local) <br>
593
- 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.
594
-
595
- <details>
596
- <summary><b>Show example local Slurm cluster config</b></summary>
597
-
598
- ```yaml
599
- # @package _global_
600
-
601
- defaults:
602
- - override /hydra/launcher@_here_: submitit_slurm
603
-
604
- data_dir: /mnt/scratch/data/
605
-
606
- hydra:
607
- launcher:
608
- timeout_min: 1440
609
- gpus_per_task: 1
610
- gres: gpu:1
611
- job:
612
- env_set:
613
- MY_VAR: /home/user/my/system/path
614
- MY_KEY: asdgjhawi8y23ihsghsueity23ihwd
615
- ```
616
-
617
- </details>
618
-
619
- <br>
620
-
621
- ### Workflow
622
-
623
- 1. Write your PyTorch Lightning module (see [models/mnist_module.py](src/models/mnist_module.py) for example)
624
- 2. Write your PyTorch Lightning datamodule (see [datamodules/mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example)
625
- 3. Write your experiment config, containing paths to your model and datamodule
626
- 4. Run training with chosen experiment config: `python train.py experiment=experiment_name`
627
-
628
- <br>
629
-
630
- ### Logs
631
-
632
- **Hydra creates new working directory for every executed run.** By default, logs have the following structure:
633
-
634
- ```
635
- β”œβ”€β”€ logs
636
- β”‚ β”œβ”€β”€ experiments # Folder for the logs generated by experiments
637
- β”‚ β”‚ β”œβ”€β”€ runs # Folder for single runs
638
- β”‚ β”‚ β”‚ β”œβ”€β”€ experiment_name # Experiment name
639
- β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ YYYY-MM-DD_HH-MM-SS # Datetime of the run
640
- β”‚ β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ .hydra # Hydra logs
641
- β”‚ β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ csv # Csv logs
642
- β”‚ β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ wandb # Weights&Biases logs
643
- β”‚ β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ checkpoints # Training checkpoints
644
- β”‚ β”‚ β”‚ β”‚ β”‚ └── ... # Any other thing saved during training
645
- β”‚ β”‚ β”‚ β”‚ └── ...
646
- β”‚ β”‚ β”‚ └── ...
647
- β”‚ β”‚ β”‚
648
- β”‚ β”‚ └── multiruns # Folder for multiruns
649
- β”‚ β”‚ β”œβ”€β”€ experiment_name # Experiment name
650
- β”‚ β”‚ β”‚ β”œβ”€β”€ YYYY-MM-DD_HH-MM-SS # Datetime of the multirun
651
- β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€1 # Multirun job number
652
- β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€2
653
- β”‚ β”‚ β”‚ β”‚ └── ...
654
- β”‚ β”‚ β”‚ └── ...
655
- β”‚ β”‚ └── ...
656
- β”‚ β”‚
657
- β”‚ β”œβ”€β”€ evaluations # Folder for the logs generated during testing
658
- β”‚ β”‚ └── ...
659
- β”‚ β”‚
660
- β”‚ └── debugs # Folder for the logs generated during debugging
661
- β”‚ └── ...
662
- ```
663
-
664
- You can change this structure by modifying paths in [hydra configuration](configs/log_dir).
665
-
666
- <br>
667
-
668
- ### Experiment Tracking
669
-
670
- PyTorch Lightning supports many popular logging frameworks:<br>
671
- **[Weights&Biases](https://www.wandb.com/) Β· [Neptune](https://neptune.ai/) Β· [Comet](https://www.comet.ml/) Β· [MLFlow](https://mlflow.org) Β· [Tensorboard](https://www.tensorflow.org/tensorboard/)**
672
-
673
- 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](configs/logger) and run:
674
-
675
- ```bash
676
- python train.py logger=logger_name
677
- ```
678
-
679
- You can use many of them at once (see [configs/logger/many_loggers.yaml](configs/logger/many_loggers.yaml) for example).
680
-
681
- You can also write your own logger.
682
-
683
- 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).
684
-
685
- <br>
686
-
687
- ### Hyperparameter Search
688
-
689
- Defining hyperparameter optimization is as easy as adding new config file to [configs/hparams_search](configs/hparams_search).
690
-
691
- <details>
692
- <summary><b>Show example</b></summary>
693
-
694
- ```yaml
695
- defaults:
696
- - override /hydra/sweeper: optuna
697
-
698
- # choose metric which will be optimized by Optuna
699
- optimized_metric: "val/acc_best"
700
-
701
- hydra:
702
- # here we define Optuna hyperparameter search
703
- # it optimizes for value returned from function with @hydra.main decorator
704
- # learn more here: https://hydra.cc/docs/next/plugins/optuna_sweeper
705
- sweeper:
706
- _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper
707
- storage: null
708
- study_name: null
709
- n_jobs: 1
710
-
711
- # 'minimize' or 'maximize' the objective
712
- direction: maximize
713
-
714
- # number of experiments that will be executed
715
- n_trials: 20
716
-
717
- # choose Optuna hyperparameter sampler
718
- # learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html
719
- sampler:
720
- _target_: optuna.samplers.TPESampler
721
- seed: 12345
722
- consider_prior: true
723
- prior_weight: 1.0
724
- consider_magic_clip: true
725
- consider_endpoints: false
726
- n_startup_trials: 10
727
- n_ei_candidates: 24
728
- multivariate: false
729
- warn_independent_sampling: true
730
-
731
- # define range of hyperparameters
732
- search_space:
733
- datamodule.batch_size:
734
- type: categorical
735
- choices: [32, 64, 128]
736
- model.lr:
737
- type: float
738
- low: 0.0001
739
- high: 0.2
740
- model.lin1_size:
741
- type: categorical
742
- choices: [32, 64, 128, 256, 512]
743
- model.lin2_size:
744
- type: categorical
745
- choices: [32, 64, 128, 256, 512]
746
- model.lin3_size:
747
- type: categorical
748
- choices: [32, 64, 128, 256, 512]
749
- ```
750
-
751
- </details>
752
-
753
- Next, you can execute it with: `python train.py -m hparams_search=mnist_optuna`
754
-
755
- Using this approach doesn't require you to add any boilerplate into your pipeline, everything is defined in a single config file.
756
-
757
- You can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad.
758
-
759
- The `optimization_results.yaml` will be available under `logs/multirun` folder.
760
-
761
- This approach doesn't support advanced technics like prunning - for more sophisticated search, you probably shouldn't use hydra multirun feature and instead write your own optimization pipeline.
762
-
763
- <br>
764
-
765
- ### Inference
766
-
767
- The following code is an example of loading model from checkpoint and running predictions.<br>
768
-
769
- <details>
770
- <summary><b>Show example</b></summary>
771
-
772
- ```python
773
- from PIL import Image
774
- from torchvision import transforms
775
-
776
- from src.models.mnist_module import MNISTLitModule
777
-
778
-
779
- def predict():
780
- """Example of inference with trained model.
781
- It loads trained image classification model from checkpoint.
782
- Then it loads example image and predicts its label.
783
- """
784
-
785
- # ckpt can be also a URL!
786
- CKPT_PATH = "last.ckpt"
787
-
788
- # load model from checkpoint
789
- # model __init__ parameters will be loaded from ckpt automatically
790
- # you can also pass some parameter explicitly to override it
791
- trained_model = MNISTLitModule.load_from_checkpoint(checkpoint_path=CKPT_PATH)
792
-
793
- # print model hyperparameters
794
- print(trained_model.hparams)
795
-
796
- # switch to evaluation mode
797
- trained_model.eval()
798
- trained_model.freeze()
799
-
800
- # load data
801
- img = Image.open("data/example_img.png").convert("L") # convert to black and white
802
- # img = Image.open("data/example_img.png").convert("RGB") # convert to RGB
803
-
804
- # preprocess
805
- mnist_transforms = transforms.Compose(
806
- [
807
- transforms.ToTensor(),
808
- transforms.Resize((28, 28)),
809
- transforms.Normalize((0.1307,), (0.3081,)),
810
- ]
811
- )
812
- img = mnist_transforms(img)
813
- img = img.reshape((1, *img.size())) # reshape to form batch of size 1
814
-
815
- # inference
816
- output = trained_model(img)
817
- print(output)
818
-
819
-
820
- if __name__ == "__main__":
821
- predict()
822
-
823
- ```
824
-
825
- </details>
826
-
827
- <br>
828
-
829
- ### Tests
830
-
831
- Template comes with example tests implemented with pytest library. To execute them simply run:
832
-
833
- ```bash
834
- # run all tests
835
- pytest
836
-
837
- # run tests from specific file
838
- pytest tests/shell/test_basic_commands.py
839
-
840
- # run all tests except the ones marked as slow
841
- pytest -k "not slow"
842
- ```
843
-
844
- To speed up the development, you can once in a while execute tests that run a couple of quick experiments, like training 1 epoch on 25% of data, executing single train/val/test step, etc. Those kind of tests don't check for any specific output - they exist to simply verify that executing some bash commands doesn't end up in throwing exceptions. You can find them implemented in [tests/shell](tests/shell) folder.
845
-
846
- You can easily modify the commands in the scripts for your use case. If 1 epoch is too much for your model, then make it run for a couple of batches instead (by using the right trainer flags).
847
-
848
- <br>
849
-
850
- ### Callbacks
851
-
852
- The branch [`wandb-callbacks`](https://github.com/ashleve/lightning-hydra-template/tree/wandb-callbacks) contains example callbacks enabling better Weights&Biases integration, which you can use as a reference for writing your own callbacks (see [wandb_callbacks.py](https://github.com/ashleve/lightning-hydra-template/tree/wandb-callbacks/src/callbacks/wandb_callbacks.py)).
853
-
854
- Callbacks which support reproducibility:
855
-
856
- - **WatchModel**
857
- - **UploadCodeAsArtifact**
858
- - **UploadCheckpointsAsArtifact**
859
-
860
- Callbacks which provide examples of logging custom visualisations:
861
-
862
- - **LogConfusionMatrix**
863
- - **LogF1PrecRecHeatmap**
864
- - **LogImagePredictions**
865
-
866
- To try all of the callbacks at once, switch to the right branch:
867
-
868
- ```bash
869
- git checkout wandb-callbacks
870
- ```
871
-
872
- And then run the following command:
873
-
874
- ```bash
875
- python train.py logger=wandb callbacks=wandb
876
- ```
877
-
878
- To see the result of all the callbacks attached, take a look at [this experiment dashboard](https://wandb.ai/hobglob/template-tests/runs/3rw7q70h).
879
-
880
- <br>
881
-
882
- ### Multi-GPU Training
883
-
884
- 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](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html).
885
-
886
- You can run DDP on mnist example with 4 GPUs like this:
887
-
888
- ```bash
889
- python train.py trainer.gpus=4 +trainer.strategy=ddp
890
- ```
891
-
892
- ⚠️ 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).
893
-
894
- <br>
895
-
896
- ### Docker
897
-
898
- First you will need to [install Nvidia Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to enable GPU support.
899
-
900
- The template Dockerfile is provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). Copy it to the template root folder.
901
-
902
- To build the container use:
903
-
904
- ```bash
905
- docker build -t <project_name> .
906
- ```
907
-
908
- To mount the project to the container use:
909
-
910
- ```bash
911
- docker run -v $(pwd):/workspace/project --gpus all -it --rm <project_name>
912
- ```
913
-
914
- <br>
915
-
916
- ### Reproducibility
917
-
918
- What provides reproducibility:
919
-
920
- - Hydra manages your configs
921
- - Hydra manages your logging paths and makes every executed run store its hyperparameters and config overrides in a separate file in logs
922
- - Single seed for random number generators in pytorch, numpy and python.random
923
- - LightningDataModule allows you to encapsulate data split, transformations and default parameters in a single, clean abstraction
924
- - LightningModule separates your research code from engineering code in a clean way
925
- - Experiment tracking frameworks take care of logging metrics and hparams, some can also store results and artifacts in cloud
926
- - Pytorch Lightning takes care of creating training checkpoints
927
- - Example callbacks for wandb show how you can save and upload a snapshot of codebase every time the run is executed, as well as upload ckpts and track model gradients
928
-
929
- <!--
930
- You can load the config of previous run using:
931
-
932
- ```bash
933
- python train.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml
934
- ```
935
-
936
- The `config.yaml` from `.hydra` folder contains all overriden parameters and sections. This approach however is not officially supported by Hydra and doesn't override the `hydra/` part of the config, meaning logging paths will revert to default!
937
- -->
938
- <br>
939
-
940
- ### Limitations
941
-
942
- - Currently, template doesn't support k-fold cross validation, but it's possible to achieve it with Lightning Loop interface. See the [official example](https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pl_examples/loop_examples/kfold.py). Implementing it requires rewriting the training pipeline.
943
- - Pytorch Lightning might not be the best choice for scalable reinforcement learning, it's probably better to use something like [Ray](https://github.com/ray-project/ray).
944
- - Currently hyperparameter search with Hydra Optuna Plugin doesn't support prunning.
945
- - Hydra changes working directory to new logging folder for every executed run, which might not be compatible with the way some libraries work.
946
-
947
- <br>
948
-
949
- ## Useful Tricks
950
-
951
- <details>
952
- <summary><b>Accessing datamodule attributes in model</b></summary>
953
-
954
- 1. The simplest way is to pass datamodule attribute directly to model on initialization:
955
-
956
- ```python
957
- # ./src/training_pipeline.py
958
- datamodule = hydra.utils.instantiate(config.datamodule)
959
- model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)
960
- ```
961
-
962
- This is not a very robust solution, since it assumes all your datamodules have `some_param` attribute available (otherwise the run will crash).
963
-
964
- 2. If you only want to access datamodule config, you can simply pass it as an init parameter:
965
-
966
- ```python
967
- # ./src/training_pipeline.py
968
- model = hydra.utils.instantiate(config.model, dm_conf=config.datamodule, _recursive_=False)
969
- ```
970
-
971
- Now you can access any datamodule config part like this:
972
-
973
- ```python
974
- # ./src/models/my_model.py
975
- class MyLitModel(LightningModule):
976
- def __init__(self, dm_conf, param1, param2):
977
- super().__init__()
978
-
979
- batch_size = dm_conf.batch_size
980
- ```
981
-
982
- 3. If you need to access the datamodule object attributes, a little hacky solution is to add Omegaconf resolver to your datamodule:
983
-
984
- ```python
985
- # ./src/datamodules/my_datamodule.py
986
- from omegaconf import OmegaConf
987
-
988
- class MyDataModule(LightningDataModule):
989
- def __init__(self, param1, param2):
990
- super().__init__()
991
-
992
- self.param1 = param1
993
-
994
- resolver_name = "datamodule"
995
- OmegaConf.register_new_resolver(
996
- resolver_name,
997
- lambda name: getattr(self, name),
998
- use_cache=False
999
- )
1000
- ```
1001
-
1002
- This way you can reference any datamodule attribute from your config like this:
1003
-
1004
- ```yaml
1005
- # this will return attribute 'param1' from datamodule object
1006
- param1: ${datamodule: param1}
1007
- ```
1008
-
1009
- When later accessing this field, say in your lightning model, it will get automatically resolved based on all resolvers that are registered. Remember not to access this field before datamodule is initialized or it will crash. **You also need to set `resolve=False` in `print_config()` in [train.py](train.py) or it will throw errors:**
1010
-
1011
- ```python
1012
- # ./src/train.py
1013
- utils.print_config(config, resolve=False)
1014
- ```
1015
-
1016
- </details>
1017
-
1018
- <details>
1019
- <summary><b>Automatic activation of virtual environment and tab completion when entering folder</b></summary>
1020
-
1021
- 1. Create a new file called `.autoenv` (this name is excluded from version control in `.gitignore`). <br>
1022
- You can use it to automatically execute shell commands when entering folder. Add some commands to your `.autoenv` file, like in the example below:
1023
-
1024
- ```bash
1025
- # activate conda environment
1026
- conda activate myenv
1027
-
1028
- # activate hydra tab completion for bash
1029
- eval "$(python train.py -sc install=bash)"
1030
- ```
1031
-
1032
- (these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file)
1033
-
1034
- 2. To setup this automation for bash, execute the following line (it will append your `.bashrc` file):
1035
-
1036
- ```bash
1037
- echo "autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
1038
- ```
1039
-
1040
- 3. Lastly add execution previliges to your `.autoenv` file:
1041
-
1042
- ```
1043
- chmod +x .autoenv
1044
- ```
1045
-
1046
- (for safety, only `.autoenv` with previligies will be executed)
1047
-
1048
- **Explanation**
1049
-
1050
- The mentioned line appends your `.bashrc` file with 2 commands:
1051
-
1052
- 1. `autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi }` - this declares the `autoenv()` function, which executes `.autoenv` file if it exists in current work dir and has execution previligies
1053
- 2. `cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv` - this extends behaviour of `cd` command, to make it execute `autoenv()` function each time you change folder in terminal or open new terminal
1054
-
1055
- </details>
1056
-
1057
- <!--
1058
- <details>
1059
- <summary><b>Making sweeps failure resistant</b></summary>
1060
-
1061
- TODO
1062
-
1063
- </details>
1064
- -->
1065
-
1066
- <br>
1067
-
1068
- ## Best Practices
1069
-
1070
- <details>
1071
- <summary><b>Use Miniconda for GPU environments</b></summary>
1072
-
1073
- Use miniconda for your python environments (it's usually unnecessary to install full anaconda environment, miniconda should be enough).
1074
- It makes it easier to install some dependencies, like cudatoolkit for GPU support. It also allows you to acccess your environments globally.
1075
-
1076
- Example installation:
1077
-
1078
- ```bash
1079
- wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
1080
- bash Miniconda3-latest-Linux-x86_64.sh
1081
- ```
1082
-
1083
- Create new conda environment:
1084
-
1085
- ```bash
1086
- conda create -n myenv python=3.8
1087
- conda activate myenv
1088
- ```
1089
-
1090
- </details>
1091
-
1092
- <details>
1093
- <summary><b>Use automatic code formatting</b></summary>
1094
-
1095
- Use pre-commit hooks to standardize code formatting of your project and save mental energy.<br>
1096
- Simply install pre-commit package with:
1097
-
1098
- ```bash
1099
- pip install pre-commit
1100
- ```
1101
-
1102
- Next, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml):
1103
-
1104
- ```bash
1105
- pre-commit install
1106
- ```
1107
-
1108
- After that your code will be automatically reformatted on every new commit.<br>
1109
- Currently template contains configurations of **black** (python code formatting), **isort** (python import sorting), **flake8** (python code analysis), **prettier** (yaml formating) and **nbstripout** (clearing output from jupyter notebooks). <br>
1110
-
1111
- To reformat all files in the project use command:
1112
-
1113
- ```bash
1114
- pre-commit run -a
1115
- ```
1116
-
1117
- </details>
1118
-
1119
- <details>
1120
- <summary><b>Set private environment variables in .env file</b></summary>
1121
-
1122
- 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.<br>
1123
-
1124
- 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).
1125
- You should use it for storing environment variables like this:
1126
-
1127
- ```
1128
- MY_VAR=/home/user/my_system_path
1129
- ```
1130
-
1131
- All variables from `.env` are loaded in `train.py` automatically.
1132
-
1133
- Hydra allows you to reference any env variable in `.yaml` configs like this:
1134
-
1135
- ```yaml
1136
- path_to_data: ${oc.env:MY_VAR}
1137
- ```
1138
-
1139
- </details>
1140
-
1141
- <details>
1142
- <summary><b>Name metrics using '/' character</b></summary>
1143
-
1144
- Depending on which logger you're using, it's often useful to define metric name with `/` character:
1145
-
1146
- ```python
1147
- self.log("train/loss", loss)
1148
- ```
1149
-
1150
- This way loggers will treat your metrics as belonging to different sections, which helps to get them organised in UI.
1151
-
1152
- </details>
1153
-
1154
- <details>
1155
- <summary><b>Use torchmetrics</b></summary>
1156
-
1157
- Use official [torchmetrics](https://github.com/PytorchLightning/metrics) library to ensure proper calculation of metrics. This is especially important for multi-GPU training!
1158
-
1159
- For example, instead of calculating accuracy by yourself, you should use the provided `Accuracy` class like this:
1160
-
1161
- ```python
1162
- from torchmetrics.classification.accuracy import Accuracy
1163
-
1164
-
1165
- class LitModel(LightningModule):
1166
- def __init__(self)
1167
- self.train_acc = Accuracy()
1168
- self.val_acc = Accuracy()
1169
-
1170
- def training_step(self, batch, batch_idx):
1171
- ...
1172
- acc = self.train_acc(predictions, targets)
1173
- self.log("train/acc", acc)
1174
- ...
1175
-
1176
- def validation_step(self, batch, batch_idx):
1177
- ...
1178
- acc = self.val_acc(predictions, targets)
1179
- self.log("val/acc", acc)
1180
- ...
1181
- ```
1182
-
1183
- Make sure to use different metric instance for each step to ensure proper value reduction over all GPU processes.
1184
-
1185
- Torchmetrics provides metrics for most use cases, like F1 score or confusion matrix. Read [documentation](https://torchmetrics.readthedocs.io/en/latest/#more-reading) for more.
1186
-
1187
- </details>
1188
-
1189
- <details>
1190
- <summary><b>Follow PyTorch Lightning style guide</b></summary>
1191
-
1192
- The style guide is available [here](https://pytorch-lightning.readthedocs.io/en/latest/starter/style_guide.html).<br>
1193
-
1194
- 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!
1195
-
1196
- ```python
1197
- class LitModel(LightningModule):
1198
- def __init__(self, layer_size: int = 256, lr: float = 0.001):
1199
- ```
1200
-
1201
- 2. Preserve the recommended method order.
1202
-
1203
- ```python
1204
- class LitModel(LightningModule):
1205
-
1206
- def __init__():
1207
- ...
1208
-
1209
- def forward():
1210
- ...
1211
-
1212
- def training_step():
1213
- ...
1214
-
1215
- def training_step_end():
1216
- ...
1217
-
1218
- def training_epoch_end():
1219
- ...
1220
-
1221
- def validation_step():
1222
- ...
1223
-
1224
- def validation_step_end():
1225
- ...
1226
-
1227
- def validation_epoch_end():
1228
- ...
1229
-
1230
- def test_step():
1231
- ...
1232
-
1233
- def test_step_end():
1234
- ...
1235
-
1236
- def test_epoch_end():
1237
- ...
1238
-
1239
- def configure_optimizers():
1240
- ...
1241
-
1242
- def any_extra_hook():
1243
- ...
1244
- ```
1245
-
1246
- </details>
1247
-
1248
- <details>
1249
- <summary><b>Version control your data and models with DVC</b></summary>
1250
-
1251
- Use [DVC](https://dvc.org) to version control big files, like your data or trained ML models.<br>
1252
- To initialize the dvc repository:
1253
-
1254
- ```bash
1255
- dvc init
1256
- ```
1257
-
1258
- To start tracking a file or directory, use `dvc add`:
1259
-
1260
- ```bash
1261
- dvc add data/MNIST
1262
- ```
1263
-
1264
- 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:
1265
-
1266
- ```bash
1267
- git add data/MNIST.dvc data/.gitignore
1268
- git commit -m "Add raw data"
1269
- ```
1270
-
1271
- </details>
1272
-
1273
- <details>
1274
- <summary><b>Support installing project as a package</b></summary>
1275
-
1276
- It allows other people to easily use your modules in their own projects.
1277
- Change name of the `src` folder to your project name and add `setup.py` file:
1278
-
1279
- ```python
1280
- from setuptools import find_packages, setup
1281
-
1282
-
1283
- setup(
1284
- name="src", # change "src" folder name to your project name
1285
- version="0.0.0",
1286
- description="Describe Your Cool Project",
1287
- author="...",
1288
- author_email="...",
1289
- url="https://github.com/ashleve/lightning-hydra-template", # replace with your own github project link
1290
- install_requires=[
1291
- "pytorch>=1.10.0",
1292
- "pytorch-lightning>=1.4.0",
1293
- "hydra-core>=1.1.0",
1294
- ],
1295
- packages=find_packages(),
1296
- )
1297
- ```
1298
-
1299
- Now your project can be installed from local files:
1300
-
1301
- ```bash
1302
- pip install -e .
1303
- ```
1304
-
1305
- Or directly from git repository:
1306
-
1307
- ```bash
1308
- pip install git+git://github.com/YourGithubName/your-repo-name.git --upgrade
1309
- ```
1310
-
1311
- So any file can be easily imported into any other file like so:
1312
-
1313
- ```python
1314
- from project_name.models.mnist_module import MNISTLitModule
1315
- from project_name.datamodules.mnist_datamodule import MNISTDataModule
1316
- ```
1317
-
1318
- </details>
1319
-
1320
- <!-- <details>
1321
- <summary><b>Make notebooks independent from other files</b></summary>
1322
-
1323
- It's a good practice for jupyter notebooks to be portable. Try to make them independent from src files. If you need to access external code, try to embed it inside the notebook.
1324
-
1325
- </details> -->
1326
-
1327
- <!--<details>
1328
- <summary><b>Use Docker</b></summary>
1329
-
1330
- 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>
1331
-
1332
- </details> -->
1333
-
1334
- <br>
1335
-
1336
- ## Other Repositories
1337
-
1338
- <details>
1339
- <summary><b>Inspirations</b></summary>
1340
-
1341
- This template was inspired by:
1342
- [PyTorchLightning/deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template),
1343
- [drivendata/cookiecutter-data-science](https://github.com/drivendata/cookiecutter-data-science),
1344
- [tchaton/lightning-hydra-seed](https://github.com/tchaton/lightning-hydra-seed),
1345
- [Erlemar/pytorch_tempest](https://github.com/Erlemar/pytorch_tempest),
1346
- [lucmos/nn-template](https://github.com/lucmos/nn-template).
1347
-
1348
- </details>
1349
-
1350
- <details>
1351
- <summary><b>Useful repositories</b></summary>
1352
-
1353
- - [pytorch/hydra-torch](https://github.com/pytorch/hydra-torch) - resources for configuring PyTorch classes with Hydra,
1354
- - [romesco/hydra-lightning](https://github.com/romesco/hydra-lightning) - resources for configuring PyTorch Lightning classes with Hydra
1355
- - [lucmos/nn-template](https://github.com/lucmos/nn-template) - similar template
1356
- - [PyTorchLightning/lightning-transformers](https://github.com/PyTorchLightning/lightning-transformers) - official Lightning Transformers repo built with Hydra
1357
-
1358
- </details>
1359
-
1360
- <!-- ## :star:&nbsp; Stargazers Over Time
1361
- [![Stargazers over time](https://starchart.cc/ashleve/lightning-hydra-template.svg)](https://starchart.cc/ashleve/lightning-hydra-template) -->
1362
-
1363
- <br>
1364
-
1365
- ## License
1366
-
1367
- This project is licensed under the MIT License.
1368
-
1369
- ```
1370
- MIT License
1371
-
1372
- Copyright (c) 2021 ashleve
1373
-
1374
- Permission is hereby granted, free of charge, to any person obtaining a copy
1375
- of this software and associated documentation files (the "Software"), to deal
1376
- in the Software without restriction, including without limitation the rights
1377
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1378
- copies of the Software, and to permit persons to whom the Software is
1379
- furnished to do so, subject to the following conditions:
1380
-
1381
- The above copyright notice and this permission notice shall be included in all
1382
- copies or substantial portions of the Software.
1383
-
1384
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1385
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1386
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1387
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1388
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1389
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1390
- SOFTWARE.
1391
- ```
1392
-
1393
- <br>
1394
- <br>
1395
- <br>
1396
- <br>
1397
-
1398
- **DELETE EVERYTHING ABOVE FOR YOUR PROJECT**
1399
-
1400
- ---
1401
-
1402
- <div align="center">
1403
-
1404
- # Your Project Name
1405
-
1406
- <a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-ee4c2c?logo=pytorch&logoColor=white"></a>
1407
- <a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5?logo=pytorchlightning&logoColor=white"></a>
1408
  <a href="https://hydra.cc/"><img alt="Config: Hydra" src="https://img.shields.io/badge/Config-Hydra-89b8cd"></a>
1409
- <a href="https://github.com/ashleve/lightning-hydra-template"><img alt="Template" src="https://img.shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat&logo=github&labelColor=gray"></a><br>
1410
- [![Paper](http://img.shields.io/badge/paper-arxiv.1001.2234-B31B1B.svg)](https://www.nature.com/articles/nature14539)
1411
- [![Conference](http://img.shields.io/badge/AnyConference-year-4b44ce.svg)](https://papers.nips.cc/paper/2020)
1412
-
1413
- </div>
1414
 
1415
  ## Description
1416
 
1417
- What it does
1418
 
1419
  ## How to run
1420
 
 
 
1421
  Install dependencies
1422
 
1423
  ```bash
 
12
  - pytorch
13
  ---
14
 
15
+ # K-POP: Predicting Distance to Focal Plane for Kato-Katz Prepared Microscopy Slides Using Deep Learning
16
 
17
+ <a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-ee4c2c?logo=pytorch&logoColor=white"></a><a href="https://pytorchlightning.ai/">
18
+ <img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5?logo=pytorchlightning&logoColor=white"></a>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  <a href="https://hydra.cc/"><img alt="Config: Hydra" src="https://img.shields.io/badge/Config-Hydra-89b8cd"></a>
 
 
 
 
 
20
 
21
  ## Description
22
 
23
+ TODO
24
 
25
  ## How to run
26
 
27
+ TODO
28
+
29
  Install dependencies
30
 
31
  ```bash