If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step.
+
1
+2
+3
# Truncated back-propagation through time
+deftraining_step(self,batch,batch_nb,hiddens):
+ # hiddens are the hiddens from the previous truncated backprop step
+
+
+
+
You can also return a -1 instead of a dict to stop the current loop. This is useful if you want to
+break out of the current training epoch early.
+
+
training_end
+
1
deftraining_end(self,train_step_outputs)
+
+
+
+
In certain cases (dp, ddp2), you might want to use all outputs of every process to do something.
+For instance, if using negative samples, you could run a batch via dp and use ALL the outputs
+for a single softmax across the full batch (ie: the denominator would use the full batch).
+
In this case you should define training_end to perform those calculations.
+
Params
+
+
+
+
Param
+
description
+
+
+
+
+
outputs
+
What you return in training_step.
+
+
+
+
Return
+
Dictionary or OrderedDict
+
+
+
+
key
+
value
+
is required
+
+
+
+
+
loss
+
tensor scalar
+
Y
+
+
+
progress_bar
+
Dict for progress bar display. Must have only tensors
+
N
+
+
+
log
+
Dict of metrics to add to logger. Must have only tensors (no images, etc)
# WITHOUT training_end
+# if used in DP or DDP2, this batch is 1/nb_gpus large
+deftraining_step(self,batch,batch_nb):
+ # batch is 1/nb_gpus big
+ x,y=batch
+
+ out=self.forward(x)
+ loss=self.softmax(out)
+ loss=nce_loss(loss)
+ return{'loss':loss}
+
+# --------------
+# with training_end to do softmax over the full batch
+deftraining_step(self,batch,batch_nb):
+ # batch is 1/nb_gpus big
+ x,y=batch
+
+ out=self.forward(x)
+ return{'out':out}
+
+deftraining_end(self,outputs):
+ # this out is now the full size of the batch
+ out=outputs['out']
+
+ # this softmax now uses the full batch size
+ loss=self.softmax(out)
+ loss=nce_loss(loss)
+ return{'loss':loss}
+
+
+
+
If you define multiple optimizers, this step will also be called with an additional optimizer_idx param.
+
1
+2
+3
+4
+5
+6
# Multiple optimizers (ie: GANs)
+deftraining_step(self,batch,batch_nb,optimizer_idx):
+ ifoptimizer_idx==0:
+ # do training_step with encoder
+ ifoptimizer_idx==1:
+ # do training_step with decoder
+
+
+
+
If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step.
+
1
+2
+3
# Truncated back-propagation through time
+deftraining_step(self,batch,batch_nb,hiddens):
+ # hiddens are the hiddens from the previous truncated backprop step
+
+
+
You can also return a -1 instead of a dict to stop the current loop. This is useful if you want to
break out of the current training epoch early.
@@ -1255,7 +1417,7 @@ break out of the current training epoch early.
Called by lightning during training loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed.
-If you want to change the data during every epoch DON'T use the data_loader decorator.
+If you want to change the data during every epoch DON'T use the data_loader decorator.
This is the easiest/fastest way which uses the meta_tags.csv file from test-tube to rebuild the model.
-The meta_tags.csv file can be found in the test-tube experiment save_dir.
+
This is the easiest/fastest way which loads hyperparameters and weights from a checkpoint,
+such as the one saved by the ModelCheckpoint callback
If you're using test tube, there is an alternate method which uses the meta_tags.csv
+file from test-tube to rebuild the model. The meta_tags.csv file can be found in the
+test-tube experiment save_dir.
1
2
3
@@ -716,7 +753,7 @@ The meta_tags.csv file can be found in the test-tube experiment save_dir.
You might want to not only load a model but also continue training it. Use this method to
restore the trainer state as well. This will continue from the epoch and global step you last left off.
However, the dataloaders will start from the first batch again (if you shuffled it shouldn't matter).
-
Lightning will restore the session if you pass an experiment with the same version and there's a saved checkpoint.
-
1
-2
-3
-4
-5
-6
-7
-8
-9
fromtest_tubeimportExperiment
+
Lightning will restore the session if you pass a logger with the same version and there's a saved checkpoint.
frompytorch_lightningimportTrainer
+frompytorch_lightning.loggingimportTestTubeLogger
-exp=Experiment(version=a_previous_version_with_a_saved_checkpoint)
-trainer=Trainer(experiment=exp)
+logger=TestTubeLogger(
+ save_dir='./savepath',
+ version=1# An existing version with a saved checkpoint
+)
+trainer=Trainer(
+ logger=logger,
+ default_save_path='./savepath'
+)# this fit call loads model weights and trainer state# the trainer continues seamlessly from where you left off
@@ -733,7 +747,7 @@ the system isn't different. If you add a layer, for instance, it might not work.
# DEFAULT (int) specifies how many GPUs to use.Trainer(gpus=k)
+# Above is equivalent to
+Trainer(gpus=list(range(k)))
+
# You specify which GPUs (don't use if running on cluster) Trainer(gpus=[0,1])# can also be a stringTrainer(gpus='0, 1')
+
+# can also be -1 or '-1', this uses all available GPUs
+# this is equivalent to list(range(torch.cuda.available_devices()))
+Trainer(gpus=-1)
@@ -1025,7 +1039,7 @@ portion of your dataset onto each GPU. (World_size = gpus_per_node * nb_nodes).
Instead of manually building SLURM scripts, you can use the SlurmCluster object to
do this for you. The SlurmCluster can also run a grid search if you pass in a HyperOptArgumentParser.
Here is an example where you run a grid search of 9 combinations of hyperparams.
-The full examples are here.
frompytorch_lightning.loggingimportCometLogger
+# arguments made to CometLogger are passed on to the comet_ml.Experiment class
+comet_logger=CometLogger(
+ api_key=os.environ["COMET_KEY"],
+ workspace=os.environ["COMET_KEY"],
+)
+trainer=Trainer(logger=comet_logger)
+
+
+
+
Use the logger anywhere in you LightningModule as follows:
You can implement your own logger by writing a class that inherits from
@@ -1039,7 +1087,7 @@ Lightning will stack progress bars according to this value.
Below are all the things lightning automates for you in the training loop.
Accumulated gradients
-
Accumulated gradients runs K small batches of size N before doing a backwards pass. The effect is a large effective batch size of size KxN.
+
Accumulated gradients runs K small batches of size N before doing a backwards pass. The effect is a large effective batch size of size KxN.
1
2
# DEFAULT (ie: no accumulated grads)trainer=Trainer(accumulate_grad_batches=1)
@@ -650,7 +678,7 @@
Early stopping
-
The trainer already sets up default early stopping for you.
+
The trainer already sets up default early stopping for you.
To modify this behavior, pass in your own EarlyStopping callback.
1
2
@@ -684,10 +712,10 @@ To modify this behavior, pass in your own EarlyStopping callback.
# without passing anything in, uses the default callback abovetrainer=Trainer()
-# pass in your own to override the default callback
+# pass in your own to override the default callbacktrainer=Trainer(early_stop_callback=early_stop_callback)
-# pass in None to disable it
+# pass in None to disable ittrainer=Trainer(early_stop_callback=None)
When using PackedSequence, do 2 things:
+1. return either a padded tensor in dataset or a list of variable length tensors in the dataloader collate_fn (example above shows the list implementation).
+2. Pack the sequence in forward or training and validation steps depending on use case.
+
1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
# For use in dataloader
+defcollate_fn(batch):
+ x=[item[0]foriteminbatch]
+ y=[item[1]foriteminbatch]
+ returnx,y
+
+# In module
+deftraining_step(self,batch,batch_nb):
+ x=rnn.pack_sequence(batch[0],enforce_sorted=False)
+ y=rnn.pack_sequence(batch[1],enforce_sorted=False)
+
+
+
+
+
Truncated Back Propagation Through Time
+
There are times when multiple backwards passes are needed for each batch. For example, it may save memory to use Truncated Back Propagation Through Time when training RNNs.
+
When this flag is enabled each batch is split into sequences of size truncated_bptt_steps and passed to training_step(...) separately. A default splitting function is provided, however, you can override it for more flexibility. See tbptt_split_batch.
+
1
+2
+3
+4
+5
# DEFAULT (single backwards pass per batch)
+trainer=Trainer(truncated_bptt_steps=None)
+
+# (split batch into sequences of size 2)
+trainer=Trainer(truncated_bptt_steps=2)
+
Set validation check frequency within 1 training epoch
-
For large datasets it's often desirable to check validation multiple times within a training loop
+
For large datasets it's often desirable to check validation multiple times within a training loop.
+Pass in a float to check that often within 1 training epoch.
+Pass in an int k to check every k training batches. Must use an int if using
+an IterableDataset.
1
2
3
4
-5
# DEFAULT
+5
+6
+7
+8
# DEFAULTtrainer=Trainer(val_check_interval=0.95)# check every .25 of an epoch trainer=Trainer(val_check_interval=0.25)
+
+# check every 100 train batches (ie: for IterableDatasets or fixed frequency)
+trainer=Trainer(val_check_interval=100)
@@ -739,7 +748,7 @@ Lightning will run 5 steps of validation in the beginning of training as a sanit
+
@@ -807,6 +877,39 @@ Good place to inspect weight information with weights updated.
+
+
backward
+
Called to perform backward step.
+Feel free to override as needed.
+
The loss passed in has already been scaled for accumulated gradients if requested.
+
1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
+11
+12
+13
defbackward(self,use_amp,loss,optimizer):
+ """
+ Override backward with your own implementation if you need to
+ :param use_amp: Whether amp was requested or not
+ :param loss: Loss is already scaled by accumulated grads
+ :param optimizer: Current optimizer being used
+ :return:
+ """
+ ifuse_amp:
+ withamp.scale_loss(loss,optimizer)asscaled_loss:
+ scaled_loss.backward()
+ else:
+ loss.backward()
+
+
+
on_after_backward
Called in the training loop after model.backward()
@@ -828,6 +931,192 @@ This is the ideal place to inspect or log gradient information
defconfigure_apex(self,amp,model,optimizers,amp_level):
+ """
+ Override to init AMP your own way
+ Must return a model and list of optimizers
+ :param amp:
+ :param model:
+ :param optimizers:
+ :param amp_level:
+ :return: Apex wrapped model and optimizers
+ """
+ model,optimizers=amp.initialize(
+ model,optimizers,opt_level=amp_level,
+ )
+
+ returnmodel,optimizers
+
+
+
+
+
configure_ddp
+
Overwrite to define your own DDP implementation init.
+The only requirement is that:
+1. On a validation batch the call goes to model.validation_step.
+2. On a training batch the call goes to model.training_step.
+3. On a testing batch, the call goes to model.test_step
defconfigure_ddp(self,model,device_ids):
+ """
+ Override to init DDP in a different way or use your own wrapper.
+ Must return model.
+ :param model:
+ :param device_ids:
+ :return: DDP wrapped model
+ """
+ # Lightning DDP simply routes to test_step, val_step, etc...
+ model=LightningDistributedDataParallel(
+ model,
+ device_ids=device_ids,
+ find_unused_parameters=True
+ )
+ returnmodel
+
definit_ddp_connection(self):
+ """
+ Connect all procs in the world using the env:// init
+ Use the first node as the root address
+ """
+
+ # use slurm job id for the port number
+ # guarantees unique ports across jobs from same grid search
+ try:
+ # use the last 4 numbers in the job id as the id
+ default_port=os.environ['SLURM_JOB_ID']
+ default_port=default_port[-4:]
+
+ # all ports should be in the 10k+ range
+ default_port=int(default_port)+15000
+
+ exceptExceptionase:
+ default_port=12910
+
+ # if user gave a port number, use that one instead
+ try:
+ default_port=os.environ['MASTER_PORT']
+ exceptException:
+ os.environ['MASTER_PORT']=str(default_port)
+
+ # figure out the root node addr
+ try:
+ root_node=os.environ['SLURM_NODELIST'].split(' ')[0]
+ exceptException:
+ root_node='127.0.0.2'
+
+ root_node=self.trainer.resolve_root_node_address(root_node)
+ os.environ['MASTER_ADDR']=root_node
+ dist.init_process_group('nccl',rank=self.proc_rank,world_size=self.world_size)
+
+
@@ -897,7 +1186,7 @@ This is the ideal place to inspect or log gradient information
In 99% of cases you want to just copy one of the examples to start a new lightningModule and change the core of what your model is actually trying to do.
+
In 99% of cases you want to just copy one of the examples to start a new lightningModule and change the core of what your model is actually trying to do.
1
2
# get a copy of the module template
-wget https://raw.githubusercontent.com/williamFalcon/pytorch-lightning/master/examples/new_project_templates/lightning_module_template.py
+wget https://raw.githubusercontent.com/williamFalcon/pytorch-lightning/master/pl_examples/new_project_templates/lightning_module_template.py
@@ -796,7 +796,7 @@ argument parser you get the default arguments in the argument parser.
job_display_name=job_display_name[0:3]# run hopt
- print('submitting jobs...')
+ logging.info('submitting jobs...')cluster.optimize_parallel_cluster_gpu(main,nb_trials=hyperparams.nb_hopt_trials,
@@ -862,7 +862,7 @@ argument parser you get the default arguments in the argument parser.
@@ -963,7 +964,7 @@ You would define a single LightningModule and use flags to switch between your d
-
+
diff --git a/search/search_index.json b/search/search_index.json
index a0c1475c..6e70ab11 100644
--- a/search/search_index.json
+++ b/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"New project Quick Start To start a new project define two files, a LightningModule and a Trainer file. To illustrate Lightning power and simplicity, here's an example of a typical research flow. Case 1: BERT Let's say you're working on something like BERT but want to try different ways of training or even different networks. You would define a single LightningModule and use flags to switch between your different ideas. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class BERT ( pl . LightningModule ): def __init__ ( self , model_name , task ): self . task = task if model_name == 'transformer' : self . net = Transformer () elif model_name == 'my_cool_version' : self . net = MyCoolVersion () def training_step ( self , batch , batch_nb ): if self . task == 'standard_bert' : # do standard bert training with self.net... # return loss if self . task == 'my_cool_task' : # do my own version with self.net # return loss Case 2: COOLER NOT BERT But if you wanted to try something completely different, you'd define a new module for that. 1 2 3 4 5 6 7 class CoolerNotBERT ( pl . LightningModule ): def __init__ ( self ): self . net = ... def training_step ( self , batch , batch_nb ): # do some other cool task # return loss Rapid research flow Then you could do rapid research by switching between these two and using the same trainer. 1 2 3 4 5 6 7 if use_bert : model = BERT () else : model = CoolerNotBERT () trainer = Trainer ( gpus = 4 , use_amp = True ) trainer . fit ( model ) Notice a few things about this flow: 1. You're writing pure PyTorch... no unnecessary abstractions or new libraries to learn. 2. You get free GPU and 16-bit support without writing any of that code in your model. 3. You also get all of the capabilities below (without coding or testing yourself). Templates MNIST LightningModule Trainer Basic CPU, GPU Trainer Template GPU cluster Trainer Template Docs shortcuts LightningModule Trainer Quick start examples CPU example Hyperparameter search on single GPU Hyperparameter search on multiple GPUs on same node Hyperparameter search on a SLURM HPC cluster Checkpointing Checkpoint callback Model saving Model loading Restoring training session Computing cluster (SLURM) Running grid search on a cluster Walltime auto-resubmit Debugging Fast dev run Inspect gradient norms Log GPU usage Make model overfit on subset of data Print the parameter count by layer Pring which gradients are nan Print input and output size of every module in system Distributed training 16-bit mixed precision Multi-GPU Multi-node Single GPU Self-balancing architecture Experiment Logging Display metrics in progress bar Log metric row every k batches Process position Tensorboard support Save a snapshot of all hyperparameters Snapshot code for a training run Write logs file to csv every k batches Training loop Accumulate gradients Force training for min or max epochs Early stopping callback Force disable early stop Gradient Clipping Hooks Learning rate scheduling Use multiple optimizers (like GANs) Set how much of the training set to check (1-100%) Step optimizers at arbitrary intervals Validation loop Check validation every n epochs Hooks Set how much of the validation set to check Set how much of the test set to check Set validation check frequency within 1 training epoch Set the number of validation sanity steps Testing loop Run test set","title":"Home"},{"location":"#new-project-quick-start","text":"To start a new project define two files, a LightningModule and a Trainer file. To illustrate Lightning power and simplicity, here's an example of a typical research flow.","title":"New project Quick Start"},{"location":"#case-1-bert","text":"Let's say you're working on something like BERT but want to try different ways of training or even different networks. You would define a single LightningModule and use flags to switch between your different ideas. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class BERT ( pl . LightningModule ): def __init__ ( self , model_name , task ): self . task = task if model_name == 'transformer' : self . net = Transformer () elif model_name == 'my_cool_version' : self . net = MyCoolVersion () def training_step ( self , batch , batch_nb ): if self . task == 'standard_bert' : # do standard bert training with self.net... # return loss if self . task == 'my_cool_task' : # do my own version with self.net # return loss","title":"Case 1: BERT"},{"location":"#case-2-cooler-not-bert","text":"But if you wanted to try something completely different, you'd define a new module for that. 1 2 3 4 5 6 7 class CoolerNotBERT ( pl . LightningModule ): def __init__ ( self ): self . net = ... def training_step ( self , batch , batch_nb ): # do some other cool task # return loss","title":"Case 2: COOLER NOT BERT"},{"location":"#rapid-research-flow","text":"Then you could do rapid research by switching between these two and using the same trainer. 1 2 3 4 5 6 7 if use_bert : model = BERT () else : model = CoolerNotBERT () trainer = Trainer ( gpus = 4 , use_amp = True ) trainer . fit ( model ) Notice a few things about this flow: 1. You're writing pure PyTorch... no unnecessary abstractions or new libraries to learn. 2. You get free GPU and 16-bit support without writing any of that code in your model. 3. You also get all of the capabilities below (without coding or testing yourself).","title":"Rapid research flow"},{"location":"#templates","text":"MNIST LightningModule Trainer Basic CPU, GPU Trainer Template GPU cluster Trainer Template","title":"Templates"},{"location":"#docs-shortcuts","text":"LightningModule Trainer","title":"Docs shortcuts"},{"location":"#quick-start-examples","text":"CPU example Hyperparameter search on single GPU Hyperparameter search on multiple GPUs on same node Hyperparameter search on a SLURM HPC cluster","title":"Quick start examples"},{"location":"#checkpointing","text":"Checkpoint callback Model saving Model loading Restoring training session","title":"Checkpointing"},{"location":"#computing-cluster-slurm","text":"Running grid search on a cluster Walltime auto-resubmit","title":"Computing cluster (SLURM)"},{"location":"#debugging","text":"Fast dev run Inspect gradient norms Log GPU usage Make model overfit on subset of data Print the parameter count by layer Pring which gradients are nan Print input and output size of every module in system","title":"Debugging"},{"location":"#distributed-training","text":"16-bit mixed precision Multi-GPU Multi-node Single GPU Self-balancing architecture","title":"Distributed training"},{"location":"#experiment-logging","text":"Display metrics in progress bar Log metric row every k batches Process position Tensorboard support Save a snapshot of all hyperparameters Snapshot code for a training run Write logs file to csv every k batches","title":"Experiment Logging"},{"location":"#training-loop","text":"Accumulate gradients Force training for min or max epochs Early stopping callback Force disable early stop Gradient Clipping Hooks Learning rate scheduling Use multiple optimizers (like GANs) Set how much of the training set to check (1-100%) Step optimizers at arbitrary intervals","title":"Training loop"},{"location":"#validation-loop","text":"Check validation every n epochs Hooks Set how much of the validation set to check Set how much of the test set to check Set validation check frequency within 1 training epoch Set the number of validation sanity steps","title":"Validation loop"},{"location":"#testing-loop","text":"Run test set","title":"Testing loop"},{"location":"LightningModule/RequiredTrainerInterface/","text":"Lightning Module interface [ Github Code ] A lightning module is a strict superclass of nn.Module, it provides a standard interface for the trainer to interact with the model. The easiest thing to do is copy the minimal example below and modify accordingly. Otherwise, to Define a Lightning Module, implement the following methods: Required : training_step train_dataloader configure_optimizers Optional : validation_step validation_end test_step test_end val_dataloader test_dataloader on_save_checkpoint on_load_checkpoint add_model_specific_args Minimal example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 import os import torch from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision.datasets import MNIST import torchvision.transforms as transforms import pytorch_lightning as pl class CoolModel ( pl . LightningModule ): def __init__ ( self ): super ( CoolModel , self ) . __init__ () # not the best model... self . l1 = torch . nn . Linear ( 28 * 28 , 10 ) def forward ( self , x ): return torch . relu ( self . l1 ( x . view ( x . size ( 0 ), - 1 ))) def training_step ( self , batch , batch_nb ): # REQUIRED x , y = batch y_hat = self . forward ( x ) return { 'loss' : F . cross_entropy ( y_hat , y )} def validation_step ( self , batch , batch_nb ): # OPTIONAL x , y = batch y_hat = self . forward ( x ) return { 'val_loss' : F . cross_entropy ( y_hat , y )} def validation_end ( self , outputs ): # OPTIONAL avg_loss = torch . stack ([ x [ 'val_loss' ] for x in outputs ]) . mean () return { 'avg_val_loss' : avg_loss } def test_step ( self , batch , batch_nb ): # OPTIONAL x , y = batch y_hat = self . forward ( x ) return { 'test_loss' : F . cross_entropy ( y_hat , y )} def test_end ( self , outputs ): # OPTIONAL avg_loss = torch . stack ([ x [ 'test_loss' ] for x in outputs ]) . mean () return { 'avg_test_loss' : avg_loss } def configure_optimizers ( self ): # REQUIRED return torch . optim . Adam ( self . parameters (), lr = 0.02 ) @pl.data_loader def train_dataloader ( self ): return DataLoader ( MNIST ( os . getcwd (), train = True , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) @pl.data_loader def val_dataloader ( self ): # OPTIONAL # can also return a list of val dataloaders return DataLoader ( MNIST ( os . getcwd (), train = True , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) @pl.data_loader def test_dataloader ( self ): # OPTIONAL # can also return a list of test dataloaders return DataLoader ( MNIST ( os . getcwd (), train = False , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) How do these methods fit into the broader training? The LightningModule interface is on the right. Each method corresponds to a part of a research project. Lightning automates everything not in blue. Required Methods training_step 1 def training_step ( self , batch , batch_nb ) In this step you'd normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something specific to your model. Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is Return Dictionary or OrderedDict key value is required loss tensor scalar Y progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 def training_step ( self , batch , batch_nb ): x , y , z = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , x ) logger_logs = { 'training_loss' : loss } # optional (MUST ALL BE TENSORS) # if using TestTubeLogger or TensorboardLogger you can nest scalars logger_logs = { 'losses' : logger_logs } # optional (MUST ALL BE TENSORS) output = { 'loss' : loss , # required 'progress_bar' : { 'training_loss' : loss }, # optional (MUST ALL BE TENSORS) 'log' : logger_logs } # return a dict return output If you define multiple optimizers, this step will also be called with an additional optimizer_idx param. 1 2 3 4 5 6 # Multiple optimizers (ie: GANs) def training_step ( self , batch , batch_nb , optimizer_idx ): if optimizer_idx == 0 : # do training_step with encoder if optimizer_idx == 1 : # do training_step with decoder You can also return a -1 instead of a dict to stop the current loop. This is useful if you want to break out of the current training epoch early. train_dataloader 1 2 @pl.data_loader def train_dataloader ( self ) Called by lightning during training loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator. Return PyTorch DataLoader Example 1 2 3 4 5 6 7 8 9 10 @pl.data_loader def train_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = True , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader configure_optimizers 1 def configure_optimizers ( self ) Set up as many optimizers and (optionally) learning rate schedulers as you need. Normally you'd need one. But in the case of GANs or something more esoteric you might have multiple. Lightning will call .backward() and .step() on each one in every epoch. If you use 16 bit precision it will also handle that. Note: If you use multiple optimizers, training_step will have an additional optimizer_idx parameter. Note 2: If you use LBFGS lightning handles the closure function automatically for you. Return Return any of these 3 options: Single optimizer List or Tuple - List of optimizers Two lists - The first list has multiple optimizers, the second a list of learning-rate schedulers Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # most cases def configure_optimizers ( self ): opt = Adam ( self . parameters (), lr = 0.01 ) return opt # multiple optimizer case (eg: GAN) def configure_optimizers ( self ): generator_opt = Adam ( self . model_gen . parameters (), lr = 0.01 ) disriminator_opt = Adam ( self . model_disc . parameters (), lr = 0.02 ) return generator_opt , disriminator_opt # example with learning_rate schedulers def configure_optimizers ( self ): generator_opt = Adam ( self . model_gen . parameters (), lr = 0.01 ) disriminator_opt = Adam ( self . model_disc . parameters (), lr = 0.02 ) discriminator_sched = CosineAnnealing ( discriminator_opt , T_max = 10 ) return [ generator_opt , disriminator_opt ], [ discriminator_sched ] If you need to control how often those optimizers step or override the default .step() schedule, override the optimizer_step hook. Optional Methods validation_step 1 2 3 4 5 # if you have one val dataloader: def validation_step ( self , batch , batch_nb ) # if you have multiple val dataloaders: def validation_step ( self , batch , batch_nb , dataloader_idxdx ) OPTIONAL If you don't need to validate you don't need to implement this method. In this step you'd normally generate examples or calculate anything of interest such as accuracy. When the validation_step is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, model goes back to training mode and gradients are enabled. The dict you return here will be available in the validation_end method. Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is dataloader_idx Integer displaying which dataloader this is (only if multiple val datasets used) Return Return description optional dict Dict or OrderedDict - passed to the validation_end step N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 # CASE 1: A single validation dataset def validation_step ( self , batch , batch_nb ): x , y = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , y ) # log 6 example images # or generated text... or whatever sample_imgs = x [: 6 ] grid = torchvision . utils . make_grid ( sample_imgs ) self . logger . experiment . add_image ( 'example_images' , grid , 0 ) # calculate acc labels_hat = torch . argmax ( out , dim = 1 ) val_acc = torch . sum ( y == labels_hat ) . item () / ( len ( y ) * 1.0 ) # all optional... # return whatever you need for the collation function validation_end output = OrderedDict ({ 'val_loss' : loss_val , 'val_acc' : torch . tensor ( val_acc ), # everything must be a tensor }) # return an optional dict return output If you pass in multiple validation datasets, validation_step will have an additional argument. 1 2 3 # CASE 2: multiple validation datasets def validation_step ( self , batch , batch_nb , dataset_idx ): # dataset_idx tells you which dataset this is. The dataset_idx corresponds to the order of datasets returned in val_dataloader . validation_end 1 def validation_end ( self , outputs ) If you didn't define a validation_step, this won't be called. Called at the end of the validation loop with the outputs of validation_step. The outputs here are strictly for the progress bar. If you don't need to display anything, don't return anything. Any keys present in 'log', 'progress_bar' or the rest of the dictionary are available for callbacks to access. Params Param description outputs List of outputs you defined in validation_step, or if there are multiple dataloaders, a list containing a list of outputs for each dataloader Return Dictionary or OrderedDict key value is required progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example With a single dataloader 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def validation_end ( self , outputs ): \"\"\" Called at the end of validation to aggregate outputs :param outputs: list of individual outputs of each validation step :return: \"\"\" val_loss_mean = 0 val_acc_mean = 0 for output in outputs : val_loss_mean += output [ 'val_loss' ] val_acc_mean += output [ 'val_acc' ] val_loss_mean /= len ( outputs ) val_acc_mean /= len ( outputs ) tqdm_dict = { 'val_loss' : val_loss_mean . item (), 'val_acc' : val_acc_mean . item ()} # show val_loss and val_acc in progress bar but only log val_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'val_loss' : val_loss_mean . item ()} } return results With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def validation_end ( self , outputs ): \"\"\" Called at the end of validation to aggregate outputs :param outputs: list of list of individual outputs of each validation step :return: \"\"\" val_loss_mean = 0 val_acc_mean = 0 i = 0 for dataloader_outputs in outputs : for output in dataloader_outputs : val_loss_mean += output [ 'val_loss' ] val_acc_mean += output [ 'val_acc' ] i += 1 val_loss_mean /= i val_acc_mean /= i tqdm_dict = { 'val_loss' : val_loss_mean . item (), 'val_acc' : val_acc_mean . item ()} # show val_loss and val_acc in progress bar but only log val_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'val_loss' : val_loss_mean . item ()} } return results test_step 1 2 3 4 5 # if you have one test dataloader: def test_step ( self , batch , batch_nb ) # if you have multiple test dataloaders: def test_step ( self , batch , batch_nb , dataloader_idxdx ) OPTIONAL If you don't need to test you don't need to implement this method. In this step you'd normally generate examples or calculate anything of interest such as accuracy. When the validation_step is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, model goes back to training mode and gradients are enabled. The dict you return here will be available in the test_end method. This function is used when you execute trainer.test() . Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is dataloader_idx Integer displaying which dataloader this is (only if multiple test datasets used) Return Return description optional dict Dict or OrderedDict with metrics to display in progress bar. All keys must be tensors. Y Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # CASE 1: A single test dataset def test_step ( self , batch , batch_nb ): x , y = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , y ) # calculate acc labels_hat = torch . argmax ( out , dim = 1 ) test_acc = torch . sum ( y == labels_hat ) . item () / ( len ( y ) * 1.0 ) # all optional... # return whatever you need for the collation function test_end output = OrderedDict ({ 'test_loss' : loss_test , 'test_acc' : torch . tensor ( test_acc ), # everything must be a tensor }) # return an optional dict return output If you pass in multiple test datasets, test_step will have an additional argument. 1 2 3 # CASE 2: multiple test datasets def test_step ( self , batch , batch_nb , dataset_idx ): # dataset_idx tells you which dataset this is. The dataset_idx corresponds to the order of datasets returned in test_dataloader . test_end 1 def test_end ( self , outputs ) If you didn't define a test_step, this won't be called. Called at the end of the test step with the output of each test_step. The outputs here are strictly for the progress bar. If you don't need to display anything, don't return anything. Params Param description outputs List of outputs you defined in test_step, or if there are multiple dataloaders, a list containing a list of outputs for each dataloader Return Return description optional dict Dict of OrderedDict with metrics to display in progress bar Y Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def test_end ( self , outputs ): \"\"\" Called at the end of test to aggregate outputs :param outputs: list of individual outputs of each test step :return: \"\"\" test_loss_mean = 0 test_acc_mean = 0 for output in outputs : test_loss_mean += output [ 'test_loss' ] test_acc_mean += output [ 'test_acc' ] test_loss_mean /= len ( outputs ) test_acc_mean /= len ( outputs ) tqdm_dict = { 'test_loss' : test_loss_mean . item (), 'test_acc' : test_acc_mean . item ()} # show test_loss and test_acc in progress bar but only log test_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'test_loss' : val_loss_mean . item ()} } return results With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def test_end ( self , outputs ): \"\"\" Called at the end of test to aggregate outputs :param outputs: list of individual outputs of each test step :return: \"\"\" test_loss_mean = 0 test_acc_mean = 0 i = 0 for dataloader_outputs in outputs : for output in dataloader_outputs : test_loss_mean += output [ 'test_loss' ] test_acc_mean += output [ 'test_acc' ] i += 1 test_loss_mean /= i test_acc_mean /= i tqdm_dict = { 'test_loss' : test_loss_mean . item (), 'test_acc' : test_acc_mean . item ()} # show test_loss and test_acc in progress bar but only log test_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'test_loss' : val_loss_mean . item ()} } return results on_save_checkpoint 1 def on_save_checkpoint ( self , checkpoint ) Called by lightning to checkpoint your model. Lightning saves the training state (current epoch, global_step, etc) and also saves the model state_dict. If you want to save anything else, use this method to add your own key-value pair. Return Nothing Example 1 2 3 def on_save_checkpoint ( self , checkpoint ): # 99% of use cases you don't need to implement this method checkpoint [ 'something_cool_i_want_to_save' ] = my_cool_pickable_object on_load_checkpoint 1 def on_load_checkpoint ( self , checkpoint ) Called by lightning to restore your model. Lighting auto-restores global step, epoch, etc... It also restores the model state_dict. If you saved something with on_save_checkpoint this is your chance to restore this. Return Nothing Example 1 2 3 def on_load_checkpoint ( self , checkpoint ): # 99% of the time you don't need to implement this method self . something_cool_i_want_to_save = checkpoint [ 'something_cool_i_want_to_save' ] val_dataloader 1 2 @pl.data_loader def val_dataloader ( self ) OPTIONAL If you don't need a validation dataset and a validation_step, you don't need to implement this method. Called by lightning during validation loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator. Return PyTorch DataLoader or list of PyTorch Dataloaders. Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @pl.data_loader def val_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = False , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader # can also return multiple dataloaders @pl.data_loader def val_dataloader ( self ): return [ loader_a , loader_b , ... , loader_n ] In the case where you return multiple val_dataloaders, the validation_step will have an arguement dataset_idx which matches the order here. test_dataloader 1 2 @pl.data_loader def test_dataloader ( self ) OPTIONAL If you don't need a test dataset and a test_step, you don't need to implement this method. Called by lightning during test loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator. Return PyTorch DataLoader Example 1 2 3 4 5 6 7 8 9 10 11 @pl.data_loader def test_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = False , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader add_model_specific_args 1 2 @staticmethod def add_model_specific_args ( parent_parser , root_dir ) Lightning has a list of default argparse commands. This method is your chance to add or modify commands specific to your model. The hyperparameter argument parser is available anywhere in your model by calling self.hparams. Return An argument parser Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @staticmethod def add_model_specific_args ( parent_parser , root_dir ): parser = HyperOptArgumentParser ( strategy = parent_parser . strategy , parents = [ parent_parser ]) # param overwrites # parser.set_defaults(gradient_clip_val=5.0) # network params parser . opt_list ( '--drop_prob' , default = 0.2 , options = [ 0.2 , 0.5 ], type = float , tunable = False ) parser . add_argument ( '--in_features' , default = 28 * 28 ) parser . add_argument ( '--out_features' , default = 10 ) parser . add_argument ( '--hidden_dim' , default = 50000 ) # use 500 for CPU, 50000 for GPU to see speed difference # data parser . add_argument ( '--data_root' , default = os . path . join ( root_dir , 'mnist' ), type = str ) # training params (opt) parser . opt_list ( '--learning_rate' , default = 0.001 , type = float , options = [ 0.0001 , 0.0005 , 0.001 , 0.005 ], tunable = False ) parser . opt_list ( '--batch_size' , default = 256 , type = int , options = [ 32 , 64 , 128 , 256 ], tunable = False ) parser . opt_list ( '--optimizer_name' , default = 'adam' , type = str , options = [ 'adam' ], tunable = False ) return parser","title":"Lightning Module interface"},{"location":"LightningModule/RequiredTrainerInterface/#lightning-module-interface","text":"[ Github Code ] A lightning module is a strict superclass of nn.Module, it provides a standard interface for the trainer to interact with the model. The easiest thing to do is copy the minimal example below and modify accordingly. Otherwise, to Define a Lightning Module, implement the following methods: Required : training_step train_dataloader configure_optimizers Optional : validation_step validation_end test_step test_end val_dataloader test_dataloader on_save_checkpoint on_load_checkpoint add_model_specific_args","title":"Lightning Module interface"},{"location":"LightningModule/RequiredTrainerInterface/#minimal-example","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 import os import torch from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision.datasets import MNIST import torchvision.transforms as transforms import pytorch_lightning as pl class CoolModel ( pl . LightningModule ): def __init__ ( self ): super ( CoolModel , self ) . __init__ () # not the best model... self . l1 = torch . nn . Linear ( 28 * 28 , 10 ) def forward ( self , x ): return torch . relu ( self . l1 ( x . view ( x . size ( 0 ), - 1 ))) def training_step ( self , batch , batch_nb ): # REQUIRED x , y = batch y_hat = self . forward ( x ) return { 'loss' : F . cross_entropy ( y_hat , y )} def validation_step ( self , batch , batch_nb ): # OPTIONAL x , y = batch y_hat = self . forward ( x ) return { 'val_loss' : F . cross_entropy ( y_hat , y )} def validation_end ( self , outputs ): # OPTIONAL avg_loss = torch . stack ([ x [ 'val_loss' ] for x in outputs ]) . mean () return { 'avg_val_loss' : avg_loss } def test_step ( self , batch , batch_nb ): # OPTIONAL x , y = batch y_hat = self . forward ( x ) return { 'test_loss' : F . cross_entropy ( y_hat , y )} def test_end ( self , outputs ): # OPTIONAL avg_loss = torch . stack ([ x [ 'test_loss' ] for x in outputs ]) . mean () return { 'avg_test_loss' : avg_loss } def configure_optimizers ( self ): # REQUIRED return torch . optim . Adam ( self . parameters (), lr = 0.02 ) @pl.data_loader def train_dataloader ( self ): return DataLoader ( MNIST ( os . getcwd (), train = True , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) @pl.data_loader def val_dataloader ( self ): # OPTIONAL # can also return a list of val dataloaders return DataLoader ( MNIST ( os . getcwd (), train = True , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) @pl.data_loader def test_dataloader ( self ): # OPTIONAL # can also return a list of test dataloaders return DataLoader ( MNIST ( os . getcwd (), train = False , download = True , transform = transforms . ToTensor ()), batch_size = 32 )","title":"Minimal example"},{"location":"LightningModule/RequiredTrainerInterface/#how-do-these-methods-fit-into-the-broader-training","text":"The LightningModule interface is on the right. Each method corresponds to a part of a research project. Lightning automates everything not in blue.","title":"How do these methods fit into the broader training?"},{"location":"LightningModule/RequiredTrainerInterface/#required-methods","text":"","title":"Required Methods"},{"location":"LightningModule/RequiredTrainerInterface/#training_step","text":"1 def training_step ( self , batch , batch_nb ) In this step you'd normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something specific to your model. Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is Return Dictionary or OrderedDict key value is required loss tensor scalar Y progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 def training_step ( self , batch , batch_nb ): x , y , z = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , x ) logger_logs = { 'training_loss' : loss } # optional (MUST ALL BE TENSORS) # if using TestTubeLogger or TensorboardLogger you can nest scalars logger_logs = { 'losses' : logger_logs } # optional (MUST ALL BE TENSORS) output = { 'loss' : loss , # required 'progress_bar' : { 'training_loss' : loss }, # optional (MUST ALL BE TENSORS) 'log' : logger_logs } # return a dict return output If you define multiple optimizers, this step will also be called with an additional optimizer_idx param. 1 2 3 4 5 6 # Multiple optimizers (ie: GANs) def training_step ( self , batch , batch_nb , optimizer_idx ): if optimizer_idx == 0 : # do training_step with encoder if optimizer_idx == 1 : # do training_step with decoder You can also return a -1 instead of a dict to stop the current loop. This is useful if you want to break out of the current training epoch early.","title":"training_step"},{"location":"LightningModule/RequiredTrainerInterface/#train_dataloader","text":"1 2 @pl.data_loader def train_dataloader ( self ) Called by lightning during training loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator.","title":"train_dataloader"},{"location":"LightningModule/RequiredTrainerInterface/#return","text":"PyTorch DataLoader Example 1 2 3 4 5 6 7 8 9 10 @pl.data_loader def train_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = True , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#configure_optimizers","text":"1 def configure_optimizers ( self ) Set up as many optimizers and (optionally) learning rate schedulers as you need. Normally you'd need one. But in the case of GANs or something more esoteric you might have multiple. Lightning will call .backward() and .step() on each one in every epoch. If you use 16 bit precision it will also handle that. Note: If you use multiple optimizers, training_step will have an additional optimizer_idx parameter. Note 2: If you use LBFGS lightning handles the closure function automatically for you.","title":"configure_optimizers"},{"location":"LightningModule/RequiredTrainerInterface/#return_1","text":"Return any of these 3 options: Single optimizer List or Tuple - List of optimizers Two lists - The first list has multiple optimizers, the second a list of learning-rate schedulers Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # most cases def configure_optimizers ( self ): opt = Adam ( self . parameters (), lr = 0.01 ) return opt # multiple optimizer case (eg: GAN) def configure_optimizers ( self ): generator_opt = Adam ( self . model_gen . parameters (), lr = 0.01 ) disriminator_opt = Adam ( self . model_disc . parameters (), lr = 0.02 ) return generator_opt , disriminator_opt # example with learning_rate schedulers def configure_optimizers ( self ): generator_opt = Adam ( self . model_gen . parameters (), lr = 0.01 ) disriminator_opt = Adam ( self . model_disc . parameters (), lr = 0.02 ) discriminator_sched = CosineAnnealing ( discriminator_opt , T_max = 10 ) return [ generator_opt , disriminator_opt ], [ discriminator_sched ] If you need to control how often those optimizers step or override the default .step() schedule, override the optimizer_step hook.","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#optional-methods","text":"","title":"Optional Methods"},{"location":"LightningModule/RequiredTrainerInterface/#validation_step","text":"1 2 3 4 5 # if you have one val dataloader: def validation_step ( self , batch , batch_nb ) # if you have multiple val dataloaders: def validation_step ( self , batch , batch_nb , dataloader_idxdx ) OPTIONAL If you don't need to validate you don't need to implement this method. In this step you'd normally generate examples or calculate anything of interest such as accuracy. When the validation_step is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, model goes back to training mode and gradients are enabled. The dict you return here will be available in the validation_end method. Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is dataloader_idx Integer displaying which dataloader this is (only if multiple val datasets used) Return Return description optional dict Dict or OrderedDict - passed to the validation_end step N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 # CASE 1: A single validation dataset def validation_step ( self , batch , batch_nb ): x , y = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , y ) # log 6 example images # or generated text... or whatever sample_imgs = x [: 6 ] grid = torchvision . utils . make_grid ( sample_imgs ) self . logger . experiment . add_image ( 'example_images' , grid , 0 ) # calculate acc labels_hat = torch . argmax ( out , dim = 1 ) val_acc = torch . sum ( y == labels_hat ) . item () / ( len ( y ) * 1.0 ) # all optional... # return whatever you need for the collation function validation_end output = OrderedDict ({ 'val_loss' : loss_val , 'val_acc' : torch . tensor ( val_acc ), # everything must be a tensor }) # return an optional dict return output If you pass in multiple validation datasets, validation_step will have an additional argument. 1 2 3 # CASE 2: multiple validation datasets def validation_step ( self , batch , batch_nb , dataset_idx ): # dataset_idx tells you which dataset this is. The dataset_idx corresponds to the order of datasets returned in val_dataloader .","title":"validation_step"},{"location":"LightningModule/RequiredTrainerInterface/#validation_end","text":"1 def validation_end ( self , outputs ) If you didn't define a validation_step, this won't be called. Called at the end of the validation loop with the outputs of validation_step. The outputs here are strictly for the progress bar. If you don't need to display anything, don't return anything. Any keys present in 'log', 'progress_bar' or the rest of the dictionary are available for callbacks to access. Params Param description outputs List of outputs you defined in validation_step, or if there are multiple dataloaders, a list containing a list of outputs for each dataloader Return Dictionary or OrderedDict key value is required progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example With a single dataloader 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def validation_end ( self , outputs ): \"\"\" Called at the end of validation to aggregate outputs :param outputs: list of individual outputs of each validation step :return: \"\"\" val_loss_mean = 0 val_acc_mean = 0 for output in outputs : val_loss_mean += output [ 'val_loss' ] val_acc_mean += output [ 'val_acc' ] val_loss_mean /= len ( outputs ) val_acc_mean /= len ( outputs ) tqdm_dict = { 'val_loss' : val_loss_mean . item (), 'val_acc' : val_acc_mean . item ()} # show val_loss and val_acc in progress bar but only log val_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'val_loss' : val_loss_mean . item ()} } return results With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def validation_end ( self , outputs ): \"\"\" Called at the end of validation to aggregate outputs :param outputs: list of list of individual outputs of each validation step :return: \"\"\" val_loss_mean = 0 val_acc_mean = 0 i = 0 for dataloader_outputs in outputs : for output in dataloader_outputs : val_loss_mean += output [ 'val_loss' ] val_acc_mean += output [ 'val_acc' ] i += 1 val_loss_mean /= i val_acc_mean /= i tqdm_dict = { 'val_loss' : val_loss_mean . item (), 'val_acc' : val_acc_mean . item ()} # show val_loss and val_acc in progress bar but only log val_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'val_loss' : val_loss_mean . item ()} } return results","title":"validation_end"},{"location":"LightningModule/RequiredTrainerInterface/#test_step","text":"1 2 3 4 5 # if you have one test dataloader: def test_step ( self , batch , batch_nb ) # if you have multiple test dataloaders: def test_step ( self , batch , batch_nb , dataloader_idxdx ) OPTIONAL If you don't need to test you don't need to implement this method. In this step you'd normally generate examples or calculate anything of interest such as accuracy. When the validation_step is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, model goes back to training mode and gradients are enabled. The dict you return here will be available in the test_end method. This function is used when you execute trainer.test() . Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is dataloader_idx Integer displaying which dataloader this is (only if multiple test datasets used) Return Return description optional dict Dict or OrderedDict with metrics to display in progress bar. All keys must be tensors. Y Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # CASE 1: A single test dataset def test_step ( self , batch , batch_nb ): x , y = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , y ) # calculate acc labels_hat = torch . argmax ( out , dim = 1 ) test_acc = torch . sum ( y == labels_hat ) . item () / ( len ( y ) * 1.0 ) # all optional... # return whatever you need for the collation function test_end output = OrderedDict ({ 'test_loss' : loss_test , 'test_acc' : torch . tensor ( test_acc ), # everything must be a tensor }) # return an optional dict return output If you pass in multiple test datasets, test_step will have an additional argument. 1 2 3 # CASE 2: multiple test datasets def test_step ( self , batch , batch_nb , dataset_idx ): # dataset_idx tells you which dataset this is. The dataset_idx corresponds to the order of datasets returned in test_dataloader .","title":"test_step"},{"location":"LightningModule/RequiredTrainerInterface/#test_end","text":"1 def test_end ( self , outputs ) If you didn't define a test_step, this won't be called. Called at the end of the test step with the output of each test_step. The outputs here are strictly for the progress bar. If you don't need to display anything, don't return anything. Params Param description outputs List of outputs you defined in test_step, or if there are multiple dataloaders, a list containing a list of outputs for each dataloader Return Return description optional dict Dict of OrderedDict with metrics to display in progress bar Y Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def test_end ( self , outputs ): \"\"\" Called at the end of test to aggregate outputs :param outputs: list of individual outputs of each test step :return: \"\"\" test_loss_mean = 0 test_acc_mean = 0 for output in outputs : test_loss_mean += output [ 'test_loss' ] test_acc_mean += output [ 'test_acc' ] test_loss_mean /= len ( outputs ) test_acc_mean /= len ( outputs ) tqdm_dict = { 'test_loss' : test_loss_mean . item (), 'test_acc' : test_acc_mean . item ()} # show test_loss and test_acc in progress bar but only log test_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'test_loss' : val_loss_mean . item ()} } return results With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def test_end ( self , outputs ): \"\"\" Called at the end of test to aggregate outputs :param outputs: list of individual outputs of each test step :return: \"\"\" test_loss_mean = 0 test_acc_mean = 0 i = 0 for dataloader_outputs in outputs : for output in dataloader_outputs : test_loss_mean += output [ 'test_loss' ] test_acc_mean += output [ 'test_acc' ] i += 1 test_loss_mean /= i test_acc_mean /= i tqdm_dict = { 'test_loss' : test_loss_mean . item (), 'test_acc' : test_acc_mean . item ()} # show test_loss and test_acc in progress bar but only log test_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'test_loss' : val_loss_mean . item ()} } return results","title":"test_end"},{"location":"LightningModule/RequiredTrainerInterface/#on_save_checkpoint","text":"1 def on_save_checkpoint ( self , checkpoint ) Called by lightning to checkpoint your model. Lightning saves the training state (current epoch, global_step, etc) and also saves the model state_dict. If you want to save anything else, use this method to add your own key-value pair.","title":"on_save_checkpoint"},{"location":"LightningModule/RequiredTrainerInterface/#return_2","text":"Nothing Example 1 2 3 def on_save_checkpoint ( self , checkpoint ): # 99% of use cases you don't need to implement this method checkpoint [ 'something_cool_i_want_to_save' ] = my_cool_pickable_object","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#on_load_checkpoint","text":"1 def on_load_checkpoint ( self , checkpoint ) Called by lightning to restore your model. Lighting auto-restores global step, epoch, etc... It also restores the model state_dict. If you saved something with on_save_checkpoint this is your chance to restore this.","title":"on_load_checkpoint"},{"location":"LightningModule/RequiredTrainerInterface/#return_3","text":"Nothing Example 1 2 3 def on_load_checkpoint ( self , checkpoint ): # 99% of the time you don't need to implement this method self . something_cool_i_want_to_save = checkpoint [ 'something_cool_i_want_to_save' ]","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#val_dataloader","text":"1 2 @pl.data_loader def val_dataloader ( self ) OPTIONAL If you don't need a validation dataset and a validation_step, you don't need to implement this method. Called by lightning during validation loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator.","title":"val_dataloader"},{"location":"LightningModule/RequiredTrainerInterface/#return_4","text":"PyTorch DataLoader or list of PyTorch Dataloaders. Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @pl.data_loader def val_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = False , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader # can also return multiple dataloaders @pl.data_loader def val_dataloader ( self ): return [ loader_a , loader_b , ... , loader_n ] In the case where you return multiple val_dataloaders, the validation_step will have an arguement dataset_idx which matches the order here.","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#test_dataloader","text":"1 2 @pl.data_loader def test_dataloader ( self ) OPTIONAL If you don't need a test dataset and a test_step, you don't need to implement this method. Called by lightning during test loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator.","title":"test_dataloader"},{"location":"LightningModule/RequiredTrainerInterface/#return_5","text":"PyTorch DataLoader Example 1 2 3 4 5 6 7 8 9 10 11 @pl.data_loader def test_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = False , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#add_model_specific_args","text":"1 2 @staticmethod def add_model_specific_args ( parent_parser , root_dir ) Lightning has a list of default argparse commands. This method is your chance to add or modify commands specific to your model. The hyperparameter argument parser is available anywhere in your model by calling self.hparams.","title":"add_model_specific_args"},{"location":"LightningModule/RequiredTrainerInterface/#return_6","text":"An argument parser Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @staticmethod def add_model_specific_args ( parent_parser , root_dir ): parser = HyperOptArgumentParser ( strategy = parent_parser . strategy , parents = [ parent_parser ]) # param overwrites # parser.set_defaults(gradient_clip_val=5.0) # network params parser . opt_list ( '--drop_prob' , default = 0.2 , options = [ 0.2 , 0.5 ], type = float , tunable = False ) parser . add_argument ( '--in_features' , default = 28 * 28 ) parser . add_argument ( '--out_features' , default = 10 ) parser . add_argument ( '--hidden_dim' , default = 50000 ) # use 500 for CPU, 50000 for GPU to see speed difference # data parser . add_argument ( '--data_root' , default = os . path . join ( root_dir , 'mnist' ), type = str ) # training params (opt) parser . opt_list ( '--learning_rate' , default = 0.001 , type = float , options = [ 0.0001 , 0.0005 , 0.001 , 0.005 ], tunable = False ) parser . opt_list ( '--batch_size' , default = 256 , type = int , options = [ 32 , 64 , 128 , 256 ], tunable = False ) parser . opt_list ( '--optimizer_name' , default = 'adam' , type = str , options = [ 'adam' ], tunable = False ) return parser","title":"Return"},{"location":"LightningModule/methods/","text":"Lightning modules are strict superclasses of torch.nn.Module. A LightningModule offers the following in addition to that API. freeze Freeze all params for inference 1 2 model = MyLightningModule ( ... ) model . freeze () load_from_metrics This is the easiest/fastest way which uses the meta_tags.csv file from test-tube to rebuild the model. The meta_tags.csv file can be found in the test-tube experiment save_dir. 1 2 3 4 5 6 7 8 9 10 11 pretrained_model = MyLightningModule . load_from_metrics ( weights_path = '/path/to/pytorch_checkpoint.ckpt' , tags_csv = '/path/to/test_tube/experiment/version/meta_tags.csv' , on_gpu = True , map_location = None ) # predict pretrained_model . eval () pretrained_model . freeze () y_hat = pretrained_model ( x ) Params Param description weights_path Path to a PyTorch checkpoint tags_csv Path to meta_tags.csv file generated by the test-tube Experiment on_gpu if True, puts model on GPU. Make sure to use transforms option if model devices have changed map_location A dictionary mapping saved weight GPU devices to new GPU devices Returns LightningModule - The pretrained LightningModule unfreeze Unfreeze all params for inference 1 2 model = MyLightningModule ( ... ) model . unfreeze ()","title":"Methods"},{"location":"LightningModule/methods/#freeze","text":"Freeze all params for inference 1 2 model = MyLightningModule ( ... ) model . freeze ()","title":"freeze"},{"location":"LightningModule/methods/#load_from_metrics","text":"This is the easiest/fastest way which uses the meta_tags.csv file from test-tube to rebuild the model. The meta_tags.csv file can be found in the test-tube experiment save_dir. 1 2 3 4 5 6 7 8 9 10 11 pretrained_model = MyLightningModule . load_from_metrics ( weights_path = '/path/to/pytorch_checkpoint.ckpt' , tags_csv = '/path/to/test_tube/experiment/version/meta_tags.csv' , on_gpu = True , map_location = None ) # predict pretrained_model . eval () pretrained_model . freeze () y_hat = pretrained_model ( x ) Params Param description weights_path Path to a PyTorch checkpoint tags_csv Path to meta_tags.csv file generated by the test-tube Experiment on_gpu if True, puts model on GPU. Make sure to use transforms option if model devices have changed map_location A dictionary mapping saved weight GPU devices to new GPU devices Returns LightningModule - The pretrained LightningModule","title":"load_from_metrics"},{"location":"LightningModule/methods/#unfreeze","text":"Unfreeze all params for inference 1 2 model = MyLightningModule ( ... ) model . unfreeze ()","title":"unfreeze"},{"location":"LightningModule/properties/","text":"A LightningModule has the following properties which you can access at any time current_epoch The current epoch dtype Current dtype logger A reference to the logger you passed into trainer. Passing a logger is optional. If you don't pass one in, Lightning will create one for you automatically. This logger saves logs to '''/os.getcwd()/lightning_logs''' 1 Trainer ( logger = your_logger ) Call it from anywhere in your LightningModule to add metrics, images, etc... whatever your logger supports. Here is an example using the TestTubeLogger (which is a wrapper on PyTorch SummaryWriter with versioned folder structure). 1 2 3 4 # if logger is a tensorboard logger or TestTubeLogger self . logger . experiment . add_embedding ( ... ) self . logger . experiment . log ({ 'val_loss' : 0.9 }) self . logger . experiment . add_scalars ( ... ) global_step Total training batches seen across all epochs gradient_clip_val The current gradient clip value on_gpu True if your model is currently running on GPUs. Useful to set flags around the LightningModule for different CPU vs GPU behavior. trainer Last resort access to any state the trainer has. Changing certain properties here could affect your training run. 1 2 3 self . trainer . optimizers self . trainer . current_epoch ... Debugging The LightningModule also offers these tricks to help debug. example_input_array In the LightningModule init, you can set a dummy tensor for this property to get a print out of sizes coming into and out of every layer. 1 2 3 def __init__ ( self ): # put the dimensions of the first input to your system self . example_input_array = torch . rand ( 5 , 28 * 28 )","title":"Properties"},{"location":"LightningModule/properties/#current_epoch","text":"The current epoch","title":"current_epoch"},{"location":"LightningModule/properties/#dtype","text":"Current dtype","title":"dtype"},{"location":"LightningModule/properties/#logger","text":"A reference to the logger you passed into trainer. Passing a logger is optional. If you don't pass one in, Lightning will create one for you automatically. This logger saves logs to '''/os.getcwd()/lightning_logs''' 1 Trainer ( logger = your_logger ) Call it from anywhere in your LightningModule to add metrics, images, etc... whatever your logger supports. Here is an example using the TestTubeLogger (which is a wrapper on PyTorch SummaryWriter with versioned folder structure). 1 2 3 4 # if logger is a tensorboard logger or TestTubeLogger self . logger . experiment . add_embedding ( ... ) self . logger . experiment . log ({ 'val_loss' : 0.9 }) self . logger . experiment . add_scalars ( ... )","title":"logger"},{"location":"LightningModule/properties/#global_step","text":"Total training batches seen across all epochs","title":"global_step"},{"location":"LightningModule/properties/#gradient_clip_val","text":"The current gradient clip value","title":"gradient_clip_val"},{"location":"LightningModule/properties/#on_gpu","text":"True if your model is currently running on GPUs. Useful to set flags around the LightningModule for different CPU vs GPU behavior.","title":"on_gpu"},{"location":"LightningModule/properties/#trainer","text":"Last resort access to any state the trainer has. Changing certain properties here could affect your training run. 1 2 3 self . trainer . optimizers self . trainer . current_epoch ...","title":"trainer"},{"location":"LightningModule/properties/#debugging","text":"The LightningModule also offers these tricks to help debug.","title":"Debugging"},{"location":"LightningModule/properties/#example_input_array","text":"In the LightningModule init, you can set a dummy tensor for this property to get a print out of sizes coming into and out of every layer. 1 2 3 def __init__ ( self ): # put the dimensions of the first input to your system self . example_input_array = torch . rand ( 5 , 28 * 28 )","title":"example_input_array"},{"location":"Trainer/","text":"Trainer [ Github Code ] The lightning trainer abstracts best practices for running a training, val, test routine. It calls parts of your model when it wants to hand over full control and otherwise makes training assumptions which are now standard practice in AI research. This is the basic use of the trainer: 1 2 3 4 5 6 from pytorch_lightning import Trainer model = LightningTemplate () trainer = Trainer () trainer . fit ( model ) But of course the fun is in all the advanced things it can do: Checkpointing Checkpoint callback Model saving Model loading Restoring training session Computing cluster (SLURM) Running grid search on a cluster Walltime auto-resubmit Debugging Fast dev run Inspect gradient norms Log GPU usage Make model overfit on subset of data Print the parameter count by layer Print which gradients are nan Print input and output size of every module in system Distributed training 16-bit mixed precision Multi-GPU Multi-node Single GPU Self-balancing architecture Experiment Logging Display metrics in progress bar Log metric row every k batches Process position Tensorboard support Save a snapshot of all hyperparameters Snapshot code for a training run Write logs file to csv every k batches Training loop Accumulate gradients Force training for min or max epochs Early stopping callback Force disable early stop Gradient Clipping Hooks Learning rate scheduling Use multiple optimizers (like GANs) Set how much of the training set to check (1-100%) Step optimizers at arbitrary intervals Validation loop Check validation every n epochs Hooks Set how much of the validation set to check Set how much of the test set to check Set validation check frequency within 1 training epoch Set the number of validation sanity steps Testing loop Run test set","title":"Trainer"},{"location":"Trainer/#trainer","text":"[ Github Code ] The lightning trainer abstracts best practices for running a training, val, test routine. It calls parts of your model when it wants to hand over full control and otherwise makes training assumptions which are now standard practice in AI research. This is the basic use of the trainer: 1 2 3 4 5 6 from pytorch_lightning import Trainer model = LightningTemplate () trainer = Trainer () trainer . fit ( model ) But of course the fun is in all the advanced things it can do: Checkpointing Checkpoint callback Model saving Model loading Restoring training session Computing cluster (SLURM) Running grid search on a cluster Walltime auto-resubmit Debugging Fast dev run Inspect gradient norms Log GPU usage Make model overfit on subset of data Print the parameter count by layer Print which gradients are nan Print input and output size of every module in system Distributed training 16-bit mixed precision Multi-GPU Multi-node Single GPU Self-balancing architecture Experiment Logging Display metrics in progress bar Log metric row every k batches Process position Tensorboard support Save a snapshot of all hyperparameters Snapshot code for a training run Write logs file to csv every k batches Training loop Accumulate gradients Force training for min or max epochs Early stopping callback Force disable early stop Gradient Clipping Hooks Learning rate scheduling Use multiple optimizers (like GANs) Set how much of the training set to check (1-100%) Step optimizers at arbitrary intervals Validation loop Check validation every n epochs Hooks Set how much of the validation set to check Set how much of the test set to check Set validation check frequency within 1 training epoch Set the number of validation sanity steps Testing loop Run test set","title":"Trainer"},{"location":"Trainer/Checkpointing/","text":"Lightning can automate saving and loading checkpoints. Model saving Checkpointing is enabled by default to the current working directory. To change the checkpoint path pass in : 1 Trainer ( default_save_path = '/your/path/to/save/checkpoints' ) To modify the behavior of checkpointing pass in your own callback. 1 2 3 4 5 6 7 8 9 10 11 12 13 from pytorch_lightning.callbacks import ModelCheckpoint # DEFAULTS used by the Trainer checkpoint_callback = ModelCheckpoint ( filepath = os . getcwd (), save_best_only = True , verbose = True , monitor = 'val_loss' , mode = 'min' , prefix = '' ) trainer = Trainer ( checkpoint_callback = checkpoint_callback ) Restoring training session You might want to not only load a model but also continue training it. Use this method to restore the trainer state as well. This will continue from the epoch and global step you last left off. However, the dataloaders will start from the first batch again (if you shuffled it shouldn't matter). Lightning will restore the session if you pass an experiment with the same version and there's a saved checkpoint. 1 2 3 4 5 6 7 8 9 from test_tube import Experiment exp = Experiment ( version = a_previous_version_with_a_saved_checkpoint ) trainer = Trainer ( experiment = exp ) # this fit call loads model weights and trainer state # the trainer continues seamlessly from where you left off # without having to do anything else. trainer . fit ( model ) The trainer restores: global_step current_epoch All optimizers All lr_schedulers Model weights You can even change the logic of your model as long as the weights and \"architecture\" of the system isn't different. If you add a layer, for instance, it might not work. At a rough level, here's what happens inside Trainer : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 self . global_step = checkpoint [ 'global_step' ] self . current_epoch = checkpoint [ 'epoch' ] # restore the optimizers optimizer_states = checkpoint [ 'optimizer_states' ] for optimizer , opt_state in zip ( self . optimizers , optimizer_states ): optimizer . load_state_dict ( opt_state ) # restore the lr schedulers lr_schedulers = checkpoint [ 'lr_schedulers' ] for scheduler , lrs_state in zip ( self . lr_schedulers , lr_schedulers ): scheduler . load_state_dict ( lrs_state ) # uses the model you passed into trainer model . load_state_dict ( checkpoint [ 'state_dict' ])","title":"Checkpointing"},{"location":"Trainer/Checkpointing/#model-saving","text":"Checkpointing is enabled by default to the current working directory. To change the checkpoint path pass in : 1 Trainer ( default_save_path = '/your/path/to/save/checkpoints' ) To modify the behavior of checkpointing pass in your own callback. 1 2 3 4 5 6 7 8 9 10 11 12 13 from pytorch_lightning.callbacks import ModelCheckpoint # DEFAULTS used by the Trainer checkpoint_callback = ModelCheckpoint ( filepath = os . getcwd (), save_best_only = True , verbose = True , monitor = 'val_loss' , mode = 'min' , prefix = '' ) trainer = Trainer ( checkpoint_callback = checkpoint_callback )","title":"Model saving"},{"location":"Trainer/Checkpointing/#restoring-training-session","text":"You might want to not only load a model but also continue training it. Use this method to restore the trainer state as well. This will continue from the epoch and global step you last left off. However, the dataloaders will start from the first batch again (if you shuffled it shouldn't matter). Lightning will restore the session if you pass an experiment with the same version and there's a saved checkpoint. 1 2 3 4 5 6 7 8 9 from test_tube import Experiment exp = Experiment ( version = a_previous_version_with_a_saved_checkpoint ) trainer = Trainer ( experiment = exp ) # this fit call loads model weights and trainer state # the trainer continues seamlessly from where you left off # without having to do anything else. trainer . fit ( model ) The trainer restores: global_step current_epoch All optimizers All lr_schedulers Model weights You can even change the logic of your model as long as the weights and \"architecture\" of the system isn't different. If you add a layer, for instance, it might not work. At a rough level, here's what happens inside Trainer : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 self . global_step = checkpoint [ 'global_step' ] self . current_epoch = checkpoint [ 'epoch' ] # restore the optimizers optimizer_states = checkpoint [ 'optimizer_states' ] for optimizer , opt_state in zip ( self . optimizers , optimizer_states ): optimizer . load_state_dict ( opt_state ) # restore the lr schedulers lr_schedulers = checkpoint [ 'lr_schedulers' ] for scheduler , lrs_state in zip ( self . lr_schedulers , lr_schedulers ): scheduler . load_state_dict ( lrs_state ) # uses the model you passed into trainer model . load_state_dict ( checkpoint [ 'state_dict' ])","title":"Restoring training session"},{"location":"Trainer/Distributed training/","text":"Lightning makes multi-gpu training and 16 bit training trivial. Note: None of the flags below require changing anything about your lightningModel definition. Choosing a backend Lightning supports two backends. DataParallel and DistributedDataParallel. Both can be used for single-node multi-GPU training. For multi-node training you must use DistributedDataParallel. DataParallel (dp) Splits a batch across multiple GPUs on the same node. Cannot be used for multi-node training. DistributedDataParallel (ddp) Trains a copy of the model on each GPU and only syncs gradients. If used with DistributedSampler, each GPU trains on a subset of the full dataset. DistributedDataParallel-2 (ddp2) Works like DDP, except each node trains a single copy of the model using ALL GPUs on that node. Very useful when dealing with negative samples, etc... You can toggle between each mode by setting this flag. 1 2 3 4 5 6 7 8 9 10 11 # DEFAULT (when using single GPU or no GPUs) trainer = Trainer ( distributed_backend = None ) # Change to DataParallel (gpus > 1) trainer = Trainer ( distributed_backend = 'dp' ) # change to distributed data parallel (gpus > 1) trainer = Trainer ( distributed_backend = 'ddp' ) # change to distributed data parallel (gpus > 1) trainer = Trainer ( distributed_backend = 'ddp2' ) If you request multiple nodes, the back-end will auto-switch to ddp. We recommend you use DistributedDataparallel even for single-node multi-GPU training. It is MUCH faster than DP but may have configuration issues depending on your cluster. For a deeper understanding of what lightning is doing, feel free to read this guide . Distributed and 16-bit precision. Due to an issue with apex and DistributedDataParallel (PyTorch and NVIDIA issue), Lightning does not allow 16-bit and DP training. We tried to get this to work, but it's an issue on their end. Below are the possible configurations we support. 1 GPU 1+ GPUs DP DDP 16-bit command Y Trainer(gpus=1) Y Y Trainer(gpus=1, use_amp=True) Y Y Trainer(gpus=k, distributed_backend='dp') Y Y Trainer(gpus=k, distributed_backend='ddp') Y Y Y Trainer(gpus=k, distributed_backend='ddp', use_amp=True) You also have the option of specifying which GPUs to use by passing a list: 1 2 3 4 5 6 7 8 # DEFAULT (int) Trainer ( gpus = k ) # You specify which GPUs (don't use if running on cluster) Trainer ( gpus = [ 0 , 1 ]) # can also be a string Trainer ( gpus = '0, 1' ) CUDA flags CUDA flags make certain GPUs visible to your script. Lightning sets these for you automatically, there's NO NEED to do this yourself. 1 2 3 # lightning will set according to what you give the trainer # os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" However, when using a cluster, Lightning will NOT set these flags (and you should not either). SLURM will set these for you. 16-bit mixed precision 16 bit precision can cut your memory footprint by half. If using volta architecture GPUs it can give a dramatic training speed-up as well. First, install apex (if install fails, look here ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 $ git clone https://github.com/NVIDIA/apex $ cd apex # ------------------------ # OPTIONAL: on your cluster you might need to load cuda 10 or 9 # depending on how you installed PyTorch # see available modules module avail # load correct cuda before install module load cuda-10.0 # ------------------------ # make sure you've loaded a cuda version > 4.0 and < 7.0 module load gcc-6.1.0 $ pip install -v --no-cache-dir --global-option = \"--cpp_ext\" --global-option = \"--cuda_ext\" ./ then set this use_amp to True. 1 2 # DEFAULT trainer = Trainer ( amp_level = 'O2' , use_amp = False ) Single-gpu Make sure you're on a GPU machine. 1 2 # DEFAULT trainer = Trainer ( gpus = 1 ) multi-gpu Make sure you're on a GPU machine. You can set as many GPUs as you want. In this setting, the model will run on all 8 GPUs at once using DataParallel under the hood. 1 2 3 4 5 # to use DataParallel trainer = Trainer ( gpus = 8 , distributed_backend = 'dp' ) # RECOMMENDED use DistributedDataParallel trainer = Trainer ( gpus = 8 , distributed_backend = 'ddp' ) Multi-node Multi-node training is easily done by specifying these flags. 1 2 # train on 12*8 GPUs trainer = Trainer ( gpus = 8 , nb_gpu_nodes = 12 , distributed_backend = 'ddp' ) You must configure your job submission script correctly for the trainer to work. Here is an example script for the above trainer configuration. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #!/bin/bash -l # SLURM SUBMIT SCRIPT #SBATCH --nodes=12 #SBATCH --gres=gpu:8 #SBATCH --ntasks-per-node=8 #SBATCH --mem=0 #SBATCH --time=0-02:00:00 # activate conda env conda activate my_env # ------------------------- # OPTIONAL # ------------------------- # debugging flags (optional) # export NCCL_DEBUG=INFO # export PYTHONFAULTHANDLER=1 # PyTorch comes with prebuilt NCCL support... but if you have issues with it # you might need to load the latest version from your modules # module load NCCL/2.4.7-1-cuda.10.0 # on your cluster you might need these: # set the network interface # export NCCL_SOCKET_IFNAME=^docker0,lo # ------------------------- # random port between 12k and 20k export MASTER_PORT = $(( 12000 + RANDOM % 20000 )) # run script from above python my_main_file.py NOTE: When running in DDP mode, any errors in your code will show up as an NCCL issue. Set the NCCL_DEBUG=INFO flag to see the ACTUAL error. Finally, make sure to add a distributed sampler to your dataset. The distributed sampler copies a portion of your dataset onto each GPU. (World_size = gpus_per_node * nb_nodes). 1 2 3 4 5 6 7 8 # ie: this: dataset = myDataset () dataloader = Dataloader ( dataset ) # becomes: dataset = myDataset () dist_sampler = torch . utils . data . distributed . DistributedSampler ( dataset ) dataloader = Dataloader ( dataset , sampler = dist_sampler ) Auto-slurm-job-submission Instead of manually building SLURM scripts, you can use the SlurmCluster object to do this for you. The SlurmCluster can also run a grid search if you pass in a HyperOptArgumentParser . Here is an example where you run a grid search of 9 combinations of hyperparams. The full examples are here . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 # grid search 3 values of learning rate and 3 values of number of layers for your net # this generates 9 experiments (lr=1e-3, layers=16), (lr=1e-3, layers=32), (lr=1e-3, layers=64), ... (lr=1e-1, layers=64) parser = HyperOptArgumentParser ( strategy = 'grid_search' , add_help = False ) parser . opt_list ( '--learning_rate' , default = 0.001 , type = float , options = [ 1e-3 , 1e-2 , 1e-1 ], tunable = True ) parser . opt_list ( '--layers' , default = 1 , type = float , options = [ 16 , 32 , 64 ], tunable = True ) hyperparams = parser . parse_args () # Slurm cluster submits 9 jobs, each with a set of hyperparams cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = '/some/path/to/save' , ) # OPTIONAL FLAGS WHICH MAY BE CLUSTER DEPENDENT # which interface your nodes use for communication cluster . add_command ( 'export NCCL_SOCKET_IFNAME=^docker0,lo' ) # see output of the NCCL connection process # NCCL is how the nodes talk to each other cluster . add_command ( 'export NCCL_DEBUG=INFO' ) # setting a master port here is a good idea. cluster . add_command ( 'export MASTER_PORT= %r ' % PORT ) # ************** DON'T FORGET THIS *************** # MUST load the latest NCCL version cluster . load_modules ([ 'NCCL/2.4.7-1-cuda.10.0' ]) # configure cluster cluster . per_experiment_nb_nodes = 12 cluster . per_experiment_nb_gpus = 8 cluster . add_slurm_cmd ( cmd = 'ntasks-per-node' , value = 8 , comment = '1 task per gpu' ) # submit a script with 9 combinations of hyper params # (lr=1e-3, layers=16), (lr=1e-3, layers=32), (lr=1e-3, layers=64), ... (lr=1e-1, layers=64) cluster . optimize_parallel_cluster_gpu ( main , nb_trials = 9 , # how many permutations of the grid search to run job_name = 'name_for_squeue' ) The other option is that you generate scripts on your own via a bash command or use another library... Self-balancing architecture Here lightning distributes parts of your module across available GPUs to optimize for speed and memory. COMING SOON.","title":"Distributed training"},{"location":"Trainer/Distributed training/#choosing-a-backend","text":"Lightning supports two backends. DataParallel and DistributedDataParallel. Both can be used for single-node multi-GPU training. For multi-node training you must use DistributedDataParallel.","title":"Choosing a backend"},{"location":"Trainer/Distributed training/#dataparallel-dp","text":"Splits a batch across multiple GPUs on the same node. Cannot be used for multi-node training.","title":"DataParallel (dp)"},{"location":"Trainer/Distributed training/#distributeddataparallel-ddp","text":"Trains a copy of the model on each GPU and only syncs gradients. If used with DistributedSampler, each GPU trains on a subset of the full dataset.","title":"DistributedDataParallel (ddp)"},{"location":"Trainer/Distributed training/#distributeddataparallel-2-ddp2","text":"Works like DDP, except each node trains a single copy of the model using ALL GPUs on that node. Very useful when dealing with negative samples, etc... You can toggle between each mode by setting this flag. 1 2 3 4 5 6 7 8 9 10 11 # DEFAULT (when using single GPU or no GPUs) trainer = Trainer ( distributed_backend = None ) # Change to DataParallel (gpus > 1) trainer = Trainer ( distributed_backend = 'dp' ) # change to distributed data parallel (gpus > 1) trainer = Trainer ( distributed_backend = 'ddp' ) # change to distributed data parallel (gpus > 1) trainer = Trainer ( distributed_backend = 'ddp2' ) If you request multiple nodes, the back-end will auto-switch to ddp. We recommend you use DistributedDataparallel even for single-node multi-GPU training. It is MUCH faster than DP but may have configuration issues depending on your cluster. For a deeper understanding of what lightning is doing, feel free to read this guide .","title":"DistributedDataParallel-2 (ddp2)"},{"location":"Trainer/Distributed training/#distributed-and-16-bit-precision","text":"Due to an issue with apex and DistributedDataParallel (PyTorch and NVIDIA issue), Lightning does not allow 16-bit and DP training. We tried to get this to work, but it's an issue on their end. Below are the possible configurations we support. 1 GPU 1+ GPUs DP DDP 16-bit command Y Trainer(gpus=1) Y Y Trainer(gpus=1, use_amp=True) Y Y Trainer(gpus=k, distributed_backend='dp') Y Y Trainer(gpus=k, distributed_backend='ddp') Y Y Y Trainer(gpus=k, distributed_backend='ddp', use_amp=True) You also have the option of specifying which GPUs to use by passing a list: 1 2 3 4 5 6 7 8 # DEFAULT (int) Trainer ( gpus = k ) # You specify which GPUs (don't use if running on cluster) Trainer ( gpus = [ 0 , 1 ]) # can also be a string Trainer ( gpus = '0, 1' )","title":"Distributed and 16-bit precision."},{"location":"Trainer/Distributed training/#cuda-flags","text":"CUDA flags make certain GPUs visible to your script. Lightning sets these for you automatically, there's NO NEED to do this yourself. 1 2 3 # lightning will set according to what you give the trainer # os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" However, when using a cluster, Lightning will NOT set these flags (and you should not either). SLURM will set these for you.","title":"CUDA flags"},{"location":"Trainer/Distributed training/#16-bit-mixed-precision","text":"16 bit precision can cut your memory footprint by half. If using volta architecture GPUs it can give a dramatic training speed-up as well. First, install apex (if install fails, look here ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 $ git clone https://github.com/NVIDIA/apex $ cd apex # ------------------------ # OPTIONAL: on your cluster you might need to load cuda 10 or 9 # depending on how you installed PyTorch # see available modules module avail # load correct cuda before install module load cuda-10.0 # ------------------------ # make sure you've loaded a cuda version > 4.0 and < 7.0 module load gcc-6.1.0 $ pip install -v --no-cache-dir --global-option = \"--cpp_ext\" --global-option = \"--cuda_ext\" ./ then set this use_amp to True. 1 2 # DEFAULT trainer = Trainer ( amp_level = 'O2' , use_amp = False )","title":"16-bit mixed precision"},{"location":"Trainer/Distributed training/#single-gpu","text":"Make sure you're on a GPU machine. 1 2 # DEFAULT trainer = Trainer ( gpus = 1 )","title":"Single-gpu"},{"location":"Trainer/Distributed training/#multi-gpu","text":"Make sure you're on a GPU machine. You can set as many GPUs as you want. In this setting, the model will run on all 8 GPUs at once using DataParallel under the hood. 1 2 3 4 5 # to use DataParallel trainer = Trainer ( gpus = 8 , distributed_backend = 'dp' ) # RECOMMENDED use DistributedDataParallel trainer = Trainer ( gpus = 8 , distributed_backend = 'ddp' )","title":"multi-gpu"},{"location":"Trainer/Distributed training/#multi-node","text":"Multi-node training is easily done by specifying these flags. 1 2 # train on 12*8 GPUs trainer = Trainer ( gpus = 8 , nb_gpu_nodes = 12 , distributed_backend = 'ddp' ) You must configure your job submission script correctly for the trainer to work. Here is an example script for the above trainer configuration. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #!/bin/bash -l # SLURM SUBMIT SCRIPT #SBATCH --nodes=12 #SBATCH --gres=gpu:8 #SBATCH --ntasks-per-node=8 #SBATCH --mem=0 #SBATCH --time=0-02:00:00 # activate conda env conda activate my_env # ------------------------- # OPTIONAL # ------------------------- # debugging flags (optional) # export NCCL_DEBUG=INFO # export PYTHONFAULTHANDLER=1 # PyTorch comes with prebuilt NCCL support... but if you have issues with it # you might need to load the latest version from your modules # module load NCCL/2.4.7-1-cuda.10.0 # on your cluster you might need these: # set the network interface # export NCCL_SOCKET_IFNAME=^docker0,lo # ------------------------- # random port between 12k and 20k export MASTER_PORT = $(( 12000 + RANDOM % 20000 )) # run script from above python my_main_file.py NOTE: When running in DDP mode, any errors in your code will show up as an NCCL issue. Set the NCCL_DEBUG=INFO flag to see the ACTUAL error. Finally, make sure to add a distributed sampler to your dataset. The distributed sampler copies a portion of your dataset onto each GPU. (World_size = gpus_per_node * nb_nodes). 1 2 3 4 5 6 7 8 # ie: this: dataset = myDataset () dataloader = Dataloader ( dataset ) # becomes: dataset = myDataset () dist_sampler = torch . utils . data . distributed . DistributedSampler ( dataset ) dataloader = Dataloader ( dataset , sampler = dist_sampler )","title":"Multi-node"},{"location":"Trainer/Distributed training/#auto-slurm-job-submission","text":"Instead of manually building SLURM scripts, you can use the SlurmCluster object to do this for you. The SlurmCluster can also run a grid search if you pass in a HyperOptArgumentParser . Here is an example where you run a grid search of 9 combinations of hyperparams. The full examples are here . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 # grid search 3 values of learning rate and 3 values of number of layers for your net # this generates 9 experiments (lr=1e-3, layers=16), (lr=1e-3, layers=32), (lr=1e-3, layers=64), ... (lr=1e-1, layers=64) parser = HyperOptArgumentParser ( strategy = 'grid_search' , add_help = False ) parser . opt_list ( '--learning_rate' , default = 0.001 , type = float , options = [ 1e-3 , 1e-2 , 1e-1 ], tunable = True ) parser . opt_list ( '--layers' , default = 1 , type = float , options = [ 16 , 32 , 64 ], tunable = True ) hyperparams = parser . parse_args () # Slurm cluster submits 9 jobs, each with a set of hyperparams cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = '/some/path/to/save' , ) # OPTIONAL FLAGS WHICH MAY BE CLUSTER DEPENDENT # which interface your nodes use for communication cluster . add_command ( 'export NCCL_SOCKET_IFNAME=^docker0,lo' ) # see output of the NCCL connection process # NCCL is how the nodes talk to each other cluster . add_command ( 'export NCCL_DEBUG=INFO' ) # setting a master port here is a good idea. cluster . add_command ( 'export MASTER_PORT= %r ' % PORT ) # ************** DON'T FORGET THIS *************** # MUST load the latest NCCL version cluster . load_modules ([ 'NCCL/2.4.7-1-cuda.10.0' ]) # configure cluster cluster . per_experiment_nb_nodes = 12 cluster . per_experiment_nb_gpus = 8 cluster . add_slurm_cmd ( cmd = 'ntasks-per-node' , value = 8 , comment = '1 task per gpu' ) # submit a script with 9 combinations of hyper params # (lr=1e-3, layers=16), (lr=1e-3, layers=32), (lr=1e-3, layers=64), ... (lr=1e-1, layers=64) cluster . optimize_parallel_cluster_gpu ( main , nb_trials = 9 , # how many permutations of the grid search to run job_name = 'name_for_squeue' ) The other option is that you generate scripts on your own via a bash command or use another library...","title":"Auto-slurm-job-submission"},{"location":"Trainer/Distributed training/#self-balancing-architecture","text":"Here lightning distributes parts of your module across available GPUs to optimize for speed and memory. COMING SOON.","title":"Self-balancing architecture"},{"location":"Trainer/Logging/","text":"Lighting offers options for logging information about model, gpu usage, etc, via several different logging frameworks. It also offers printing options for training monitoring. default_save_path Lightning sets a default TestTubeLogger and CheckpointCallback for you which log to os.getcwd() by default. To modify the logging path you can set: 1 Trainer ( default_save_path = '/your/path/to/save/checkpoints' ) If you need more custom behavior (different paths for both, different metrics, etc...) from the logger and the checkpointCallback, pass in your own instances as explained below. Setting up logging The trainer inits a default logger for you (TestTubeLogger). All logs will go to the current working directory under a folder named `os.getcwd()/lightning_logs . If you want to modify the default logging behavior even more, pass in a logger (which should inherit from LightningBaseLogger ). 1 2 my_logger = MyLightningLogger ( ... ) trainer = Trainer ( logger = my_logger ) The path in this logger will overwrite default_save_path. Lightning supports several common experiment tracking frameworks out of the box Test tube Log using test tube . Test tube logger is a strict subclass of PyTorch SummaryWriter , refer to their documentation for all supported operations. The TestTubeLogger adds a nicer folder structure to manage experiments and snapshots all hyperparameters you pass to a LightningModule. 1 2 3 4 5 6 7 8 from pytorch_lightning.logging import TestTubeLogger tt_logger = TestTubeLogger ( save_dir = \".\" , name = \"default\" , debug = False , create_git_tag = False ) trainer = Trainer ( logger = tt_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_method_summary_writer_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . add_histogram ( ... ) MLFlow Log using mlflow 1 2 3 4 5 6 from pytorch_lightning.logging import MLFlowLogger mlf_logger = MLFlowLogger ( experiment_name = \"default\" , tracking_uri = \"file:/.\" ) trainer = Trainer ( logger = mlf_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_ml_flow_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . whatever_ml_flow_supports ( ... ) Custom logger You can implement your own logger by writing a class that inherits from LightningLoggerBase . Use the rank_zero_only decorator to make sure that only the first process in DDP training logs data. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from pytorch_lightning.logging import LightningLoggerBase , rank_zero_only class MyLogger ( LightningLoggerBase ): @rank_zero_only def log_hyperparams ( self , params ): # params is an argparse.Namespace # your code to record hyperparameters goes here pass @rank_zero_only def log_metrics ( self , metrics , step_num ): # metrics is a dictionary of metric names and values # your code to record metrics goes here pass def save ( self ): # Optional. Any code necessary to save logger data goes here pass @rank_zero_only def finalize ( self , status ): # Optional. Any code that needs to be run after training # finishes goes here If you write a logger than may be useful to others, please send a pull request to add it to Lighting! Using loggers You can call the logger anywhere from your LightningModule by doing: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_method_summary_writer_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . add_histogram ( ... ) Display metrics in progress bar 1 2 # DEFAULT trainer = Trainer ( show_progress_bar = True ) Log metric row every k batches Every k batches lightning will make an entry in the metrics log 1 2 # DEFAULT (ie: save a .csv log file every 10 batches) trainer = Trainer ( row_log_interval = 10 ) Log GPU memory Logs GPU memory when metrics are logged. 1 2 3 4 5 6 7 8 # DEFAULT trainer = Trainer ( log_gpu_memory = None ) # log only the min/max utilization trainer = Trainer ( log_gpu_memory = 'min_max' ) # log all the GPU memory (if on DDP, logs only that node) trainer = Trainer ( log_gpu_memory = 'all' ) Process position When running multiple models on the same machine we want to decide which progress bar to use. Lightning will stack progress bars according to this value. 1 2 3 4 5 # DEFAULT trainer = Trainer ( process_position = 0 ) # if this is the second model on the node, show the second progress bar below trainer = Trainer ( process_position = 1 ) Save a snapshot of all hyperparameters Automatically log hyperparameters stored in the hparams attribute as an argparse.Namespace 1 2 3 4 5 6 7 8 9 10 11 12 class MyModel ( pl . Lightning ): def __init__ ( self , hparams ): self . hparams = hparams ... args = parser . parse_args () model = MyModel ( args ) logger = TestTubeLogger ( ... ) t = Trainer ( logger = logger ) trainer . fit ( model ) Write logs file to csv every k batches Every k batches, lightning will write the new logs to disk 1 2 # DEFAULT (ie: save a .csv log file every 100 batches) trainer = Trainer ( log_save_interval = 100 )","title":"Logging"},{"location":"Trainer/Logging/#default_save_path","text":"Lightning sets a default TestTubeLogger and CheckpointCallback for you which log to os.getcwd() by default. To modify the logging path you can set: 1 Trainer ( default_save_path = '/your/path/to/save/checkpoints' ) If you need more custom behavior (different paths for both, different metrics, etc...) from the logger and the checkpointCallback, pass in your own instances as explained below.","title":"default_save_path"},{"location":"Trainer/Logging/#setting-up-logging","text":"The trainer inits a default logger for you (TestTubeLogger). All logs will go to the current working directory under a folder named `os.getcwd()/lightning_logs . If you want to modify the default logging behavior even more, pass in a logger (which should inherit from LightningBaseLogger ). 1 2 my_logger = MyLightningLogger ( ... ) trainer = Trainer ( logger = my_logger ) The path in this logger will overwrite default_save_path. Lightning supports several common experiment tracking frameworks out of the box","title":"Setting up logging"},{"location":"Trainer/Logging/#test-tube","text":"Log using test tube . Test tube logger is a strict subclass of PyTorch SummaryWriter , refer to their documentation for all supported operations. The TestTubeLogger adds a nicer folder structure to manage experiments and snapshots all hyperparameters you pass to a LightningModule. 1 2 3 4 5 6 7 8 from pytorch_lightning.logging import TestTubeLogger tt_logger = TestTubeLogger ( save_dir = \".\" , name = \"default\" , debug = False , create_git_tag = False ) trainer = Trainer ( logger = tt_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_method_summary_writer_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . add_histogram ( ... )","title":"Test tube"},{"location":"Trainer/Logging/#mlflow","text":"Log using mlflow 1 2 3 4 5 6 from pytorch_lightning.logging import MLFlowLogger mlf_logger = MLFlowLogger ( experiment_name = \"default\" , tracking_uri = \"file:/.\" ) trainer = Trainer ( logger = mlf_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_ml_flow_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . whatever_ml_flow_supports ( ... )","title":"MLFlow"},{"location":"Trainer/Logging/#custom-logger","text":"You can implement your own logger by writing a class that inherits from LightningLoggerBase . Use the rank_zero_only decorator to make sure that only the first process in DDP training logs data. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from pytorch_lightning.logging import LightningLoggerBase , rank_zero_only class MyLogger ( LightningLoggerBase ): @rank_zero_only def log_hyperparams ( self , params ): # params is an argparse.Namespace # your code to record hyperparameters goes here pass @rank_zero_only def log_metrics ( self , metrics , step_num ): # metrics is a dictionary of metric names and values # your code to record metrics goes here pass def save ( self ): # Optional. Any code necessary to save logger data goes here pass @rank_zero_only def finalize ( self , status ): # Optional. Any code that needs to be run after training # finishes goes here If you write a logger than may be useful to others, please send a pull request to add it to Lighting!","title":"Custom logger"},{"location":"Trainer/Logging/#using-loggers","text":"You can call the logger anywhere from your LightningModule by doing: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_method_summary_writer_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . add_histogram ( ... )","title":"Using loggers"},{"location":"Trainer/Logging/#display-metrics-in-progress-bar","text":"1 2 # DEFAULT trainer = Trainer ( show_progress_bar = True )","title":"Display metrics in progress bar"},{"location":"Trainer/Logging/#log-metric-row-every-k-batches","text":"Every k batches lightning will make an entry in the metrics log 1 2 # DEFAULT (ie: save a .csv log file every 10 batches) trainer = Trainer ( row_log_interval = 10 )","title":"Log metric row every k batches"},{"location":"Trainer/Logging/#log-gpu-memory","text":"Logs GPU memory when metrics are logged. 1 2 3 4 5 6 7 8 # DEFAULT trainer = Trainer ( log_gpu_memory = None ) # log only the min/max utilization trainer = Trainer ( log_gpu_memory = 'min_max' ) # log all the GPU memory (if on DDP, logs only that node) trainer = Trainer ( log_gpu_memory = 'all' )","title":"Log GPU memory"},{"location":"Trainer/Logging/#process-position","text":"When running multiple models on the same machine we want to decide which progress bar to use. Lightning will stack progress bars according to this value. 1 2 3 4 5 # DEFAULT trainer = Trainer ( process_position = 0 ) # if this is the second model on the node, show the second progress bar below trainer = Trainer ( process_position = 1 )","title":"Process position"},{"location":"Trainer/Logging/#save-a-snapshot-of-all-hyperparameters","text":"Automatically log hyperparameters stored in the hparams attribute as an argparse.Namespace 1 2 3 4 5 6 7 8 9 10 11 12 class MyModel ( pl . Lightning ): def __init__ ( self , hparams ): self . hparams = hparams ... args = parser . parse_args () model = MyModel ( args ) logger = TestTubeLogger ( ... ) t = Trainer ( logger = logger ) trainer . fit ( model )","title":"Save a snapshot of all hyperparameters"},{"location":"Trainer/Logging/#write-logs-file-to-csv-every-k-batches","text":"Every k batches, lightning will write the new logs to disk 1 2 # DEFAULT (ie: save a .csv log file every 100 batches) trainer = Trainer ( log_save_interval = 100 )","title":"Write logs file to csv every k batches"},{"location":"Trainer/SLURM Managed Cluster/","text":"Lightning supports model training on a cluster managed by SLURM in the following cases: Training on a single cpu or single GPU. Train on multiple GPUs on the same node using DataParallel or DistributedDataParallel Training across multiple GPUs on multiple different nodes via DistributedDataParallel. Note: A node means a machine with multiple GPUs Running grid search on a cluster To use lightning to run a hyperparameter search (grid-search or random-search) on a cluster do 4 things: (1). Define the parameters for the grid search 1 2 3 4 5 6 7 8 9 10 from test_tube import HyperOptArgumentParser # subclass of argparse parser = HyperOptArgumentParser ( strategy = 'random_search' ) parser . add_argument ( '--learning_rate' , default = 0.002 , type = float , help = 'the learning rate' ) # let's enable optimizing over the number of layers in the network parser . opt_list ( '--nb_layers' , default = 2 , type = int , tunable = True , options = [ 2 , 4 , 8 ]) hparams = parser . parse_args () NOTE You must set Tunable=True for that argument to be considered in the permutation set. Otherwise test-tube will use the default value. This flag is useful when you don't want to search over an argument and want to use the default instead. (2). Define the cluster options in the SlurmCluster object (over 5 nodes and 8 gpus) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from test_tube.hpc import SlurmCluster # hyperparameters is a test-tube hyper params object # see https://williamfalcon.github.io/test-tube/hyperparameter_optimization/HyperOptArgumentParser/ hyperparams = args . parse () # init cluster cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = '/path/to/log/results/to' , python_cmd = 'python3' ) # let the cluster know where to email for a change in job status (ie: complete, fail, etc...) cluster . notify_job_status ( email = 'some@email.com' , on_done = True , on_fail = True ) # set the job options. In this instance, we'll run 20 different models # each with its own set of hyperparameters giving each one 1 GPU (ie: taking up 20 GPUs) cluster . per_experiment_nb_gpus = 8 cluster . per_experiment_nb_nodes = 5 # we'll request 10GB of memory per node cluster . memory_mb_per_node = 10000 # set a walltime of 10 minues cluster . job_time = '10:00' (3). Make a main function with your model and trainer. Each job will call this function with a particular hparams configuration. 1 2 3 4 5 6 7 8 9 10 from pytorch_lightning import Trainer def train_fx ( trial_hparams , cluster_manager , _ ): # hparams has a specific set of hyperparams my_model = MyLightningModel () # give the trainer the cluster object trainer = Trainer () trainer . fit ( my_model ) (3). Start the grid/random search 1 2 3 4 5 6 # run the models on the cluster cluster . optimize_parallel_cluster_gpu ( train_fx , nb_trials = 20 , job_name = 'my_grid_search_exp_name' , job_display_name = 'my_exp' ) NOTE nb_trials specifies how many of the possible permutations to use. If using grid_search it will use the depth first ordering. If using random_search it will use the first k shuffled options. FYI, random search has been shown to be just as good as any Bayesian optimization method when using a reasonable number of samples (60), see this paper for more information . Walltime auto-resubmit Lightning automatically resubmits jobs when they reach the walltime. Make sure to set the SIGUSR1 signal in your SLURM script. 1 2 # 90 seconds before training ends #SBATCH --signal=SIGUSR1@90 When lightning receives the SIGUSR1 signal it will: 1. save a checkpoint with 'hpc_ckpt' in the name. 2. resubmit the job using the SLURM_JOB_ID When the script starts again, Lightning will: 1. search for a 'hpc_ckpt' checkpoint. 2. restore the model, optimizers, schedulers, epoch, etc...","title":"SLURM Managed Cluster"},{"location":"Trainer/SLURM Managed Cluster/#running-grid-search-on-a-cluster","text":"To use lightning to run a hyperparameter search (grid-search or random-search) on a cluster do 4 things: (1). Define the parameters for the grid search 1 2 3 4 5 6 7 8 9 10 from test_tube import HyperOptArgumentParser # subclass of argparse parser = HyperOptArgumentParser ( strategy = 'random_search' ) parser . add_argument ( '--learning_rate' , default = 0.002 , type = float , help = 'the learning rate' ) # let's enable optimizing over the number of layers in the network parser . opt_list ( '--nb_layers' , default = 2 , type = int , tunable = True , options = [ 2 , 4 , 8 ]) hparams = parser . parse_args () NOTE You must set Tunable=True for that argument to be considered in the permutation set. Otherwise test-tube will use the default value. This flag is useful when you don't want to search over an argument and want to use the default instead. (2). Define the cluster options in the SlurmCluster object (over 5 nodes and 8 gpus) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from test_tube.hpc import SlurmCluster # hyperparameters is a test-tube hyper params object # see https://williamfalcon.github.io/test-tube/hyperparameter_optimization/HyperOptArgumentParser/ hyperparams = args . parse () # init cluster cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = '/path/to/log/results/to' , python_cmd = 'python3' ) # let the cluster know where to email for a change in job status (ie: complete, fail, etc...) cluster . notify_job_status ( email = 'some@email.com' , on_done = True , on_fail = True ) # set the job options. In this instance, we'll run 20 different models # each with its own set of hyperparameters giving each one 1 GPU (ie: taking up 20 GPUs) cluster . per_experiment_nb_gpus = 8 cluster . per_experiment_nb_nodes = 5 # we'll request 10GB of memory per node cluster . memory_mb_per_node = 10000 # set a walltime of 10 minues cluster . job_time = '10:00' (3). Make a main function with your model and trainer. Each job will call this function with a particular hparams configuration. 1 2 3 4 5 6 7 8 9 10 from pytorch_lightning import Trainer def train_fx ( trial_hparams , cluster_manager , _ ): # hparams has a specific set of hyperparams my_model = MyLightningModel () # give the trainer the cluster object trainer = Trainer () trainer . fit ( my_model ) (3). Start the grid/random search 1 2 3 4 5 6 # run the models on the cluster cluster . optimize_parallel_cluster_gpu ( train_fx , nb_trials = 20 , job_name = 'my_grid_search_exp_name' , job_display_name = 'my_exp' ) NOTE nb_trials specifies how many of the possible permutations to use. If using grid_search it will use the depth first ordering. If using random_search it will use the first k shuffled options. FYI, random search has been shown to be just as good as any Bayesian optimization method when using a reasonable number of samples (60), see this paper for more information .","title":"Running grid search on a cluster"},{"location":"Trainer/SLURM Managed Cluster/#walltime-auto-resubmit","text":"Lightning automatically resubmits jobs when they reach the walltime. Make sure to set the SIGUSR1 signal in your SLURM script. 1 2 # 90 seconds before training ends #SBATCH --signal=SIGUSR1@90 When lightning receives the SIGUSR1 signal it will: 1. save a checkpoint with 'hpc_ckpt' in the name. 2. resubmit the job using the SLURM_JOB_ID When the script starts again, Lightning will: 1. search for a 'hpc_ckpt' checkpoint. 2. restore the model, optimizers, schedulers, epoch, etc...","title":"Walltime auto-resubmit"},{"location":"Trainer/Testing loop/","text":"To ensure you don't accidentally use test data to guide training decisions Lightning makes running the test set deliberate. test You have two options to run the test set. First case is where you test right after a full training routine. 1 2 3 4 5 # run full training trainer . fit ( model ) # run test set trainer . test () Second case is where you load a model and run the test set 1 2 3 4 5 6 7 8 9 10 11 12 model = MyLightningModule . load_from_metrics ( weights_path = '/path/to/pytorch_checkpoint.ckpt' , tags_csv = '/path/to/test_tube/experiment/version/meta_tags.csv' , on_gpu = True , map_location = None ) # init trainer with whatever options trainer = Trainer ( ... ) # test (pass in the model) trainer . test ( model ) In this second case, the options you pass to trainer will be used when running the test set (ie: 16-bit, dp, ddp, etc...)","title":"Testing loop"},{"location":"Trainer/Testing loop/#test","text":"You have two options to run the test set. First case is where you test right after a full training routine. 1 2 3 4 5 # run full training trainer . fit ( model ) # run test set trainer . test () Second case is where you load a model and run the test set 1 2 3 4 5 6 7 8 9 10 11 12 model = MyLightningModule . load_from_metrics ( weights_path = '/path/to/pytorch_checkpoint.ckpt' , tags_csv = '/path/to/test_tube/experiment/version/meta_tags.csv' , on_gpu = True , map_location = None ) # init trainer with whatever options trainer = Trainer ( ... ) # test (pass in the model) trainer . test ( model ) In this second case, the options you pass to trainer will be used when running the test set (ie: 16-bit, dp, ddp, etc...)","title":"test"},{"location":"Trainer/Training Loop/","text":"The lightning training loop handles everything except the actual computations of your model. To decide what will happen in your training loop, define the training_step function . Below are all the things lightning automates for you in the training loop. Accumulated gradients Accumulated gradients runs K small batches of size N before doing a backwards pass. The effect is a large effective batch size of size KxN. 1 2 # DEFAULT (ie: no accumulated grads) trainer = Trainer ( accumulate_grad_batches = 1 ) Force training for min or max epochs It can be useful to force training for a minimum number of epochs or limit to a max number 1 2 # DEFAULT trainer = Trainer ( min_nb_epochs = 1 , max_nb_epochs = 1000 ) Early stopping The trainer already sets up default early stopping for you. To modify this behavior, pass in your own EarlyStopping callback. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from pytorch_lightning.callbacks import EarlyStopping # DEFAULTS used by Trainer early_stop_callback = EarlyStopping ( monitor = 'val_loss' , min_delta = 0.00 , patience = 3 , verbose = False , mode = 'min' ) # without passing anything in, uses the default callback above trainer = Trainer () # pass in your own to override the default callback trainer = Trainer ( early_stop_callback = early_stop_callback ) # pass in None to disable it trainer = Trainer ( early_stop_callback = None ) Force disable early stop To disable early stopping pass None to the early_stop_callback 1 2 # DEFAULT trainer = Trainer ( early_stop_callback = None ) Gradient Clipping Gradient clipping may be enabled to avoid exploding gradients. Specifically, this will clip the gradient norm computed over all model parameters together . 1 2 3 4 5 # DEFAULT (ie: don't clip) trainer = Trainer ( gradient_clip_val = 0 ) # clip gradients with norm above 0.5 trainer = Trainer ( gradient_clip_val = 0.5 ) Inspect gradient norms Looking at grad norms can help you figure out where training might be going wrong. 1 2 3 4 5 # DEFAULT (-1 doesn't track norms) trainer = Trainer ( track_grad_norm =- 1 ) # track the LP norm (P=2 here) trainer = Trainer ( track_grad_norm = 2 ) Set how much of the training set to check If you don't want to check 100% of the training set (for debugging or if it's huge), set this flag. train_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( train_percent_check = 1.0 ) # check 10% only trainer = Trainer ( train_percent_check = 0.1 )","title":"Training Loop"},{"location":"Trainer/Training Loop/#accumulated-gradients","text":"Accumulated gradients runs K small batches of size N before doing a backwards pass. The effect is a large effective batch size of size KxN. 1 2 # DEFAULT (ie: no accumulated grads) trainer = Trainer ( accumulate_grad_batches = 1 )","title":"Accumulated gradients"},{"location":"Trainer/Training Loop/#force-training-for-min-or-max-epochs","text":"It can be useful to force training for a minimum number of epochs or limit to a max number 1 2 # DEFAULT trainer = Trainer ( min_nb_epochs = 1 , max_nb_epochs = 1000 )","title":"Force training for min or max epochs"},{"location":"Trainer/Training Loop/#early-stopping","text":"The trainer already sets up default early stopping for you. To modify this behavior, pass in your own EarlyStopping callback. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from pytorch_lightning.callbacks import EarlyStopping # DEFAULTS used by Trainer early_stop_callback = EarlyStopping ( monitor = 'val_loss' , min_delta = 0.00 , patience = 3 , verbose = False , mode = 'min' ) # without passing anything in, uses the default callback above trainer = Trainer () # pass in your own to override the default callback trainer = Trainer ( early_stop_callback = early_stop_callback ) # pass in None to disable it trainer = Trainer ( early_stop_callback = None )","title":"Early stopping"},{"location":"Trainer/Training Loop/#force-disable-early-stop","text":"To disable early stopping pass None to the early_stop_callback 1 2 # DEFAULT trainer = Trainer ( early_stop_callback = None )","title":"Force disable early stop"},{"location":"Trainer/Training Loop/#gradient-clipping","text":"Gradient clipping may be enabled to avoid exploding gradients. Specifically, this will clip the gradient norm computed over all model parameters together . 1 2 3 4 5 # DEFAULT (ie: don't clip) trainer = Trainer ( gradient_clip_val = 0 ) # clip gradients with norm above 0.5 trainer = Trainer ( gradient_clip_val = 0.5 )","title":"Gradient Clipping"},{"location":"Trainer/Training Loop/#inspect-gradient-norms","text":"Looking at grad norms can help you figure out where training might be going wrong. 1 2 3 4 5 # DEFAULT (-1 doesn't track norms) trainer = Trainer ( track_grad_norm =- 1 ) # track the LP norm (P=2 here) trainer = Trainer ( track_grad_norm = 2 )","title":"Inspect gradient norms"},{"location":"Trainer/Training Loop/#set-how-much-of-the-training-set-to-check","text":"If you don't want to check 100% of the training set (for debugging or if it's huge), set this flag. train_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( train_percent_check = 1.0 ) # check 10% only trainer = Trainer ( train_percent_check = 0.1 )","title":"Set how much of the training set to check"},{"location":"Trainer/Validation loop/","text":"The lightning validation loop handles everything except the actual computations of your model. To decide what will happen in your validation loop, define the validation_step function . Below are all the things lightning automates for you in the validation loop. Note Lightning will run 5 steps of validation in the beginning of training as a sanity check so you don't have to wait until a full epoch to catch possible validation issues. Check validation every n epochs If you have a small dataset you might want to check validation every n epochs 1 2 # DEFAULT trainer = Trainer ( check_val_every_n_epoch = 1 ) Set how much of the validation set to check If you don't want to check 100% of the validation set (for debugging or if it's huge), set this flag val_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( val_percent_check = 1.0 ) # check 10% only trainer = Trainer ( val_percent_check = 0.1 ) Set how much of the test set to check If you don't want to check 100% of the test set (for debugging or if it's huge), set this flag test_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( test_percent_check = 1.0 ) # check 10% only trainer = Trainer ( test_percent_check = 0.1 ) Set validation check frequency within 1 training epoch For large datasets it's often desirable to check validation multiple times within a training loop 1 2 3 4 5 # DEFAULT trainer = Trainer ( val_check_interval = 0.95 ) # check every .25 of an epoch trainer = Trainer ( val_check_interval = 0.25 ) Set the number of validation sanity steps Lightning runs a few steps of validation in the beginning of training. This avoids crashing in the validation loop sometime deep into a lengthy training loop. 1 2 # DEFAULT trainer = Trainer ( nb_sanity_val_steps = 5 ) You can use Trainer(nb_sanity_val_steps=0) to skip the sanity check.","title":"Validation loop"},{"location":"Trainer/Validation loop/#check-validation-every-n-epochs","text":"If you have a small dataset you might want to check validation every n epochs 1 2 # DEFAULT trainer = Trainer ( check_val_every_n_epoch = 1 )","title":"Check validation every n epochs"},{"location":"Trainer/Validation loop/#set-how-much-of-the-validation-set-to-check","text":"If you don't want to check 100% of the validation set (for debugging or if it's huge), set this flag val_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( val_percent_check = 1.0 ) # check 10% only trainer = Trainer ( val_percent_check = 0.1 )","title":"Set how much of the validation set to check"},{"location":"Trainer/Validation loop/#set-how-much-of-the-test-set-to-check","text":"If you don't want to check 100% of the test set (for debugging or if it's huge), set this flag test_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( test_percent_check = 1.0 ) # check 10% only trainer = Trainer ( test_percent_check = 0.1 )","title":"Set how much of the test set to check"},{"location":"Trainer/Validation loop/#set-validation-check-frequency-within-1-training-epoch","text":"For large datasets it's often desirable to check validation multiple times within a training loop 1 2 3 4 5 # DEFAULT trainer = Trainer ( val_check_interval = 0.95 ) # check every .25 of an epoch trainer = Trainer ( val_check_interval = 0.25 )","title":"Set validation check frequency within 1 training epoch"},{"location":"Trainer/Validation loop/#set-the-number-of-validation-sanity-steps","text":"Lightning runs a few steps of validation in the beginning of training. This avoids crashing in the validation loop sometime deep into a lengthy training loop. 1 2 # DEFAULT trainer = Trainer ( nb_sanity_val_steps = 5 ) You can use Trainer(nb_sanity_val_steps=0) to skip the sanity check.","title":"Set the number of validation sanity steps"},{"location":"Trainer/debugging/","text":"These flags are useful to help debug a model. Fast dev run This flag is meant for debugging a full train/val/test loop. It'll activate callbacks, everything but only with 1 training and 1 validation batch. Use this to debug a full run of your program quickly 1 2 # DEFAULT trainer = Trainer ( fast_dev_run = False ) Inspect gradient norms Looking at grad norms can help you figure out where training might be going wrong. 1 2 3 4 5 # DEFAULT (-1 doesn't track norms) trainer = Trainer ( track_grad_norm =- 1 ) # track the LP norm (P=2 here) trainer = Trainer ( track_grad_norm = 2 ) Make model overfit on subset of data A useful debugging trick is to make your model overfit a tiny fraction of the data. setting overfit_pct > 0 will overwrite train_percent_check, val_percent_check, test_percent_check 1 2 3 4 5 # DEFAULT don't overfit (ie: normal training) trainer = Trainer ( overfit_pct = 0.0 ) # overfit on 1% of data trainer = Trainer ( overfit_pct = 0.01 ) Print the parameter count by layer By default lightning prints a list of parameters and submodules when it starts training. 1 2 3 4 5 # DEFAULT print a full list of all submodules and their parameters. trainer = Trainer ( weights_summary = 'full' ) # only print the top-level modules (i.e. the children of LightningModule). trainer = Trainer ( weights_summary = 'top' ) Print which gradients are nan This option prints a list of tensors with nan gradients. 1 2 # DEFAULT trainer = Trainer ( print_nan_grads = False ) Log GPU usage Lightning automatically logs gpu usage to the test tube logs. It'll only do it at the metric logging interval, so it doesn't slow down training.","title":"Debugging"},{"location":"Trainer/debugging/#fast-dev-run","text":"This flag is meant for debugging a full train/val/test loop. It'll activate callbacks, everything but only with 1 training and 1 validation batch. Use this to debug a full run of your program quickly 1 2 # DEFAULT trainer = Trainer ( fast_dev_run = False )","title":"Fast dev run"},{"location":"Trainer/debugging/#inspect-gradient-norms","text":"Looking at grad norms can help you figure out where training might be going wrong. 1 2 3 4 5 # DEFAULT (-1 doesn't track norms) trainer = Trainer ( track_grad_norm =- 1 ) # track the LP norm (P=2 here) trainer = Trainer ( track_grad_norm = 2 )","title":"Inspect gradient norms"},{"location":"Trainer/debugging/#make-model-overfit-on-subset-of-data","text":"A useful debugging trick is to make your model overfit a tiny fraction of the data. setting overfit_pct > 0 will overwrite train_percent_check, val_percent_check, test_percent_check 1 2 3 4 5 # DEFAULT don't overfit (ie: normal training) trainer = Trainer ( overfit_pct = 0.0 ) # overfit on 1% of data trainer = Trainer ( overfit_pct = 0.01 )","title":"Make model overfit on subset of data"},{"location":"Trainer/debugging/#print-the-parameter-count-by-layer","text":"By default lightning prints a list of parameters and submodules when it starts training. 1 2 3 4 5 # DEFAULT print a full list of all submodules and their parameters. trainer = Trainer ( weights_summary = 'full' ) # only print the top-level modules (i.e. the children of LightningModule). trainer = Trainer ( weights_summary = 'top' )","title":"Print the parameter count by layer"},{"location":"Trainer/debugging/#print-which-gradients-are-nan","text":"This option prints a list of tensors with nan gradients. 1 2 # DEFAULT trainer = Trainer ( print_nan_grads = False )","title":"Print which gradients are nan"},{"location":"Trainer/debugging/#log-gpu-usage","text":"Lightning automatically logs gpu usage to the test tube logs. It'll only do it at the metric logging interval, so it doesn't slow down training.","title":"Log GPU usage"},{"location":"Trainer/hooks/","text":"Hooks [ Github Code ] There are cases when you might want to do something different at different parts of the training/validation loop. To enable a hook, simply override the method in your LightningModule and the trainer will call it at the correct time. Contributing If there's a hook you'd like to add, simply: 1. Fork PyTorchLightning. 2. Add the hook here . 3. Add the correct place in the Trainer where it should be called. on_epoch_start Called in the training loop at the very beginning of the epoch. 1 2 def on_epoch_start ( self ): # do something when the epoch starts on_epoch_end Called in the training loop at the very end of the epoch. 1 2 def on_epoch_end ( self ): # do something when the epoch ends on_batch_start Called in the training loop before anything happens for that batch. 1 2 def on_batch_start ( self ): # do something when the batch starts on_batch_end Called in the training loop after the batch. 1 2 def on_batch_end ( self ): # do something when the batch ends on_pre_performance_check Called at the very beginning of the validation loop. 1 2 def on_pre_performance_check ( self ): # do something before validation starts on_post_performance_check Called at the very end of the validation loop. 1 2 def on_post_performance_check ( self ): # do something before validation end optimizer_step Calls .step() and .zero_grad for each optimizer. You can override this method to adjust how you do the optimizer step for each optimizer Called once per optimizer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # DEFAULT def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): optimizer . step () optimizer . zero_grad () # Alternating schedule for optimizer steps (ie: GANs) def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): # update generator opt every 2 steps if optimizer_i == 0 : if batch_nb % 2 == 0 : optimizer . step () optimizer . zero_grad () # update discriminator opt every 4 steps if optimizer_i == 1 : if batch_nb % 4 == 0 : optimizer . step () optimizer . zero_grad () # ... # add as many optimizers as you want This step allows you to do a lot of non-standard training tricks such as learning-rate warm-up: 1 2 3 4 5 6 7 8 9 10 11 # learning rate warm-up def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): # warm up lr if self . trainer . global_step < 500 : lr_scale = min ( 1. , float ( self . trainer . global_step + 1 ) / 500. ) for pg in optimizer . param_groups : pg [ 'lr' ] = lr_scale * self . hparams . learning_rate # update params optimizer . step () optimizer . zero_grad () on_before_zero_grad Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated. Called once per optimizer 1 2 def on_before_zero_grad ( self , optimizer ): # do something with the optimizer or inspect it. on_after_backward Called in the training loop after model.backward() This is the ideal place to inspect or log gradient information 1 2 3 4 5 6 7 8 def on_after_backward ( self ): # example to inspect gradient information in tensorboard if self . trainer . global_step % 25 == 0 : # don't make the tf file huge params = self . state_dict () for k , v in params . items (): grads = v name = k self . logger . experiment . add_histogram ( tag = name , values = grads , global_step = self . trainer . global_step )","title":"Hooks"},{"location":"Trainer/hooks/#hooks","text":"[ Github Code ] There are cases when you might want to do something different at different parts of the training/validation loop. To enable a hook, simply override the method in your LightningModule and the trainer will call it at the correct time. Contributing If there's a hook you'd like to add, simply: 1. Fork PyTorchLightning. 2. Add the hook here . 3. Add the correct place in the Trainer where it should be called.","title":"Hooks"},{"location":"Trainer/hooks/#on_epoch_start","text":"Called in the training loop at the very beginning of the epoch. 1 2 def on_epoch_start ( self ): # do something when the epoch starts","title":"on_epoch_start"},{"location":"Trainer/hooks/#on_epoch_end","text":"Called in the training loop at the very end of the epoch. 1 2 def on_epoch_end ( self ): # do something when the epoch ends","title":"on_epoch_end"},{"location":"Trainer/hooks/#on_batch_start","text":"Called in the training loop before anything happens for that batch. 1 2 def on_batch_start ( self ): # do something when the batch starts","title":"on_batch_start"},{"location":"Trainer/hooks/#on_batch_end","text":"Called in the training loop after the batch. 1 2 def on_batch_end ( self ): # do something when the batch ends","title":"on_batch_end"},{"location":"Trainer/hooks/#on_pre_performance_check","text":"Called at the very beginning of the validation loop. 1 2 def on_pre_performance_check ( self ): # do something before validation starts","title":"on_pre_performance_check"},{"location":"Trainer/hooks/#on_post_performance_check","text":"Called at the very end of the validation loop. 1 2 def on_post_performance_check ( self ): # do something before validation end","title":"on_post_performance_check"},{"location":"Trainer/hooks/#optimizer_step","text":"Calls .step() and .zero_grad for each optimizer. You can override this method to adjust how you do the optimizer step for each optimizer Called once per optimizer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # DEFAULT def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): optimizer . step () optimizer . zero_grad () # Alternating schedule for optimizer steps (ie: GANs) def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): # update generator opt every 2 steps if optimizer_i == 0 : if batch_nb % 2 == 0 : optimizer . step () optimizer . zero_grad () # update discriminator opt every 4 steps if optimizer_i == 1 : if batch_nb % 4 == 0 : optimizer . step () optimizer . zero_grad () # ... # add as many optimizers as you want This step allows you to do a lot of non-standard training tricks such as learning-rate warm-up: 1 2 3 4 5 6 7 8 9 10 11 # learning rate warm-up def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): # warm up lr if self . trainer . global_step < 500 : lr_scale = min ( 1. , float ( self . trainer . global_step + 1 ) / 500. ) for pg in optimizer . param_groups : pg [ 'lr' ] = lr_scale * self . hparams . learning_rate # update params optimizer . step () optimizer . zero_grad ()","title":"optimizer_step"},{"location":"Trainer/hooks/#on_before_zero_grad","text":"Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated. Called once per optimizer 1 2 def on_before_zero_grad ( self , optimizer ): # do something with the optimizer or inspect it.","title":"on_before_zero_grad"},{"location":"Trainer/hooks/#on_after_backward","text":"Called in the training loop after model.backward() This is the ideal place to inspect or log gradient information 1 2 3 4 5 6 7 8 def on_after_backward ( self ): # example to inspect gradient information in tensorboard if self . trainer . global_step % 25 == 0 : # don't make the tf file huge params = self . state_dict () for k , v in params . items (): grads = v name = k self . logger . experiment . add_histogram ( tag = name , values = grads , global_step = self . trainer . global_step )","title":"on_after_backward"},{"location":"examples/Examples/","text":"Template model definition In 99% of cases you want to just copy one of the examples to start a new lightningModule and change the core of what your model is actually trying to do. 1 2 # get a copy of the module template wget https://raw.githubusercontent.com/williamFalcon/pytorch-lightning/master/examples/new_project_templates/lightning_module_template.py Trainer Example __main__ function Normally, we want to let the __main__ function start the training. Inside the main we parse training arguments with whatever hyperparameters we want. Your LightningModule will have a chance to add hyperparameters. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from test_tube import HyperOptArgumentParser if __name__ == '__main__' : # use default args given by lightning root_dir = os . path . split ( os . path . dirname ( sys . modules [ '__main__' ] . __file__ ))[ 0 ] parent_parser = HyperOptArgumentParser ( strategy = 'random_search' , add_help = False ) add_default_args ( parent_parser , root_dir ) # allow model to overwrite or extend args parser = ExampleModel . add_model_specific_args ( parent_parser ) hyperparams = parser . parse_args () # train model main ( hyperparams ) Main Function The main function is your entry into the program. This is where you init your model, checkpoint directory, and launch the training. The main function should have 3 arguments: - hparams: a configuration of hyperparameters. - slurm_manager: Slurm cluster manager object (can be None) - dict: for you to return any values you want (useful in meta-learning, otherwise set to _) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def main ( hparams , cluster , results_dict ): \"\"\" Main training routine specific for this project :param hparams: :return: \"\"\" # build model model = MyLightningModule ( hparams ) # configure trainer trainer = Trainer () # train model trainer . fit ( model ) The main function will start training on your main function. If you use the HyperParameterOptimizer in hyper parameter optimization mode, this main function will get one set of hyperparameters. If you use it as a simple argument parser you get the default arguments in the argument parser. So, calling main(hyperparams) runs the model with the default argparse arguments. 1 main ( hyperparams ) CPU hyperparameter search 1 2 3 4 5 6 # run a grid search over 20 hyperparameter combinations. hyperparams . optimize_parallel_cpu ( main_local , nb_trials = 20 , nb_workers = 1 ) Hyperparameter search on a single or multiple GPUs 1 2 3 4 5 6 7 # run a grid search over 20 hyperparameter combinations. hyperparams . optimize_parallel_gpu ( main_local , nb_trials = 20 , nb_workers = 1 , gpus = [ 0 , 1 , 2 , 3 ] ) Hyperparameter search on a SLURM HPC cluster 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def optimize_on_cluster ( hyperparams ): # enable cluster training cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = hyperparams . tt_save_path , test_tube_exp_name = hyperparams . tt_name ) # email for cluster coms cluster . notify_job_status ( email = 'add_email_here' , on_done = True , on_fail = True ) # configure cluster cluster . per_experiment_nb_gpus = hyperparams . per_experiment_nb_gpus cluster . job_time = '48:00:00' cluster . gpu_type = '1080ti' cluster . memory_mb_per_node = 48000 # any modules for code to run in env cluster . add_command ( 'source activate pytorch_lightning' ) # name of exp job_display_name = hyperparams . tt_name . split ( '_' )[ 0 ] job_display_name = job_display_name [ 0 : 3 ] # run hopt print ( 'submitting jobs...' ) cluster . optimize_parallel_cluster_gpu ( main , nb_trials = hyperparams . nb_hopt_trials , job_name = job_display_name ) # run cluster hyperparameter search optimize_on_cluster ( hyperparams )","title":"Examples"},{"location":"examples/Examples/#template-model-definition","text":"In 99% of cases you want to just copy one of the examples to start a new lightningModule and change the core of what your model is actually trying to do. 1 2 # get a copy of the module template wget https://raw.githubusercontent.com/williamFalcon/pytorch-lightning/master/examples/new_project_templates/lightning_module_template.py","title":"Template model definition"},{"location":"examples/Examples/#trainer-example","text":"__main__ function Normally, we want to let the __main__ function start the training. Inside the main we parse training arguments with whatever hyperparameters we want. Your LightningModule will have a chance to add hyperparameters. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from test_tube import HyperOptArgumentParser if __name__ == '__main__' : # use default args given by lightning root_dir = os . path . split ( os . path . dirname ( sys . modules [ '__main__' ] . __file__ ))[ 0 ] parent_parser = HyperOptArgumentParser ( strategy = 'random_search' , add_help = False ) add_default_args ( parent_parser , root_dir ) # allow model to overwrite or extend args parser = ExampleModel . add_model_specific_args ( parent_parser ) hyperparams = parser . parse_args () # train model main ( hyperparams ) Main Function The main function is your entry into the program. This is where you init your model, checkpoint directory, and launch the training. The main function should have 3 arguments: - hparams: a configuration of hyperparameters. - slurm_manager: Slurm cluster manager object (can be None) - dict: for you to return any values you want (useful in meta-learning, otherwise set to _) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def main ( hparams , cluster , results_dict ): \"\"\" Main training routine specific for this project :param hparams: :return: \"\"\" # build model model = MyLightningModule ( hparams ) # configure trainer trainer = Trainer () # train model trainer . fit ( model ) The main function will start training on your main function. If you use the HyperParameterOptimizer in hyper parameter optimization mode, this main function will get one set of hyperparameters. If you use it as a simple argument parser you get the default arguments in the argument parser. So, calling main(hyperparams) runs the model with the default argparse arguments. 1 main ( hyperparams )","title":"Trainer Example"},{"location":"examples/Examples/#cpu-hyperparameter-search","text":"1 2 3 4 5 6 # run a grid search over 20 hyperparameter combinations. hyperparams . optimize_parallel_cpu ( main_local , nb_trials = 20 , nb_workers = 1 )","title":"CPU hyperparameter search"},{"location":"examples/Examples/#hyperparameter-search-on-a-single-or-multiple-gpus","text":"1 2 3 4 5 6 7 # run a grid search over 20 hyperparameter combinations. hyperparams . optimize_parallel_gpu ( main_local , nb_trials = 20 , nb_workers = 1 , gpus = [ 0 , 1 , 2 , 3 ] )","title":"Hyperparameter search on a single or multiple GPUs"},{"location":"examples/Examples/#hyperparameter-search-on-a-slurm-hpc-cluster","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def optimize_on_cluster ( hyperparams ): # enable cluster training cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = hyperparams . tt_save_path , test_tube_exp_name = hyperparams . tt_name ) # email for cluster coms cluster . notify_job_status ( email = 'add_email_here' , on_done = True , on_fail = True ) # configure cluster cluster . per_experiment_nb_gpus = hyperparams . per_experiment_nb_gpus cluster . job_time = '48:00:00' cluster . gpu_type = '1080ti' cluster . memory_mb_per_node = 48000 # any modules for code to run in env cluster . add_command ( 'source activate pytorch_lightning' ) # name of exp job_display_name = hyperparams . tt_name . split ( '_' )[ 0 ] job_display_name = job_display_name [ 0 : 3 ] # run hopt print ( 'submitting jobs...' ) cluster . optimize_parallel_cluster_gpu ( main , nb_trials = hyperparams . nb_hopt_trials , job_name = job_display_name ) # run cluster hyperparameter search optimize_on_cluster ( hyperparams )","title":"Hyperparameter search on a SLURM HPC cluster"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"New project Quick Start To start a new project define two files, a LightningModule and a Trainer file. To illustrate Lightning power and simplicity, here's an example of a typical research flow. Case 1: BERT Let's say you're working on something like BERT but want to try different ways of training or even different networks. You would define a single LightningModule and use flags to switch between your different ideas. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class BERT ( pl . LightningModule ): def __init__ ( self , model_name , task ): self . task = task if model_name == 'transformer' : self . net = Transformer () elif model_name == 'my_cool_version' : self . net = MyCoolVersion () def training_step ( self , batch , batch_nb ): if self . task == 'standard_bert' : # do standard bert training with self.net... # return loss if self . task == 'my_cool_task' : # do my own version with self.net # return loss Case 2: COOLER NOT BERT But if you wanted to try something completely different, you'd define a new module for that. 1 2 3 4 5 6 7 class CoolerNotBERT ( pl . LightningModule ): def __init__ ( self ): self . net = ... def training_step ( self , batch , batch_nb ): # do some other cool task # return loss Rapid research flow Then you could do rapid research by switching between these two and using the same trainer. 1 2 3 4 5 6 7 if use_bert : model = BERT () else : model = CoolerNotBERT () trainer = Trainer ( gpus = 4 , use_amp = True ) trainer . fit ( model ) Notice a few things about this flow: 1. You're writing pure PyTorch... no unnecessary abstractions or new libraries to learn. 2. You get free GPU and 16-bit support without writing any of that code in your model. 3. You also get all of the capabilities below (without coding or testing yourself). Templates MNIST LightningModule Trainer Basic CPU, GPU Trainer Template GPU cluster Trainer Template Docs shortcuts LightningModule Trainer Quick start examples CPU example Hyperparameter search on single GPU Hyperparameter search on multiple GPUs on same node Hyperparameter search on a SLURM HPC cluster Checkpointing Checkpoint callback Model saving Model loading Restoring training session Computing cluster (SLURM) Running grid search on a cluster Walltime auto-resubmit Debugging Fast dev run Inspect gradient norms Log GPU usage Make model overfit on subset of data Print the parameter count by layer Pring which gradients are nan Print input and output size of every module in system Distributed training Implement Your Own Distributed (DDP) training 16-bit mixed precision Multi-GPU Multi-node Single GPU Self-balancing architecture Experiment Logging Display metrics in progress bar Log metric row every k batches Process position Tensorboard support Save a snapshot of all hyperparameters Snapshot code for a training run Write logs file to csv every k batches Training loop Accumulate gradients Force training for min or max epochs Early stopping callback Force disable early stop Gradient Clipping Hooks Learning rate scheduling Use multiple optimizers (like GANs) Set how much of the training set to check (1-100%) Step optimizers at arbitrary intervals Validation loop Check validation every n epochs Hooks Set how much of the validation set to check Set how much of the test set to check Set validation check frequency within 1 training epoch Set the number of validation sanity steps Testing loop Run test set","title":"Home"},{"location":"#new-project-quick-start","text":"To start a new project define two files, a LightningModule and a Trainer file. To illustrate Lightning power and simplicity, here's an example of a typical research flow.","title":"New project Quick Start"},{"location":"#case-1-bert","text":"Let's say you're working on something like BERT but want to try different ways of training or even different networks. You would define a single LightningModule and use flags to switch between your different ideas. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class BERT ( pl . LightningModule ): def __init__ ( self , model_name , task ): self . task = task if model_name == 'transformer' : self . net = Transformer () elif model_name == 'my_cool_version' : self . net = MyCoolVersion () def training_step ( self , batch , batch_nb ): if self . task == 'standard_bert' : # do standard bert training with self.net... # return loss if self . task == 'my_cool_task' : # do my own version with self.net # return loss","title":"Case 1: BERT"},{"location":"#case-2-cooler-not-bert","text":"But if you wanted to try something completely different, you'd define a new module for that. 1 2 3 4 5 6 7 class CoolerNotBERT ( pl . LightningModule ): def __init__ ( self ): self . net = ... def training_step ( self , batch , batch_nb ): # do some other cool task # return loss","title":"Case 2: COOLER NOT BERT"},{"location":"#rapid-research-flow","text":"Then you could do rapid research by switching between these two and using the same trainer. 1 2 3 4 5 6 7 if use_bert : model = BERT () else : model = CoolerNotBERT () trainer = Trainer ( gpus = 4 , use_amp = True ) trainer . fit ( model ) Notice a few things about this flow: 1. You're writing pure PyTorch... no unnecessary abstractions or new libraries to learn. 2. You get free GPU and 16-bit support without writing any of that code in your model. 3. You also get all of the capabilities below (without coding or testing yourself).","title":"Rapid research flow"},{"location":"#templates","text":"MNIST LightningModule Trainer Basic CPU, GPU Trainer Template GPU cluster Trainer Template","title":"Templates"},{"location":"#docs-shortcuts","text":"LightningModule Trainer","title":"Docs shortcuts"},{"location":"#quick-start-examples","text":"CPU example Hyperparameter search on single GPU Hyperparameter search on multiple GPUs on same node Hyperparameter search on a SLURM HPC cluster","title":"Quick start examples"},{"location":"#checkpointing","text":"Checkpoint callback Model saving Model loading Restoring training session","title":"Checkpointing"},{"location":"#computing-cluster-slurm","text":"Running grid search on a cluster Walltime auto-resubmit","title":"Computing cluster (SLURM)"},{"location":"#debugging","text":"Fast dev run Inspect gradient norms Log GPU usage Make model overfit on subset of data Print the parameter count by layer Pring which gradients are nan Print input and output size of every module in system","title":"Debugging"},{"location":"#distributed-training","text":"Implement Your Own Distributed (DDP) training 16-bit mixed precision Multi-GPU Multi-node Single GPU Self-balancing architecture","title":"Distributed training"},{"location":"#experiment-logging","text":"Display metrics in progress bar Log metric row every k batches Process position Tensorboard support Save a snapshot of all hyperparameters Snapshot code for a training run Write logs file to csv every k batches","title":"Experiment Logging"},{"location":"#training-loop","text":"Accumulate gradients Force training for min or max epochs Early stopping callback Force disable early stop Gradient Clipping Hooks Learning rate scheduling Use multiple optimizers (like GANs) Set how much of the training set to check (1-100%) Step optimizers at arbitrary intervals","title":"Training loop"},{"location":"#validation-loop","text":"Check validation every n epochs Hooks Set how much of the validation set to check Set how much of the test set to check Set validation check frequency within 1 training epoch Set the number of validation sanity steps","title":"Validation loop"},{"location":"#testing-loop","text":"Run test set","title":"Testing loop"},{"location":"LightningModule/RequiredTrainerInterface/","text":"Lightning Module interface [ Github Code ] A lightning module is a strict superclass of nn.Module, it provides a standard interface for the trainer to interact with the model. The easiest thing to do is copy the minimal example below and modify accordingly. Otherwise, to Define a Lightning Module, implement the following methods: Required : training_step train_dataloader configure_optimizers Optional : training_end validation_step validation_end test_step test_end val_dataloader test_dataloader on_save_checkpoint on_load_checkpoint add_model_specific_args Minimal example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 import os import torch from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision.datasets import MNIST import torchvision.transforms as transforms import pytorch_lightning as pl class CoolModel ( pl . LightningModule ): def __init__ ( self ): super ( CoolModel , self ) . __init__ () # not the best model... self . l1 = torch . nn . Linear ( 28 * 28 , 10 ) def forward ( self , x ): return torch . relu ( self . l1 ( x . view ( x . size ( 0 ), - 1 ))) def training_step ( self , batch , batch_nb ): # REQUIRED x , y = batch y_hat = self . forward ( x ) return { 'loss' : F . cross_entropy ( y_hat , y )} def validation_step ( self , batch , batch_nb ): # OPTIONAL x , y = batch y_hat = self . forward ( x ) return { 'val_loss' : F . cross_entropy ( y_hat , y )} def validation_end ( self , outputs ): # OPTIONAL avg_loss = torch . stack ([ x [ 'val_loss' ] for x in outputs ]) . mean () return { 'avg_val_loss' : avg_loss } def test_step ( self , batch , batch_nb ): # OPTIONAL x , y = batch y_hat = self . forward ( x ) return { 'test_loss' : F . cross_entropy ( y_hat , y )} def test_end ( self , outputs ): # OPTIONAL avg_loss = torch . stack ([ x [ 'test_loss' ] for x in outputs ]) . mean () return { 'avg_test_loss' : avg_loss } def configure_optimizers ( self ): # REQUIRED return torch . optim . Adam ( self . parameters (), lr = 0.02 ) @pl.data_loader def train_dataloader ( self ): return DataLoader ( MNIST ( os . getcwd (), train = True , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) @pl.data_loader def val_dataloader ( self ): # OPTIONAL # can also return a list of val dataloaders return DataLoader ( MNIST ( os . getcwd (), train = True , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) @pl.data_loader def test_dataloader ( self ): # OPTIONAL # can also return a list of test dataloaders return DataLoader ( MNIST ( os . getcwd (), train = False , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) How do these methods fit into the broader training? The LightningModule interface is on the right. Each method corresponds to a part of a research project. Lightning automates everything not in blue. Required Methods training_step 1 def training_step ( self , batch , batch_nb ) In this step you'd normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something specific to your model. Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is Return Dictionary or OrderedDict key value is required loss tensor scalar Y progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 def training_step ( self , batch , batch_nb ): x , y , z = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , x ) logger_logs = { 'training_loss' : loss } # optional (MUST ALL BE TENSORS) # if using TestTubeLogger or TensorboardLogger you can nest scalars logger_logs = { 'losses' : logger_logs } # optional (MUST ALL BE TENSORS) output = { 'loss' : loss , # required 'progress_bar' : { 'training_loss' : loss }, # optional (MUST ALL BE TENSORS) 'log' : logger_logs } # return a dict return output If you define multiple optimizers, this step will also be called with an additional optimizer_idx param. 1 2 3 4 5 6 # Multiple optimizers (ie: GANs) def training_step ( self , batch , batch_nb , optimizer_idx ): if optimizer_idx == 0 : # do training_step with encoder if optimizer_idx == 1 : # do training_step with decoder If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step. 1 2 3 # Truncated back-propagation through time def training_step ( self , batch , batch_nb , hiddens ): # hiddens are the hiddens from the previous truncated backprop step You can also return a -1 instead of a dict to stop the current loop. This is useful if you want to break out of the current training epoch early. training_end 1 def training_end ( self , train_step_outputs ) In certain cases (dp, ddp2), you might want to use all outputs of every process to do something. For instance, if using negative samples, you could run a batch via dp and use ALL the outputs for a single softmax across the full batch (ie: the denominator would use the full batch). In this case you should define training_end to perform those calculations. Params Param description outputs What you return in training_step. Return Dictionary or OrderedDict key value is required loss tensor scalar Y progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 # WITHOUT training_end # if used in DP or DDP2, this batch is 1/nb_gpus large def training_step ( self , batch , batch_nb ): # batch is 1/nb_gpus big x , y = batch out = self . forward ( x ) loss = self . softmax ( out ) loss = nce_loss ( loss ) return { 'loss' : loss } # -------------- # with training_end to do softmax over the full batch def training_step ( self , batch , batch_nb ): # batch is 1/nb_gpus big x , y = batch out = self . forward ( x ) return { 'out' : out } def training_end ( self , outputs ): # this out is now the full size of the batch out = outputs [ 'out' ] # this softmax now uses the full batch size loss = self . softmax ( out ) loss = nce_loss ( loss ) return { 'loss' : loss } If you define multiple optimizers, this step will also be called with an additional optimizer_idx param. 1 2 3 4 5 6 # Multiple optimizers (ie: GANs) def training_step ( self , batch , batch_nb , optimizer_idx ): if optimizer_idx == 0 : # do training_step with encoder if optimizer_idx == 1 : # do training_step with decoder If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step. 1 2 3 # Truncated back-propagation through time def training_step ( self , batch , batch_nb , hiddens ): # hiddens are the hiddens from the previous truncated backprop step You can also return a -1 instead of a dict to stop the current loop. This is useful if you want to break out of the current training epoch early. train_dataloader 1 2 @pl.data_loader def train_dataloader ( self ) Called by lightning during training loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator. Return PyTorch DataLoader Example 1 2 3 4 5 6 7 8 9 10 @pl.data_loader def train_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = True , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader configure_optimizers 1 def configure_optimizers ( self ) Set up as many optimizers and (optionally) learning rate schedulers as you need. Normally you'd need one. But in the case of GANs or something more esoteric you might have multiple. Lightning will call .backward() and .step() on each one in every epoch. If you use 16 bit precision it will also handle that. Note: If you use multiple optimizers, training_step will have an additional optimizer_idx parameter. Note 2: If you use LBFGS lightning handles the closure function automatically for you. Return Return any of these 3 options: Single optimizer List or Tuple - List of optimizers Two lists - The first list has multiple optimizers, the second a list of learning-rate schedulers Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # most cases def configure_optimizers ( self ): opt = Adam ( self . parameters (), lr = 0.01 ) return opt # multiple optimizer case (eg: GAN) def configure_optimizers ( self ): generator_opt = Adam ( self . model_gen . parameters (), lr = 0.01 ) disriminator_opt = Adam ( self . model_disc . parameters (), lr = 0.02 ) return generator_opt , disriminator_opt # example with learning_rate schedulers def configure_optimizers ( self ): generator_opt = Adam ( self . model_gen . parameters (), lr = 0.01 ) disriminator_opt = Adam ( self . model_disc . parameters (), lr = 0.02 ) discriminator_sched = CosineAnnealing ( discriminator_opt , T_max = 10 ) return [ generator_opt , disriminator_opt ], [ discriminator_sched ] If you need to control how often those optimizers step or override the default .step() schedule, override the optimizer_step hook. Optional Methods validation_step 1 2 3 4 5 # if you have one val dataloader: def validation_step ( self , batch , batch_nb ) # if you have multiple val dataloaders: def validation_step ( self , batch , batch_nb , dataloader_idxdx ) OPTIONAL If you don't need to validate you don't need to implement this method. In this step you'd normally generate examples or calculate anything of interest such as accuracy. When the validation_step is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, model goes back to training mode and gradients are enabled. The dict you return here will be available in the validation_end method. Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is dataloader_idx Integer displaying which dataloader this is (only if multiple val datasets used) Return Return description optional dict Dict or OrderedDict - passed to the validation_end step N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 # CASE 1: A single validation dataset def validation_step ( self , batch , batch_nb ): x , y = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , y ) # log 6 example images # or generated text... or whatever sample_imgs = x [: 6 ] grid = torchvision . utils . make_grid ( sample_imgs ) self . logger . experiment . add_image ( 'example_images' , grid , 0 ) # calculate acc labels_hat = torch . argmax ( out , dim = 1 ) val_acc = torch . sum ( y == labels_hat ) . item () / ( len ( y ) * 1.0 ) # all optional... # return whatever you need for the collation function validation_end output = OrderedDict ({ 'val_loss' : loss_val , 'val_acc' : torch . tensor ( val_acc ), # everything must be a tensor }) # return an optional dict return output If you pass in multiple validation datasets, validation_step will have an additional argument. 1 2 3 # CASE 2: multiple validation datasets def validation_step ( self , batch , batch_nb , dataset_idx ): # dataset_idx tells you which dataset this is. The dataset_idx corresponds to the order of datasets returned in val_dataloader . validation_end 1 def validation_end ( self , outputs ) If you didn't define a validation_step, this won't be called. Called at the end of the validation loop with the outputs of validation_step. The outputs here are strictly for the progress bar. If you don't need to display anything, don't return anything. Any keys present in 'log', 'progress_bar' or the rest of the dictionary are available for callbacks to access. Params Param description outputs List of outputs you defined in validation_step, or if there are multiple dataloaders, a list containing a list of outputs for each dataloader Return Dictionary or OrderedDict key value is required progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example With a single dataloader 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def validation_end ( self , outputs ): \"\"\" Called at the end of validation to aggregate outputs :param outputs: list of individual outputs of each validation step :return: \"\"\" val_loss_mean = 0 val_acc_mean = 0 for output in outputs : val_loss_mean += output [ 'val_loss' ] val_acc_mean += output [ 'val_acc' ] val_loss_mean /= len ( outputs ) val_acc_mean /= len ( outputs ) tqdm_dict = { 'val_loss' : val_loss_mean . item (), 'val_acc' : val_acc_mean . item ()} # show val_loss and val_acc in progress bar but only log val_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'val_loss' : val_loss_mean . item ()} } return results With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def validation_end ( self , outputs ): \"\"\" Called at the end of validation to aggregate outputs :param outputs: list of list of individual outputs of each validation step :return: \"\"\" val_loss_mean = 0 val_acc_mean = 0 i = 0 for dataloader_outputs in outputs : for output in dataloader_outputs : val_loss_mean += output [ 'val_loss' ] val_acc_mean += output [ 'val_acc' ] i += 1 val_loss_mean /= i val_acc_mean /= i tqdm_dict = { 'val_loss' : val_loss_mean . item (), 'val_acc' : val_acc_mean . item ()} # show val_loss and val_acc in progress bar but only log val_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'val_loss' : val_loss_mean . item ()} } return results test_step 1 2 3 4 5 # if you have one test dataloader: def test_step ( self , batch , batch_nb ) # if you have multiple test dataloaders: def test_step ( self , batch , batch_nb , dataloader_idxdx ) OPTIONAL If you don't need to test you don't need to implement this method. In this step you'd normally generate examples or calculate anything of interest such as accuracy. When the validation_step is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, model goes back to training mode and gradients are enabled. The dict you return here will be available in the test_end method. This function is used when you execute trainer.test() . Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is dataloader_idx Integer displaying which dataloader this is (only if multiple test datasets used) Return Return description optional dict Dict or OrderedDict with metrics to display in progress bar. All keys must be tensors. Y Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # CASE 1: A single test dataset def test_step ( self , batch , batch_nb ): x , y = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , y ) # calculate acc labels_hat = torch . argmax ( out , dim = 1 ) test_acc = torch . sum ( y == labels_hat ) . item () / ( len ( y ) * 1.0 ) # all optional... # return whatever you need for the collation function test_end output = OrderedDict ({ 'test_loss' : loss_test , 'test_acc' : torch . tensor ( test_acc ), # everything must be a tensor }) # return an optional dict return output If you pass in multiple test datasets, test_step will have an additional argument. 1 2 3 # CASE 2: multiple test datasets def test_step ( self , batch , batch_nb , dataset_idx ): # dataset_idx tells you which dataset this is. The dataset_idx corresponds to the order of datasets returned in test_dataloader . test_end 1 def test_end ( self , outputs ) If you didn't define a test_step, this won't be called. Called at the end of the test step with the output of each test_step. The outputs here are strictly for the progress bar. If you don't need to display anything, don't return anything. Params Param description outputs List of outputs you defined in test_step, or if there are multiple dataloaders, a list containing a list of outputs for each dataloader Return Return description optional dict Dict of OrderedDict with metrics to display in progress bar Y Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def test_end ( self , outputs ): \"\"\" Called at the end of test to aggregate outputs :param outputs: list of individual outputs of each test step :return: \"\"\" test_loss_mean = 0 test_acc_mean = 0 for output in outputs : test_loss_mean += output [ 'test_loss' ] test_acc_mean += output [ 'test_acc' ] test_loss_mean /= len ( outputs ) test_acc_mean /= len ( outputs ) tqdm_dict = { 'test_loss' : test_loss_mean . item (), 'test_acc' : test_acc_mean . item ()} # show test_loss and test_acc in progress bar but only log test_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'test_loss' : val_loss_mean . item ()} } return results With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def test_end ( self , outputs ): \"\"\" Called at the end of test to aggregate outputs :param outputs: list of individual outputs of each test step :return: \"\"\" test_loss_mean = 0 test_acc_mean = 0 i = 0 for dataloader_outputs in outputs : for output in dataloader_outputs : test_loss_mean += output [ 'test_loss' ] test_acc_mean += output [ 'test_acc' ] i += 1 test_loss_mean /= i test_acc_mean /= i tqdm_dict = { 'test_loss' : test_loss_mean . item (), 'test_acc' : test_acc_mean . item ()} # show test_loss and test_acc in progress bar but only log test_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'test_loss' : val_loss_mean . item ()} } return results on_save_checkpoint 1 def on_save_checkpoint ( self , checkpoint ) Called by lightning to checkpoint your model. Lightning saves the training state (current epoch, global_step, etc) and also saves the model state_dict. If you want to save anything else, use this method to add your own key-value pair. Return Nothing Example 1 2 3 def on_save_checkpoint ( self , checkpoint ): # 99% of use cases you don't need to implement this method checkpoint [ 'something_cool_i_want_to_save' ] = my_cool_pickable_object on_load_checkpoint 1 def on_load_checkpoint ( self , checkpoint ) Called by lightning to restore your model. Lighting auto-restores global step, epoch, etc... It also restores the model state_dict. If you saved something with on_save_checkpoint this is your chance to restore this. Return Nothing Example 1 2 3 def on_load_checkpoint ( self , checkpoint ): # 99% of the time you don't need to implement this method self . something_cool_i_want_to_save = checkpoint [ 'something_cool_i_want_to_save' ] val_dataloader 1 2 @pl.data_loader def val_dataloader ( self ) OPTIONAL If you don't need a validation dataset and a validation_step, you don't need to implement this method. Called by lightning during validation loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator. Return PyTorch DataLoader or list of PyTorch Dataloaders. Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @pl.data_loader def val_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = False , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader # can also return multiple dataloaders @pl.data_loader def val_dataloader ( self ): return [ loader_a , loader_b , ... , loader_n ] In the case where you return multiple val_dataloaders, the validation_step will have an arguement dataset_idx which matches the order here. test_dataloader 1 2 @pl.data_loader def test_dataloader ( self ) OPTIONAL If you don't need a test dataset and a test_step, you don't need to implement this method. Called by lightning during test loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator. Return PyTorch DataLoader Example 1 2 3 4 5 6 7 8 9 10 11 @pl.data_loader def test_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = False , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader add_model_specific_args 1 2 @staticmethod def add_model_specific_args ( parent_parser , root_dir ) Lightning has a list of default argparse commands. This method is your chance to add or modify commands specific to your model. The hyperparameter argument parser is available anywhere in your model by calling self.hparams. Return An argument parser Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @staticmethod def add_model_specific_args ( parent_parser , root_dir ): parser = HyperOptArgumentParser ( strategy = parent_parser . strategy , parents = [ parent_parser ]) # param overwrites # parser.set_defaults(gradient_clip_val=5.0) # network params parser . opt_list ( '--drop_prob' , default = 0.2 , options = [ 0.2 , 0.5 ], type = float , tunable = False ) parser . add_argument ( '--in_features' , default = 28 * 28 ) parser . add_argument ( '--out_features' , default = 10 ) parser . add_argument ( '--hidden_dim' , default = 50000 ) # use 500 for CPU, 50000 for GPU to see speed difference # data parser . add_argument ( '--data_root' , default = os . path . join ( root_dir , 'mnist' ), type = str ) # training params (opt) parser . opt_list ( '--learning_rate' , default = 0.001 , type = float , options = [ 0.0001 , 0.0005 , 0.001 , 0.005 ], tunable = False ) parser . opt_list ( '--batch_size' , default = 256 , type = int , options = [ 32 , 64 , 128 , 256 ], tunable = False ) parser . opt_list ( '--optimizer_name' , default = 'adam' , type = str , options = [ 'adam' ], tunable = False ) return parser","title":"Lightning Module interface"},{"location":"LightningModule/RequiredTrainerInterface/#lightning-module-interface","text":"[ Github Code ] A lightning module is a strict superclass of nn.Module, it provides a standard interface for the trainer to interact with the model. The easiest thing to do is copy the minimal example below and modify accordingly. Otherwise, to Define a Lightning Module, implement the following methods: Required : training_step train_dataloader configure_optimizers Optional : training_end validation_step validation_end test_step test_end val_dataloader test_dataloader on_save_checkpoint on_load_checkpoint add_model_specific_args","title":"Lightning Module interface"},{"location":"LightningModule/RequiredTrainerInterface/#minimal-example","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 import os import torch from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision.datasets import MNIST import torchvision.transforms as transforms import pytorch_lightning as pl class CoolModel ( pl . LightningModule ): def __init__ ( self ): super ( CoolModel , self ) . __init__ () # not the best model... self . l1 = torch . nn . Linear ( 28 * 28 , 10 ) def forward ( self , x ): return torch . relu ( self . l1 ( x . view ( x . size ( 0 ), - 1 ))) def training_step ( self , batch , batch_nb ): # REQUIRED x , y = batch y_hat = self . forward ( x ) return { 'loss' : F . cross_entropy ( y_hat , y )} def validation_step ( self , batch , batch_nb ): # OPTIONAL x , y = batch y_hat = self . forward ( x ) return { 'val_loss' : F . cross_entropy ( y_hat , y )} def validation_end ( self , outputs ): # OPTIONAL avg_loss = torch . stack ([ x [ 'val_loss' ] for x in outputs ]) . mean () return { 'avg_val_loss' : avg_loss } def test_step ( self , batch , batch_nb ): # OPTIONAL x , y = batch y_hat = self . forward ( x ) return { 'test_loss' : F . cross_entropy ( y_hat , y )} def test_end ( self , outputs ): # OPTIONAL avg_loss = torch . stack ([ x [ 'test_loss' ] for x in outputs ]) . mean () return { 'avg_test_loss' : avg_loss } def configure_optimizers ( self ): # REQUIRED return torch . optim . Adam ( self . parameters (), lr = 0.02 ) @pl.data_loader def train_dataloader ( self ): return DataLoader ( MNIST ( os . getcwd (), train = True , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) @pl.data_loader def val_dataloader ( self ): # OPTIONAL # can also return a list of val dataloaders return DataLoader ( MNIST ( os . getcwd (), train = True , download = True , transform = transforms . ToTensor ()), batch_size = 32 ) @pl.data_loader def test_dataloader ( self ): # OPTIONAL # can also return a list of test dataloaders return DataLoader ( MNIST ( os . getcwd (), train = False , download = True , transform = transforms . ToTensor ()), batch_size = 32 )","title":"Minimal example"},{"location":"LightningModule/RequiredTrainerInterface/#how-do-these-methods-fit-into-the-broader-training","text":"The LightningModule interface is on the right. Each method corresponds to a part of a research project. Lightning automates everything not in blue.","title":"How do these methods fit into the broader training?"},{"location":"LightningModule/RequiredTrainerInterface/#required-methods","text":"","title":"Required Methods"},{"location":"LightningModule/RequiredTrainerInterface/#training_step","text":"1 def training_step ( self , batch , batch_nb ) In this step you'd normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something specific to your model. Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is Return Dictionary or OrderedDict key value is required loss tensor scalar Y progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 def training_step ( self , batch , batch_nb ): x , y , z = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , x ) logger_logs = { 'training_loss' : loss } # optional (MUST ALL BE TENSORS) # if using TestTubeLogger or TensorboardLogger you can nest scalars logger_logs = { 'losses' : logger_logs } # optional (MUST ALL BE TENSORS) output = { 'loss' : loss , # required 'progress_bar' : { 'training_loss' : loss }, # optional (MUST ALL BE TENSORS) 'log' : logger_logs } # return a dict return output If you define multiple optimizers, this step will also be called with an additional optimizer_idx param. 1 2 3 4 5 6 # Multiple optimizers (ie: GANs) def training_step ( self , batch , batch_nb , optimizer_idx ): if optimizer_idx == 0 : # do training_step with encoder if optimizer_idx == 1 : # do training_step with decoder If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step. 1 2 3 # Truncated back-propagation through time def training_step ( self , batch , batch_nb , hiddens ): # hiddens are the hiddens from the previous truncated backprop step You can also return a -1 instead of a dict to stop the current loop. This is useful if you want to break out of the current training epoch early.","title":"training_step"},{"location":"LightningModule/RequiredTrainerInterface/#training_end","text":"1 def training_end ( self , train_step_outputs ) In certain cases (dp, ddp2), you might want to use all outputs of every process to do something. For instance, if using negative samples, you could run a batch via dp and use ALL the outputs for a single softmax across the full batch (ie: the denominator would use the full batch). In this case you should define training_end to perform those calculations. Params Param description outputs What you return in training_step. Return Dictionary or OrderedDict key value is required loss tensor scalar Y progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 # WITHOUT training_end # if used in DP or DDP2, this batch is 1/nb_gpus large def training_step ( self , batch , batch_nb ): # batch is 1/nb_gpus big x , y = batch out = self . forward ( x ) loss = self . softmax ( out ) loss = nce_loss ( loss ) return { 'loss' : loss } # -------------- # with training_end to do softmax over the full batch def training_step ( self , batch , batch_nb ): # batch is 1/nb_gpus big x , y = batch out = self . forward ( x ) return { 'out' : out } def training_end ( self , outputs ): # this out is now the full size of the batch out = outputs [ 'out' ] # this softmax now uses the full batch size loss = self . softmax ( out ) loss = nce_loss ( loss ) return { 'loss' : loss } If you define multiple optimizers, this step will also be called with an additional optimizer_idx param. 1 2 3 4 5 6 # Multiple optimizers (ie: GANs) def training_step ( self , batch , batch_nb , optimizer_idx ): if optimizer_idx == 0 : # do training_step with encoder if optimizer_idx == 1 : # do training_step with decoder If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step. 1 2 3 # Truncated back-propagation through time def training_step ( self , batch , batch_nb , hiddens ): # hiddens are the hiddens from the previous truncated backprop step You can also return a -1 instead of a dict to stop the current loop. This is useful if you want to break out of the current training epoch early.","title":"training_end"},{"location":"LightningModule/RequiredTrainerInterface/#train_dataloader","text":"1 2 @pl.data_loader def train_dataloader ( self ) Called by lightning during training loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator.","title":"train_dataloader"},{"location":"LightningModule/RequiredTrainerInterface/#return","text":"PyTorch DataLoader Example 1 2 3 4 5 6 7 8 9 10 @pl.data_loader def train_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = True , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#configure_optimizers","text":"1 def configure_optimizers ( self ) Set up as many optimizers and (optionally) learning rate schedulers as you need. Normally you'd need one. But in the case of GANs or something more esoteric you might have multiple. Lightning will call .backward() and .step() on each one in every epoch. If you use 16 bit precision it will also handle that. Note: If you use multiple optimizers, training_step will have an additional optimizer_idx parameter. Note 2: If you use LBFGS lightning handles the closure function automatically for you.","title":"configure_optimizers"},{"location":"LightningModule/RequiredTrainerInterface/#return_1","text":"Return any of these 3 options: Single optimizer List or Tuple - List of optimizers Two lists - The first list has multiple optimizers, the second a list of learning-rate schedulers Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # most cases def configure_optimizers ( self ): opt = Adam ( self . parameters (), lr = 0.01 ) return opt # multiple optimizer case (eg: GAN) def configure_optimizers ( self ): generator_opt = Adam ( self . model_gen . parameters (), lr = 0.01 ) disriminator_opt = Adam ( self . model_disc . parameters (), lr = 0.02 ) return generator_opt , disriminator_opt # example with learning_rate schedulers def configure_optimizers ( self ): generator_opt = Adam ( self . model_gen . parameters (), lr = 0.01 ) disriminator_opt = Adam ( self . model_disc . parameters (), lr = 0.02 ) discriminator_sched = CosineAnnealing ( discriminator_opt , T_max = 10 ) return [ generator_opt , disriminator_opt ], [ discriminator_sched ] If you need to control how often those optimizers step or override the default .step() schedule, override the optimizer_step hook.","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#optional-methods","text":"","title":"Optional Methods"},{"location":"LightningModule/RequiredTrainerInterface/#validation_step","text":"1 2 3 4 5 # if you have one val dataloader: def validation_step ( self , batch , batch_nb ) # if you have multiple val dataloaders: def validation_step ( self , batch , batch_nb , dataloader_idxdx ) OPTIONAL If you don't need to validate you don't need to implement this method. In this step you'd normally generate examples or calculate anything of interest such as accuracy. When the validation_step is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, model goes back to training mode and gradients are enabled. The dict you return here will be available in the validation_end method. Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is dataloader_idx Integer displaying which dataloader this is (only if multiple val datasets used) Return Return description optional dict Dict or OrderedDict - passed to the validation_end step N Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 # CASE 1: A single validation dataset def validation_step ( self , batch , batch_nb ): x , y = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , y ) # log 6 example images # or generated text... or whatever sample_imgs = x [: 6 ] grid = torchvision . utils . make_grid ( sample_imgs ) self . logger . experiment . add_image ( 'example_images' , grid , 0 ) # calculate acc labels_hat = torch . argmax ( out , dim = 1 ) val_acc = torch . sum ( y == labels_hat ) . item () / ( len ( y ) * 1.0 ) # all optional... # return whatever you need for the collation function validation_end output = OrderedDict ({ 'val_loss' : loss_val , 'val_acc' : torch . tensor ( val_acc ), # everything must be a tensor }) # return an optional dict return output If you pass in multiple validation datasets, validation_step will have an additional argument. 1 2 3 # CASE 2: multiple validation datasets def validation_step ( self , batch , batch_nb , dataset_idx ): # dataset_idx tells you which dataset this is. The dataset_idx corresponds to the order of datasets returned in val_dataloader .","title":"validation_step"},{"location":"LightningModule/RequiredTrainerInterface/#validation_end","text":"1 def validation_end ( self , outputs ) If you didn't define a validation_step, this won't be called. Called at the end of the validation loop with the outputs of validation_step. The outputs here are strictly for the progress bar. If you don't need to display anything, don't return anything. Any keys present in 'log', 'progress_bar' or the rest of the dictionary are available for callbacks to access. Params Param description outputs List of outputs you defined in validation_step, or if there are multiple dataloaders, a list containing a list of outputs for each dataloader Return Dictionary or OrderedDict key value is required progress_bar Dict for progress bar display. Must have only tensors N log Dict of metrics to add to logger. Must have only tensors (no images, etc) N Example With a single dataloader 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def validation_end ( self , outputs ): \"\"\" Called at the end of validation to aggregate outputs :param outputs: list of individual outputs of each validation step :return: \"\"\" val_loss_mean = 0 val_acc_mean = 0 for output in outputs : val_loss_mean += output [ 'val_loss' ] val_acc_mean += output [ 'val_acc' ] val_loss_mean /= len ( outputs ) val_acc_mean /= len ( outputs ) tqdm_dict = { 'val_loss' : val_loss_mean . item (), 'val_acc' : val_acc_mean . item ()} # show val_loss and val_acc in progress bar but only log val_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'val_loss' : val_loss_mean . item ()} } return results With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def validation_end ( self , outputs ): \"\"\" Called at the end of validation to aggregate outputs :param outputs: list of list of individual outputs of each validation step :return: \"\"\" val_loss_mean = 0 val_acc_mean = 0 i = 0 for dataloader_outputs in outputs : for output in dataloader_outputs : val_loss_mean += output [ 'val_loss' ] val_acc_mean += output [ 'val_acc' ] i += 1 val_loss_mean /= i val_acc_mean /= i tqdm_dict = { 'val_loss' : val_loss_mean . item (), 'val_acc' : val_acc_mean . item ()} # show val_loss and val_acc in progress bar but only log val_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'val_loss' : val_loss_mean . item ()} } return results","title":"validation_end"},{"location":"LightningModule/RequiredTrainerInterface/#test_step","text":"1 2 3 4 5 # if you have one test dataloader: def test_step ( self , batch , batch_nb ) # if you have multiple test dataloaders: def test_step ( self , batch , batch_nb , dataloader_idxdx ) OPTIONAL If you don't need to test you don't need to implement this method. In this step you'd normally generate examples or calculate anything of interest such as accuracy. When the validation_step is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, model goes back to training mode and gradients are enabled. The dict you return here will be available in the test_end method. This function is used when you execute trainer.test() . Params Param description batch The output of your dataloader. A tensor, tuple or list batch_nb Integer displaying which batch this is dataloader_idx Integer displaying which dataloader this is (only if multiple test datasets used) Return Return description optional dict Dict or OrderedDict with metrics to display in progress bar. All keys must be tensors. Y Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # CASE 1: A single test dataset def test_step ( self , batch , batch_nb ): x , y = batch # implement your own out = self . forward ( x ) loss = self . loss ( out , y ) # calculate acc labels_hat = torch . argmax ( out , dim = 1 ) test_acc = torch . sum ( y == labels_hat ) . item () / ( len ( y ) * 1.0 ) # all optional... # return whatever you need for the collation function test_end output = OrderedDict ({ 'test_loss' : loss_test , 'test_acc' : torch . tensor ( test_acc ), # everything must be a tensor }) # return an optional dict return output If you pass in multiple test datasets, test_step will have an additional argument. 1 2 3 # CASE 2: multiple test datasets def test_step ( self , batch , batch_nb , dataset_idx ): # dataset_idx tells you which dataset this is. The dataset_idx corresponds to the order of datasets returned in test_dataloader .","title":"test_step"},{"location":"LightningModule/RequiredTrainerInterface/#test_end","text":"1 def test_end ( self , outputs ) If you didn't define a test_step, this won't be called. Called at the end of the test step with the output of each test_step. The outputs here are strictly for the progress bar. If you don't need to display anything, don't return anything. Params Param description outputs List of outputs you defined in test_step, or if there are multiple dataloaders, a list containing a list of outputs for each dataloader Return Return description optional dict Dict of OrderedDict with metrics to display in progress bar Y Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def test_end ( self , outputs ): \"\"\" Called at the end of test to aggregate outputs :param outputs: list of individual outputs of each test step :return: \"\"\" test_loss_mean = 0 test_acc_mean = 0 for output in outputs : test_loss_mean += output [ 'test_loss' ] test_acc_mean += output [ 'test_acc' ] test_loss_mean /= len ( outputs ) test_acc_mean /= len ( outputs ) tqdm_dict = { 'test_loss' : test_loss_mean . item (), 'test_acc' : test_acc_mean . item ()} # show test_loss and test_acc in progress bar but only log test_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'test_loss' : val_loss_mean . item ()} } return results With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def test_end ( self , outputs ): \"\"\" Called at the end of test to aggregate outputs :param outputs: list of individual outputs of each test step :return: \"\"\" test_loss_mean = 0 test_acc_mean = 0 i = 0 for dataloader_outputs in outputs : for output in dataloader_outputs : test_loss_mean += output [ 'test_loss' ] test_acc_mean += output [ 'test_acc' ] i += 1 test_loss_mean /= i test_acc_mean /= i tqdm_dict = { 'test_loss' : test_loss_mean . item (), 'test_acc' : test_acc_mean . item ()} # show test_loss and test_acc in progress bar but only log test_loss results = { 'progress_bar' : tqdm_dict , 'log' : { 'test_loss' : val_loss_mean . item ()} } return results","title":"test_end"},{"location":"LightningModule/RequiredTrainerInterface/#on_save_checkpoint","text":"1 def on_save_checkpoint ( self , checkpoint ) Called by lightning to checkpoint your model. Lightning saves the training state (current epoch, global_step, etc) and also saves the model state_dict. If you want to save anything else, use this method to add your own key-value pair.","title":"on_save_checkpoint"},{"location":"LightningModule/RequiredTrainerInterface/#return_2","text":"Nothing Example 1 2 3 def on_save_checkpoint ( self , checkpoint ): # 99% of use cases you don't need to implement this method checkpoint [ 'something_cool_i_want_to_save' ] = my_cool_pickable_object","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#on_load_checkpoint","text":"1 def on_load_checkpoint ( self , checkpoint ) Called by lightning to restore your model. Lighting auto-restores global step, epoch, etc... It also restores the model state_dict. If you saved something with on_save_checkpoint this is your chance to restore this.","title":"on_load_checkpoint"},{"location":"LightningModule/RequiredTrainerInterface/#return_3","text":"Nothing Example 1 2 3 def on_load_checkpoint ( self , checkpoint ): # 99% of the time you don't need to implement this method self . something_cool_i_want_to_save = checkpoint [ 'something_cool_i_want_to_save' ]","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#val_dataloader","text":"1 2 @pl.data_loader def val_dataloader ( self ) OPTIONAL If you don't need a validation dataset and a validation_step, you don't need to implement this method. Called by lightning during validation loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator.","title":"val_dataloader"},{"location":"LightningModule/RequiredTrainerInterface/#return_4","text":"PyTorch DataLoader or list of PyTorch Dataloaders. Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @pl.data_loader def val_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = False , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader # can also return multiple dataloaders @pl.data_loader def val_dataloader ( self ): return [ loader_a , loader_b , ... , loader_n ] In the case where you return multiple val_dataloaders, the validation_step will have an arguement dataset_idx which matches the order here.","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#test_dataloader","text":"1 2 @pl.data_loader def test_dataloader ( self ) OPTIONAL If you don't need a test dataset and a test_step, you don't need to implement this method. Called by lightning during test loop. Make sure to use the @pl.data_loader decorator, this ensures not calling this function until the data are needed. If you want to change the data during every epoch DON'T use the data_loader decorator.","title":"test_dataloader"},{"location":"LightningModule/RequiredTrainerInterface/#return_5","text":"PyTorch DataLoader Example 1 2 3 4 5 6 7 8 9 10 11 @pl.data_loader def test_dataloader ( self ): transform = transforms . Compose ([ transforms . ToTensor (), transforms . Normalize (( 0.5 ,), ( 1.0 ,))]) dataset = MNIST ( root = '/path/to/mnist/' , train = False , transform = transform , download = True ) loader = torch . utils . data . DataLoader ( dataset = dataset , batch_size = self . hparams . batch_size , shuffle = True ) return loader","title":"Return"},{"location":"LightningModule/RequiredTrainerInterface/#add_model_specific_args","text":"1 2 @staticmethod def add_model_specific_args ( parent_parser , root_dir ) Lightning has a list of default argparse commands. This method is your chance to add or modify commands specific to your model. The hyperparameter argument parser is available anywhere in your model by calling self.hparams.","title":"add_model_specific_args"},{"location":"LightningModule/RequiredTrainerInterface/#return_6","text":"An argument parser Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @staticmethod def add_model_specific_args ( parent_parser , root_dir ): parser = HyperOptArgumentParser ( strategy = parent_parser . strategy , parents = [ parent_parser ]) # param overwrites # parser.set_defaults(gradient_clip_val=5.0) # network params parser . opt_list ( '--drop_prob' , default = 0.2 , options = [ 0.2 , 0.5 ], type = float , tunable = False ) parser . add_argument ( '--in_features' , default = 28 * 28 ) parser . add_argument ( '--out_features' , default = 10 ) parser . add_argument ( '--hidden_dim' , default = 50000 ) # use 500 for CPU, 50000 for GPU to see speed difference # data parser . add_argument ( '--data_root' , default = os . path . join ( root_dir , 'mnist' ), type = str ) # training params (opt) parser . opt_list ( '--learning_rate' , default = 0.001 , type = float , options = [ 0.0001 , 0.0005 , 0.001 , 0.005 ], tunable = False ) parser . opt_list ( '--batch_size' , default = 256 , type = int , options = [ 32 , 64 , 128 , 256 ], tunable = False ) parser . opt_list ( '--optimizer_name' , default = 'adam' , type = str , options = [ 'adam' ], tunable = False ) return parser","title":"Return"},{"location":"LightningModule/methods/","text":"Lightning modules are strict superclasses of torch.nn.Module. A LightningModule offers the following in addition to that API. freeze Freeze all params for inference 1 2 model = MyLightningModule ( ... ) model . freeze () load_from_metrics This is the easiest/fastest way which loads hyperparameters and weights from a checkpoint, such as the one saved by the ModelCheckpoint callback 1 2 3 4 5 6 7 8 pretrained_model = MyLightningModule . load_from_checkpoint ( checkpoint_path = '/path/to/pytorch_checkpoint.ckpt' ) # predict pretrained_model . eval () pretrained_model . freeze () y_hat = pretrained_model ( x ) load_from_metrics If you're using test tube, there is an alternate method which uses the meta_tags.csv file from test-tube to rebuild the model. The meta_tags.csv file can be found in the test-tube experiment save_dir. 1 2 3 4 5 6 7 8 9 10 11 pretrained_model = MyLightningModule . load_from_metrics ( weights_path = '/path/to/pytorch_checkpoint.ckpt' , tags_csv = '/path/to/test_tube/experiment/version/meta_tags.csv' , on_gpu = True , map_location = None ) # predict pretrained_model . eval () pretrained_model . freeze () y_hat = pretrained_model ( x ) Params Param description weights_path Path to a PyTorch checkpoint tags_csv Path to meta_tags.csv file generated by the test-tube Experiment on_gpu if True, puts model on GPU. Make sure to use transforms option if model devices have changed map_location A dictionary mapping saved weight GPU devices to new GPU devices Returns LightningModule - The pretrained LightningModule unfreeze Unfreeze all params for inference 1 2 model = MyLightningModule ( ... ) model . unfreeze ()","title":"Methods"},{"location":"LightningModule/methods/#freeze","text":"Freeze all params for inference 1 2 model = MyLightningModule ( ... ) model . freeze ()","title":"freeze"},{"location":"LightningModule/methods/#load_from_metrics","text":"This is the easiest/fastest way which loads hyperparameters and weights from a checkpoint, such as the one saved by the ModelCheckpoint callback 1 2 3 4 5 6 7 8 pretrained_model = MyLightningModule . load_from_checkpoint ( checkpoint_path = '/path/to/pytorch_checkpoint.ckpt' ) # predict pretrained_model . eval () pretrained_model . freeze () y_hat = pretrained_model ( x )","title":"load_from_metrics"},{"location":"LightningModule/methods/#load_from_metrics_1","text":"If you're using test tube, there is an alternate method which uses the meta_tags.csv file from test-tube to rebuild the model. The meta_tags.csv file can be found in the test-tube experiment save_dir. 1 2 3 4 5 6 7 8 9 10 11 pretrained_model = MyLightningModule . load_from_metrics ( weights_path = '/path/to/pytorch_checkpoint.ckpt' , tags_csv = '/path/to/test_tube/experiment/version/meta_tags.csv' , on_gpu = True , map_location = None ) # predict pretrained_model . eval () pretrained_model . freeze () y_hat = pretrained_model ( x ) Params Param description weights_path Path to a PyTorch checkpoint tags_csv Path to meta_tags.csv file generated by the test-tube Experiment on_gpu if True, puts model on GPU. Make sure to use transforms option if model devices have changed map_location A dictionary mapping saved weight GPU devices to new GPU devices Returns LightningModule - The pretrained LightningModule","title":"load_from_metrics"},{"location":"LightningModule/methods/#unfreeze","text":"Unfreeze all params for inference 1 2 model = MyLightningModule ( ... ) model . unfreeze ()","title":"unfreeze"},{"location":"LightningModule/properties/","text":"A LightningModule has the following properties which you can access at any time current_epoch The current epoch dtype Current dtype logger A reference to the logger you passed into trainer. Passing a logger is optional. If you don't pass one in, Lightning will create one for you automatically. This logger saves logs to '''/os.getcwd()/lightning_logs''' 1 Trainer ( logger = your_logger ) Call it from anywhere in your LightningModule to add metrics, images, etc... whatever your logger supports. Here is an example using the TestTubeLogger (which is a wrapper on PyTorch SummaryWriter with versioned folder structure). 1 2 3 4 # if logger is a tensorboard logger or TestTubeLogger self . logger . experiment . add_embedding ( ... ) self . logger . experiment . log ({ 'val_loss' : 0.9 }) self . logger . experiment . add_scalars ( ... ) global_step Total training batches seen across all epochs gradient_clip_val The current gradient clip value on_gpu True if your model is currently running on GPUs. Useful to set flags around the LightningModule for different CPU vs GPU behavior. trainer Last resort access to any state the trainer has. Changing certain properties here could affect your training run. 1 2 3 self . trainer . optimizers self . trainer . current_epoch ... Debugging The LightningModule also offers these tricks to help debug. example_input_array In the LightningModule init, you can set a dummy tensor for this property to get a print out of sizes coming into and out of every layer. 1 2 3 def __init__ ( self ): # put the dimensions of the first input to your system self . example_input_array = torch . rand ( 5 , 28 * 28 )","title":"Properties"},{"location":"LightningModule/properties/#current_epoch","text":"The current epoch","title":"current_epoch"},{"location":"LightningModule/properties/#dtype","text":"Current dtype","title":"dtype"},{"location":"LightningModule/properties/#logger","text":"A reference to the logger you passed into trainer. Passing a logger is optional. If you don't pass one in, Lightning will create one for you automatically. This logger saves logs to '''/os.getcwd()/lightning_logs''' 1 Trainer ( logger = your_logger ) Call it from anywhere in your LightningModule to add metrics, images, etc... whatever your logger supports. Here is an example using the TestTubeLogger (which is a wrapper on PyTorch SummaryWriter with versioned folder structure). 1 2 3 4 # if logger is a tensorboard logger or TestTubeLogger self . logger . experiment . add_embedding ( ... ) self . logger . experiment . log ({ 'val_loss' : 0.9 }) self . logger . experiment . add_scalars ( ... )","title":"logger"},{"location":"LightningModule/properties/#global_step","text":"Total training batches seen across all epochs","title":"global_step"},{"location":"LightningModule/properties/#gradient_clip_val","text":"The current gradient clip value","title":"gradient_clip_val"},{"location":"LightningModule/properties/#on_gpu","text":"True if your model is currently running on GPUs. Useful to set flags around the LightningModule for different CPU vs GPU behavior.","title":"on_gpu"},{"location":"LightningModule/properties/#trainer","text":"Last resort access to any state the trainer has. Changing certain properties here could affect your training run. 1 2 3 self . trainer . optimizers self . trainer . current_epoch ...","title":"trainer"},{"location":"LightningModule/properties/#debugging","text":"The LightningModule also offers these tricks to help debug.","title":"Debugging"},{"location":"LightningModule/properties/#example_input_array","text":"In the LightningModule init, you can set a dummy tensor for this property to get a print out of sizes coming into and out of every layer. 1 2 3 def __init__ ( self ): # put the dimensions of the first input to your system self . example_input_array = torch . rand ( 5 , 28 * 28 )","title":"example_input_array"},{"location":"Trainer/","text":"Trainer [ Github Code ] The lightning trainer abstracts best practices for running a training, val, test routine. It calls parts of your model when it wants to hand over full control and otherwise makes training assumptions which are now standard practice in AI research. This is the basic use of the trainer: 1 2 3 4 5 6 from pytorch_lightning import Trainer model = LightningTemplate () trainer = Trainer () trainer . fit ( model ) But of course the fun is in all the advanced things it can do: Checkpointing Checkpoint callback Model saving Model loading Restoring training session Computing cluster (SLURM) Running grid search on a cluster Walltime auto-resubmit Debugging Fast dev run Inspect gradient norms Log GPU usage Make model overfit on subset of data Print the parameter count by layer Print which gradients are nan Print input and output size of every module in system Distributed training Implement Your Own Distributed (DDP) training 16-bit mixed precision Multi-GPU Multi-node Single GPU Self-balancing architecture Experiment Logging Display metrics in progress bar Log metric row every k batches Process position Tensorboard support Save a snapshot of all hyperparameters Snapshot code for a training run Write logs file to csv every k batches Training loop Accumulate gradients Force training for min or max epochs Early stopping callback Force disable early stop Gradient Clipping Hooks Learning rate scheduling Use multiple optimizers (like GANs) Set how much of the training set to check (1-100%) Step optimizers at arbitrary intervals Packed sequences Truncated Back Propagation Through Time Validation loop Check validation every n epochs Hooks Set how much of the validation set to check Set how much of the test set to check Set validation check frequency within 1 training epoch Set the number of validation sanity steps Testing loop Run test set","title":"Trainer"},{"location":"Trainer/#trainer","text":"[ Github Code ] The lightning trainer abstracts best practices for running a training, val, test routine. It calls parts of your model when it wants to hand over full control and otherwise makes training assumptions which are now standard practice in AI research. This is the basic use of the trainer: 1 2 3 4 5 6 from pytorch_lightning import Trainer model = LightningTemplate () trainer = Trainer () trainer . fit ( model ) But of course the fun is in all the advanced things it can do: Checkpointing Checkpoint callback Model saving Model loading Restoring training session Computing cluster (SLURM) Running grid search on a cluster Walltime auto-resubmit Debugging Fast dev run Inspect gradient norms Log GPU usage Make model overfit on subset of data Print the parameter count by layer Print which gradients are nan Print input and output size of every module in system Distributed training Implement Your Own Distributed (DDP) training 16-bit mixed precision Multi-GPU Multi-node Single GPU Self-balancing architecture Experiment Logging Display metrics in progress bar Log metric row every k batches Process position Tensorboard support Save a snapshot of all hyperparameters Snapshot code for a training run Write logs file to csv every k batches Training loop Accumulate gradients Force training for min or max epochs Early stopping callback Force disable early stop Gradient Clipping Hooks Learning rate scheduling Use multiple optimizers (like GANs) Set how much of the training set to check (1-100%) Step optimizers at arbitrary intervals Packed sequences Truncated Back Propagation Through Time Validation loop Check validation every n epochs Hooks Set how much of the validation set to check Set how much of the test set to check Set validation check frequency within 1 training epoch Set the number of validation sanity steps Testing loop Run test set","title":"Trainer"},{"location":"Trainer/Checkpointing/","text":"Lightning can automate saving and loading checkpoints. Model saving Checkpointing is enabled by default to the current working directory. To change the checkpoint path pass in : 1 Trainer ( default_save_path = '/your/path/to/save/checkpoints' ) To modify the behavior of checkpointing pass in your own callback. 1 2 3 4 5 6 7 8 9 10 11 12 13 from pytorch_lightning.callbacks import ModelCheckpoint # DEFAULTS used by the Trainer checkpoint_callback = ModelCheckpoint ( filepath = os . getcwd (), save_best_only = True , verbose = True , monitor = 'val_loss' , mode = 'min' , prefix = '' ) trainer = Trainer ( checkpoint_callback = checkpoint_callback ) Restoring training session You might want to not only load a model but also continue training it. Use this method to restore the trainer state as well. This will continue from the epoch and global step you last left off. However, the dataloaders will start from the first batch again (if you shuffled it shouldn't matter). Lightning will restore the session if you pass a logger with the same version and there's a saved checkpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from pytorch_lightning import Trainer from pytorch_lightning.logging import TestTubeLogger logger = TestTubeLogger ( save_dir = './savepath' , version = 1 # An existing version with a saved checkpoint ) trainer = Trainer ( logger = logger , default_save_path = './savepath' ) # this fit call loads model weights and trainer state # the trainer continues seamlessly from where you left off # without having to do anything else. trainer . fit ( model ) The trainer restores: global_step current_epoch All optimizers All lr_schedulers Model weights You can even change the logic of your model as long as the weights and \"architecture\" of the system isn't different. If you add a layer, for instance, it might not work. At a rough level, here's what happens inside Trainer : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 self . global_step = checkpoint [ 'global_step' ] self . current_epoch = checkpoint [ 'epoch' ] # restore the optimizers optimizer_states = checkpoint [ 'optimizer_states' ] for optimizer , opt_state in zip ( self . optimizers , optimizer_states ): optimizer . load_state_dict ( opt_state ) # restore the lr schedulers lr_schedulers = checkpoint [ 'lr_schedulers' ] for scheduler , lrs_state in zip ( self . lr_schedulers , lr_schedulers ): scheduler . load_state_dict ( lrs_state ) # uses the model you passed into trainer model . load_state_dict ( checkpoint [ 'state_dict' ])","title":"Checkpointing"},{"location":"Trainer/Checkpointing/#model-saving","text":"Checkpointing is enabled by default to the current working directory. To change the checkpoint path pass in : 1 Trainer ( default_save_path = '/your/path/to/save/checkpoints' ) To modify the behavior of checkpointing pass in your own callback. 1 2 3 4 5 6 7 8 9 10 11 12 13 from pytorch_lightning.callbacks import ModelCheckpoint # DEFAULTS used by the Trainer checkpoint_callback = ModelCheckpoint ( filepath = os . getcwd (), save_best_only = True , verbose = True , monitor = 'val_loss' , mode = 'min' , prefix = '' ) trainer = Trainer ( checkpoint_callback = checkpoint_callback )","title":"Model saving"},{"location":"Trainer/Checkpointing/#restoring-training-session","text":"You might want to not only load a model but also continue training it. Use this method to restore the trainer state as well. This will continue from the epoch and global step you last left off. However, the dataloaders will start from the first batch again (if you shuffled it shouldn't matter). Lightning will restore the session if you pass a logger with the same version and there's a saved checkpoint. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from pytorch_lightning import Trainer from pytorch_lightning.logging import TestTubeLogger logger = TestTubeLogger ( save_dir = './savepath' , version = 1 # An existing version with a saved checkpoint ) trainer = Trainer ( logger = logger , default_save_path = './savepath' ) # this fit call loads model weights and trainer state # the trainer continues seamlessly from where you left off # without having to do anything else. trainer . fit ( model ) The trainer restores: global_step current_epoch All optimizers All lr_schedulers Model weights You can even change the logic of your model as long as the weights and \"architecture\" of the system isn't different. If you add a layer, for instance, it might not work. At a rough level, here's what happens inside Trainer : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 self . global_step = checkpoint [ 'global_step' ] self . current_epoch = checkpoint [ 'epoch' ] # restore the optimizers optimizer_states = checkpoint [ 'optimizer_states' ] for optimizer , opt_state in zip ( self . optimizers , optimizer_states ): optimizer . load_state_dict ( opt_state ) # restore the lr schedulers lr_schedulers = checkpoint [ 'lr_schedulers' ] for scheduler , lrs_state in zip ( self . lr_schedulers , lr_schedulers ): scheduler . load_state_dict ( lrs_state ) # uses the model you passed into trainer model . load_state_dict ( checkpoint [ 'state_dict' ])","title":"Restoring training session"},{"location":"Trainer/Distributed training/","text":"Lightning makes multi-gpu training and 16 bit training trivial. Note: None of the flags below require changing anything about your lightningModel definition. Choosing a backend Lightning supports two backends. DataParallel and DistributedDataParallel. Both can be used for single-node multi-GPU training. For multi-node training you must use DistributedDataParallel. DataParallel (dp) Splits a batch across multiple GPUs on the same node. Cannot be used for multi-node training. DistributedDataParallel (ddp) Trains a copy of the model on each GPU and only syncs gradients. If used with DistributedSampler, each GPU trains on a subset of the full dataset. DistributedDataParallel-2 (ddp2) Works like DDP, except each node trains a single copy of the model using ALL GPUs on that node. Very useful when dealing with negative samples, etc... You can toggle between each mode by setting this flag. 1 2 3 4 5 6 7 8 9 10 11 # DEFAULT (when using single GPU or no GPUs) trainer = Trainer ( distributed_backend = None ) # Change to DataParallel (gpus > 1) trainer = Trainer ( distributed_backend = 'dp' ) # change to distributed data parallel (gpus > 1) trainer = Trainer ( distributed_backend = 'ddp' ) # change to distributed data parallel (gpus > 1) trainer = Trainer ( distributed_backend = 'ddp2' ) If you request multiple nodes, the back-end will auto-switch to ddp. We recommend you use DistributedDataparallel even for single-node multi-GPU training. It is MUCH faster than DP but may have configuration issues depending on your cluster. For a deeper understanding of what lightning is doing, feel free to read this guide . Distributed and 16-bit precision. Due to an issue with apex and DistributedDataParallel (PyTorch and NVIDIA issue), Lightning does not allow 16-bit and DP training. We tried to get this to work, but it's an issue on their end. Below are the possible configurations we support. 1 GPU 1+ GPUs DP DDP 16-bit command Y Trainer(gpus=1) Y Y Trainer(gpus=1, use_amp=True) Y Y Trainer(gpus=k, distributed_backend='dp') Y Y Trainer(gpus=k, distributed_backend='ddp') Y Y Y Trainer(gpus=k, distributed_backend='ddp', use_amp=True) You also have the option of specifying which GPUs to use by passing a list: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # DEFAULT (int) specifies how many GPUs to use. Trainer ( gpus = k ) # Above is equivalent to Trainer ( gpus = list ( range ( k ))) # You specify which GPUs (don't use if running on cluster) Trainer ( gpus = [ 0 , 1 ]) # can also be a string Trainer ( gpus = '0, 1' ) # can also be -1 or '-1', this uses all available GPUs # this is equivalent to list(range(torch.cuda.available_devices())) Trainer ( gpus =- 1 ) CUDA flags CUDA flags make certain GPUs visible to your script. Lightning sets these for you automatically, there's NO NEED to do this yourself. 1 2 3 # lightning will set according to what you give the trainer # os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" However, when using a cluster, Lightning will NOT set these flags (and you should not either). SLURM will set these for you. 16-bit mixed precision 16 bit precision can cut your memory footprint by half. If using volta architecture GPUs it can give a dramatic training speed-up as well. First, install apex (if install fails, look here ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 $ git clone https://github.com/NVIDIA/apex $ cd apex # ------------------------ # OPTIONAL: on your cluster you might need to load cuda 10 or 9 # depending on how you installed PyTorch # see available modules module avail # load correct cuda before install module load cuda-10.0 # ------------------------ # make sure you've loaded a cuda version > 4.0 and < 7.0 module load gcc-6.1.0 $ pip install -v --no-cache-dir --global-option = \"--cpp_ext\" --global-option = \"--cuda_ext\" ./ then set this use_amp to True. 1 2 # DEFAULT trainer = Trainer ( amp_level = 'O2' , use_amp = False ) Single-gpu Make sure you're on a GPU machine. 1 2 # DEFAULT trainer = Trainer ( gpus = 1 ) multi-gpu Make sure you're on a GPU machine. You can set as many GPUs as you want. In this setting, the model will run on all 8 GPUs at once using DataParallel under the hood. 1 2 3 4 5 # to use DataParallel trainer = Trainer ( gpus = 8 , distributed_backend = 'dp' ) # RECOMMENDED use DistributedDataParallel trainer = Trainer ( gpus = 8 , distributed_backend = 'ddp' ) Multi-node Multi-node training is easily done by specifying these flags. 1 2 # train on 12*8 GPUs trainer = Trainer ( gpus = 8 , nb_gpu_nodes = 12 , distributed_backend = 'ddp' ) You must configure your job submission script correctly for the trainer to work. Here is an example script for the above trainer configuration. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #!/bin/bash -l # SLURM SUBMIT SCRIPT #SBATCH --nodes=12 #SBATCH --gres=gpu:8 #SBATCH --ntasks-per-node=8 #SBATCH --mem=0 #SBATCH --time=0-02:00:00 # activate conda env conda activate my_env # ------------------------- # OPTIONAL # ------------------------- # debugging flags (optional) # export NCCL_DEBUG=INFO # export PYTHONFAULTHANDLER=1 # PyTorch comes with prebuilt NCCL support... but if you have issues with it # you might need to load the latest version from your modules # module load NCCL/2.4.7-1-cuda.10.0 # on your cluster you might need these: # set the network interface # export NCCL_SOCKET_IFNAME=^docker0,lo # ------------------------- # random port between 12k and 20k export MASTER_PORT = $(( 12000 + RANDOM % 20000 )) # run script from above python my_main_file.py NOTE: When running in DDP mode, any errors in your code will show up as an NCCL issue. Set the NCCL_DEBUG=INFO flag to see the ACTUAL error. Finally, make sure to add a distributed sampler to your dataset. The distributed sampler copies a portion of your dataset onto each GPU. (World_size = gpus_per_node * nb_nodes). 1 2 3 4 5 6 7 8 # ie: this: dataset = myDataset () dataloader = Dataloader ( dataset ) # becomes: dataset = myDataset () dist_sampler = torch . utils . data . distributed . DistributedSampler ( dataset ) dataloader = Dataloader ( dataset , sampler = dist_sampler ) Auto-slurm-job-submission Instead of manually building SLURM scripts, you can use the SlurmCluster object to do this for you. The SlurmCluster can also run a grid search if you pass in a HyperOptArgumentParser . Here is an example where you run a grid search of 9 combinations of hyperparams. The full examples are here . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 # grid search 3 values of learning rate and 3 values of number of layers for your net # this generates 9 experiments (lr=1e-3, layers=16), (lr=1e-3, layers=32), (lr=1e-3, layers=64), ... (lr=1e-1, layers=64) parser = HyperOptArgumentParser ( strategy = 'grid_search' , add_help = False ) parser . opt_list ( '--learning_rate' , default = 0.001 , type = float , options = [ 1e-3 , 1e-2 , 1e-1 ], tunable = True ) parser . opt_list ( '--layers' , default = 1 , type = float , options = [ 16 , 32 , 64 ], tunable = True ) hyperparams = parser . parse_args () # Slurm cluster submits 9 jobs, each with a set of hyperparams cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = '/some/path/to/save' , ) # OPTIONAL FLAGS WHICH MAY BE CLUSTER DEPENDENT # which interface your nodes use for communication cluster . add_command ( 'export NCCL_SOCKET_IFNAME=^docker0,lo' ) # see output of the NCCL connection process # NCCL is how the nodes talk to each other cluster . add_command ( 'export NCCL_DEBUG=INFO' ) # setting a master port here is a good idea. cluster . add_command ( 'export MASTER_PORT= %r ' % PORT ) # ************** DON'T FORGET THIS *************** # MUST load the latest NCCL version cluster . load_modules ([ 'NCCL/2.4.7-1-cuda.10.0' ]) # configure cluster cluster . per_experiment_nb_nodes = 12 cluster . per_experiment_nb_gpus = 8 cluster . add_slurm_cmd ( cmd = 'ntasks-per-node' , value = 8 , comment = '1 task per gpu' ) # submit a script with 9 combinations of hyper params # (lr=1e-3, layers=16), (lr=1e-3, layers=32), (lr=1e-3, layers=64), ... (lr=1e-1, layers=64) cluster . optimize_parallel_cluster_gpu ( main , nb_trials = 9 , # how many permutations of the grid search to run job_name = 'name_for_squeue' ) The other option is that you generate scripts on your own via a bash command or use another library... Self-balancing architecture Here lightning distributes parts of your module across available GPUs to optimize for speed and memory. COMING SOON.","title":"Distributed training"},{"location":"Trainer/Distributed training/#choosing-a-backend","text":"Lightning supports two backends. DataParallel and DistributedDataParallel. Both can be used for single-node multi-GPU training. For multi-node training you must use DistributedDataParallel.","title":"Choosing a backend"},{"location":"Trainer/Distributed training/#dataparallel-dp","text":"Splits a batch across multiple GPUs on the same node. Cannot be used for multi-node training.","title":"DataParallel (dp)"},{"location":"Trainer/Distributed training/#distributeddataparallel-ddp","text":"Trains a copy of the model on each GPU and only syncs gradients. If used with DistributedSampler, each GPU trains on a subset of the full dataset.","title":"DistributedDataParallel (ddp)"},{"location":"Trainer/Distributed training/#distributeddataparallel-2-ddp2","text":"Works like DDP, except each node trains a single copy of the model using ALL GPUs on that node. Very useful when dealing with negative samples, etc... You can toggle between each mode by setting this flag. 1 2 3 4 5 6 7 8 9 10 11 # DEFAULT (when using single GPU or no GPUs) trainer = Trainer ( distributed_backend = None ) # Change to DataParallel (gpus > 1) trainer = Trainer ( distributed_backend = 'dp' ) # change to distributed data parallel (gpus > 1) trainer = Trainer ( distributed_backend = 'ddp' ) # change to distributed data parallel (gpus > 1) trainer = Trainer ( distributed_backend = 'ddp2' ) If you request multiple nodes, the back-end will auto-switch to ddp. We recommend you use DistributedDataparallel even for single-node multi-GPU training. It is MUCH faster than DP but may have configuration issues depending on your cluster. For a deeper understanding of what lightning is doing, feel free to read this guide .","title":"DistributedDataParallel-2 (ddp2)"},{"location":"Trainer/Distributed training/#distributed-and-16-bit-precision","text":"Due to an issue with apex and DistributedDataParallel (PyTorch and NVIDIA issue), Lightning does not allow 16-bit and DP training. We tried to get this to work, but it's an issue on their end. Below are the possible configurations we support. 1 GPU 1+ GPUs DP DDP 16-bit command Y Trainer(gpus=1) Y Y Trainer(gpus=1, use_amp=True) Y Y Trainer(gpus=k, distributed_backend='dp') Y Y Trainer(gpus=k, distributed_backend='ddp') Y Y Y Trainer(gpus=k, distributed_backend='ddp', use_amp=True) You also have the option of specifying which GPUs to use by passing a list: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # DEFAULT (int) specifies how many GPUs to use. Trainer ( gpus = k ) # Above is equivalent to Trainer ( gpus = list ( range ( k ))) # You specify which GPUs (don't use if running on cluster) Trainer ( gpus = [ 0 , 1 ]) # can also be a string Trainer ( gpus = '0, 1' ) # can also be -1 or '-1', this uses all available GPUs # this is equivalent to list(range(torch.cuda.available_devices())) Trainer ( gpus =- 1 )","title":"Distributed and 16-bit precision."},{"location":"Trainer/Distributed training/#cuda-flags","text":"CUDA flags make certain GPUs visible to your script. Lightning sets these for you automatically, there's NO NEED to do this yourself. 1 2 3 # lightning will set according to what you give the trainer # os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" However, when using a cluster, Lightning will NOT set these flags (and you should not either). SLURM will set these for you.","title":"CUDA flags"},{"location":"Trainer/Distributed training/#16-bit-mixed-precision","text":"16 bit precision can cut your memory footprint by half. If using volta architecture GPUs it can give a dramatic training speed-up as well. First, install apex (if install fails, look here ): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 $ git clone https://github.com/NVIDIA/apex $ cd apex # ------------------------ # OPTIONAL: on your cluster you might need to load cuda 10 or 9 # depending on how you installed PyTorch # see available modules module avail # load correct cuda before install module load cuda-10.0 # ------------------------ # make sure you've loaded a cuda version > 4.0 and < 7.0 module load gcc-6.1.0 $ pip install -v --no-cache-dir --global-option = \"--cpp_ext\" --global-option = \"--cuda_ext\" ./ then set this use_amp to True. 1 2 # DEFAULT trainer = Trainer ( amp_level = 'O2' , use_amp = False )","title":"16-bit mixed precision"},{"location":"Trainer/Distributed training/#single-gpu","text":"Make sure you're on a GPU machine. 1 2 # DEFAULT trainer = Trainer ( gpus = 1 )","title":"Single-gpu"},{"location":"Trainer/Distributed training/#multi-gpu","text":"Make sure you're on a GPU machine. You can set as many GPUs as you want. In this setting, the model will run on all 8 GPUs at once using DataParallel under the hood. 1 2 3 4 5 # to use DataParallel trainer = Trainer ( gpus = 8 , distributed_backend = 'dp' ) # RECOMMENDED use DistributedDataParallel trainer = Trainer ( gpus = 8 , distributed_backend = 'ddp' )","title":"multi-gpu"},{"location":"Trainer/Distributed training/#multi-node","text":"Multi-node training is easily done by specifying these flags. 1 2 # train on 12*8 GPUs trainer = Trainer ( gpus = 8 , nb_gpu_nodes = 12 , distributed_backend = 'ddp' ) You must configure your job submission script correctly for the trainer to work. Here is an example script for the above trainer configuration. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #!/bin/bash -l # SLURM SUBMIT SCRIPT #SBATCH --nodes=12 #SBATCH --gres=gpu:8 #SBATCH --ntasks-per-node=8 #SBATCH --mem=0 #SBATCH --time=0-02:00:00 # activate conda env conda activate my_env # ------------------------- # OPTIONAL # ------------------------- # debugging flags (optional) # export NCCL_DEBUG=INFO # export PYTHONFAULTHANDLER=1 # PyTorch comes with prebuilt NCCL support... but if you have issues with it # you might need to load the latest version from your modules # module load NCCL/2.4.7-1-cuda.10.0 # on your cluster you might need these: # set the network interface # export NCCL_SOCKET_IFNAME=^docker0,lo # ------------------------- # random port between 12k and 20k export MASTER_PORT = $(( 12000 + RANDOM % 20000 )) # run script from above python my_main_file.py NOTE: When running in DDP mode, any errors in your code will show up as an NCCL issue. Set the NCCL_DEBUG=INFO flag to see the ACTUAL error. Finally, make sure to add a distributed sampler to your dataset. The distributed sampler copies a portion of your dataset onto each GPU. (World_size = gpus_per_node * nb_nodes). 1 2 3 4 5 6 7 8 # ie: this: dataset = myDataset () dataloader = Dataloader ( dataset ) # becomes: dataset = myDataset () dist_sampler = torch . utils . data . distributed . DistributedSampler ( dataset ) dataloader = Dataloader ( dataset , sampler = dist_sampler )","title":"Multi-node"},{"location":"Trainer/Distributed training/#auto-slurm-job-submission","text":"Instead of manually building SLURM scripts, you can use the SlurmCluster object to do this for you. The SlurmCluster can also run a grid search if you pass in a HyperOptArgumentParser . Here is an example where you run a grid search of 9 combinations of hyperparams. The full examples are here . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 # grid search 3 values of learning rate and 3 values of number of layers for your net # this generates 9 experiments (lr=1e-3, layers=16), (lr=1e-3, layers=32), (lr=1e-3, layers=64), ... (lr=1e-1, layers=64) parser = HyperOptArgumentParser ( strategy = 'grid_search' , add_help = False ) parser . opt_list ( '--learning_rate' , default = 0.001 , type = float , options = [ 1e-3 , 1e-2 , 1e-1 ], tunable = True ) parser . opt_list ( '--layers' , default = 1 , type = float , options = [ 16 , 32 , 64 ], tunable = True ) hyperparams = parser . parse_args () # Slurm cluster submits 9 jobs, each with a set of hyperparams cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = '/some/path/to/save' , ) # OPTIONAL FLAGS WHICH MAY BE CLUSTER DEPENDENT # which interface your nodes use for communication cluster . add_command ( 'export NCCL_SOCKET_IFNAME=^docker0,lo' ) # see output of the NCCL connection process # NCCL is how the nodes talk to each other cluster . add_command ( 'export NCCL_DEBUG=INFO' ) # setting a master port here is a good idea. cluster . add_command ( 'export MASTER_PORT= %r ' % PORT ) # ************** DON'T FORGET THIS *************** # MUST load the latest NCCL version cluster . load_modules ([ 'NCCL/2.4.7-1-cuda.10.0' ]) # configure cluster cluster . per_experiment_nb_nodes = 12 cluster . per_experiment_nb_gpus = 8 cluster . add_slurm_cmd ( cmd = 'ntasks-per-node' , value = 8 , comment = '1 task per gpu' ) # submit a script with 9 combinations of hyper params # (lr=1e-3, layers=16), (lr=1e-3, layers=32), (lr=1e-3, layers=64), ... (lr=1e-1, layers=64) cluster . optimize_parallel_cluster_gpu ( main , nb_trials = 9 , # how many permutations of the grid search to run job_name = 'name_for_squeue' ) The other option is that you generate scripts on your own via a bash command or use another library...","title":"Auto-slurm-job-submission"},{"location":"Trainer/Distributed training/#self-balancing-architecture","text":"Here lightning distributes parts of your module across available GPUs to optimize for speed and memory. COMING SOON.","title":"Self-balancing architecture"},{"location":"Trainer/Logging/","text":"Lighting offers options for logging information about model, gpu usage, etc, via several different logging frameworks. It also offers printing options for training monitoring. default_save_path Lightning sets a default TestTubeLogger and CheckpointCallback for you which log to os.getcwd() by default. To modify the logging path you can set: 1 Trainer ( default_save_path = '/your/path/to/save/checkpoints' ) If you need more custom behavior (different paths for both, different metrics, etc...) from the logger and the checkpointCallback, pass in your own instances as explained below. Setting up logging The trainer inits a default logger for you (TestTubeLogger). All logs will go to the current working directory under a folder named `os.getcwd()/lightning_logs . If you want to modify the default logging behavior even more, pass in a logger (which should inherit from LightningBaseLogger ). 1 2 my_logger = MyLightningLogger ( ... ) trainer = Trainer ( logger = my_logger ) The path in this logger will overwrite default_save_path. Lightning supports several common experiment tracking frameworks out of the box Test tube Log using test tube . Test tube logger is a strict subclass of PyTorch SummaryWriter , refer to their documentation for all supported operations. The TestTubeLogger adds a nicer folder structure to manage experiments and snapshots all hyperparameters you pass to a LightningModule. 1 2 3 4 5 6 7 8 from pytorch_lightning.logging import TestTubeLogger tt_logger = TestTubeLogger ( save_dir = \".\" , name = \"default\" , debug = False , create_git_tag = False ) trainer = Trainer ( logger = tt_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_method_summary_writer_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . add_histogram ( ... ) MLFlow Log using mlflow 1 2 3 4 5 6 from pytorch_lightning.logging import MLFlowLogger mlf_logger = MLFlowLogger ( experiment_name = \"default\" , tracking_uri = \"file:/.\" ) trainer = Trainer ( logger = mlf_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_ml_flow_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . whatever_ml_flow_supports ( ... ) Comet.ml Log using comet 1 2 3 4 5 6 7 from pytorch_lightning.logging import CometLogger # arguments made to CometLogger are passed on to the comet_ml.Experiment class comet_logger = CometLogger ( api_key = os . environ [ \"COMET_KEY\" ], workspace = os . environ [ \"COMET_KEY\" ], ) trainer = Trainer ( logger = comet_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_comet_ml_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . whatever_comet_ml_supports ( ... ) Custom logger You can implement your own logger by writing a class that inherits from LightningLoggerBase . Use the rank_zero_only decorator to make sure that only the first process in DDP training logs data. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from pytorch_lightning.logging import LightningLoggerBase , rank_zero_only class MyLogger ( LightningLoggerBase ): @rank_zero_only def log_hyperparams ( self , params ): # params is an argparse.Namespace # your code to record hyperparameters goes here pass @rank_zero_only def log_metrics ( self , metrics , step_num ): # metrics is a dictionary of metric names and values # your code to record metrics goes here pass def save ( self ): # Optional. Any code necessary to save logger data goes here pass @rank_zero_only def finalize ( self , status ): # Optional. Any code that needs to be run after training # finishes goes here If you write a logger than may be useful to others, please send a pull request to add it to Lighting! Using loggers You can call the logger anywhere from your LightningModule by doing: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_method_summary_writer_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . add_histogram ( ... ) Display metrics in progress bar 1 2 # DEFAULT trainer = Trainer ( show_progress_bar = True ) Log metric row every k batches Every k batches lightning will make an entry in the metrics log 1 2 # DEFAULT (ie: save a .csv log file every 10 batches) trainer = Trainer ( row_log_interval = 10 ) Log GPU memory Logs GPU memory when metrics are logged. 1 2 3 4 5 6 7 8 # DEFAULT trainer = Trainer ( log_gpu_memory = None ) # log only the min/max utilization trainer = Trainer ( log_gpu_memory = 'min_max' ) # log all the GPU memory (if on DDP, logs only that node) trainer = Trainer ( log_gpu_memory = 'all' ) Process position When running multiple models on the same machine we want to decide which progress bar to use. Lightning will stack progress bars according to this value. 1 2 3 4 5 # DEFAULT trainer = Trainer ( process_position = 0 ) # if this is the second model on the node, show the second progress bar below trainer = Trainer ( process_position = 1 ) Save a snapshot of all hyperparameters Automatically log hyperparameters stored in the hparams attribute as an argparse.Namespace 1 2 3 4 5 6 7 8 9 10 11 12 class MyModel ( pl . Lightning ): def __init__ ( self , hparams ): self . hparams = hparams ... args = parser . parse_args () model = MyModel ( args ) logger = TestTubeLogger ( ... ) t = Trainer ( logger = logger ) trainer . fit ( model ) Write logs file to csv every k batches Every k batches, lightning will write the new logs to disk 1 2 # DEFAULT (ie: save a .csv log file every 100 batches) trainer = Trainer ( log_save_interval = 100 )","title":"Logging"},{"location":"Trainer/Logging/#default_save_path","text":"Lightning sets a default TestTubeLogger and CheckpointCallback for you which log to os.getcwd() by default. To modify the logging path you can set: 1 Trainer ( default_save_path = '/your/path/to/save/checkpoints' ) If you need more custom behavior (different paths for both, different metrics, etc...) from the logger and the checkpointCallback, pass in your own instances as explained below.","title":"default_save_path"},{"location":"Trainer/Logging/#setting-up-logging","text":"The trainer inits a default logger for you (TestTubeLogger). All logs will go to the current working directory under a folder named `os.getcwd()/lightning_logs . If you want to modify the default logging behavior even more, pass in a logger (which should inherit from LightningBaseLogger ). 1 2 my_logger = MyLightningLogger ( ... ) trainer = Trainer ( logger = my_logger ) The path in this logger will overwrite default_save_path. Lightning supports several common experiment tracking frameworks out of the box","title":"Setting up logging"},{"location":"Trainer/Logging/#test-tube","text":"Log using test tube . Test tube logger is a strict subclass of PyTorch SummaryWriter , refer to their documentation for all supported operations. The TestTubeLogger adds a nicer folder structure to manage experiments and snapshots all hyperparameters you pass to a LightningModule. 1 2 3 4 5 6 7 8 from pytorch_lightning.logging import TestTubeLogger tt_logger = TestTubeLogger ( save_dir = \".\" , name = \"default\" , debug = False , create_git_tag = False ) trainer = Trainer ( logger = tt_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_method_summary_writer_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . add_histogram ( ... )","title":"Test tube"},{"location":"Trainer/Logging/#mlflow","text":"Log using mlflow 1 2 3 4 5 6 from pytorch_lightning.logging import MLFlowLogger mlf_logger = MLFlowLogger ( experiment_name = \"default\" , tracking_uri = \"file:/.\" ) trainer = Trainer ( logger = mlf_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_ml_flow_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . whatever_ml_flow_supports ( ... )","title":"MLFlow"},{"location":"Trainer/Logging/#cometml","text":"Log using comet 1 2 3 4 5 6 7 from pytorch_lightning.logging import CometLogger # arguments made to CometLogger are passed on to the comet_ml.Experiment class comet_logger = CometLogger ( api_key = os . environ [ \"COMET_KEY\" ], workspace = os . environ [ \"COMET_KEY\" ], ) trainer = Trainer ( logger = comet_logger ) Use the logger anywhere in you LightningModule as follows: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_comet_ml_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . whatever_comet_ml_supports ( ... )","title":"Comet.ml"},{"location":"Trainer/Logging/#custom-logger","text":"You can implement your own logger by writing a class that inherits from LightningLoggerBase . Use the rank_zero_only decorator to make sure that only the first process in DDP training logs data. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from pytorch_lightning.logging import LightningLoggerBase , rank_zero_only class MyLogger ( LightningLoggerBase ): @rank_zero_only def log_hyperparams ( self , params ): # params is an argparse.Namespace # your code to record hyperparameters goes here pass @rank_zero_only def log_metrics ( self , metrics , step_num ): # metrics is a dictionary of metric names and values # your code to record metrics goes here pass def save ( self ): # Optional. Any code necessary to save logger data goes here pass @rank_zero_only def finalize ( self , status ): # Optional. Any code that needs to be run after training # finishes goes here If you write a logger than may be useful to others, please send a pull request to add it to Lighting!","title":"Custom logger"},{"location":"Trainer/Logging/#using-loggers","text":"You can call the logger anywhere from your LightningModule by doing: 1 2 3 4 5 6 def train_step ( ... ): # example self . logger . experiment . whatever_method_summary_writer_supports ( ... ) def any_lightning_module_function_or_hook ( ... ): self . logger . experiment . add_histogram ( ... )","title":"Using loggers"},{"location":"Trainer/Logging/#display-metrics-in-progress-bar","text":"1 2 # DEFAULT trainer = Trainer ( show_progress_bar = True )","title":"Display metrics in progress bar"},{"location":"Trainer/Logging/#log-metric-row-every-k-batches","text":"Every k batches lightning will make an entry in the metrics log 1 2 # DEFAULT (ie: save a .csv log file every 10 batches) trainer = Trainer ( row_log_interval = 10 )","title":"Log metric row every k batches"},{"location":"Trainer/Logging/#log-gpu-memory","text":"Logs GPU memory when metrics are logged. 1 2 3 4 5 6 7 8 # DEFAULT trainer = Trainer ( log_gpu_memory = None ) # log only the min/max utilization trainer = Trainer ( log_gpu_memory = 'min_max' ) # log all the GPU memory (if on DDP, logs only that node) trainer = Trainer ( log_gpu_memory = 'all' )","title":"Log GPU memory"},{"location":"Trainer/Logging/#process-position","text":"When running multiple models on the same machine we want to decide which progress bar to use. Lightning will stack progress bars according to this value. 1 2 3 4 5 # DEFAULT trainer = Trainer ( process_position = 0 ) # if this is the second model on the node, show the second progress bar below trainer = Trainer ( process_position = 1 )","title":"Process position"},{"location":"Trainer/Logging/#save-a-snapshot-of-all-hyperparameters","text":"Automatically log hyperparameters stored in the hparams attribute as an argparse.Namespace 1 2 3 4 5 6 7 8 9 10 11 12 class MyModel ( pl . Lightning ): def __init__ ( self , hparams ): self . hparams = hparams ... args = parser . parse_args () model = MyModel ( args ) logger = TestTubeLogger ( ... ) t = Trainer ( logger = logger ) trainer . fit ( model )","title":"Save a snapshot of all hyperparameters"},{"location":"Trainer/Logging/#write-logs-file-to-csv-every-k-batches","text":"Every k batches, lightning will write the new logs to disk 1 2 # DEFAULT (ie: save a .csv log file every 100 batches) trainer = Trainer ( log_save_interval = 100 )","title":"Write logs file to csv every k batches"},{"location":"Trainer/SLURM Managed Cluster/","text":"Lightning supports model training on a cluster managed by SLURM in the following cases: Training on a single cpu or single GPU. Train on multiple GPUs on the same node using DataParallel or DistributedDataParallel Training across multiple GPUs on multiple different nodes via DistributedDataParallel. Note: A node means a machine with multiple GPUs Running grid search on a cluster To use lightning to run a hyperparameter search (grid-search or random-search) on a cluster do 4 things: (1). Define the parameters for the grid search 1 2 3 4 5 6 7 8 9 10 from test_tube import HyperOptArgumentParser # subclass of argparse parser = HyperOptArgumentParser ( strategy = 'random_search' ) parser . add_argument ( '--learning_rate' , default = 0.002 , type = float , help = 'the learning rate' ) # let's enable optimizing over the number of layers in the network parser . opt_list ( '--nb_layers' , default = 2 , type = int , tunable = True , options = [ 2 , 4 , 8 ]) hparams = parser . parse_args () NOTE You must set Tunable=True for that argument to be considered in the permutation set. Otherwise test-tube will use the default value. This flag is useful when you don't want to search over an argument and want to use the default instead. (2). Define the cluster options in the SlurmCluster object (over 5 nodes and 8 gpus) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from test_tube.hpc import SlurmCluster # hyperparameters is a test-tube hyper params object # see https://williamfalcon.github.io/test-tube/hyperparameter_optimization/HyperOptArgumentParser/ hyperparams = args . parse () # init cluster cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = '/path/to/log/results/to' , python_cmd = 'python3' ) # let the cluster know where to email for a change in job status (ie: complete, fail, etc...) cluster . notify_job_status ( email = 'some@email.com' , on_done = True , on_fail = True ) # set the job options. In this instance, we'll run 20 different models # each with its own set of hyperparameters giving each one 1 GPU (ie: taking up 20 GPUs) cluster . per_experiment_nb_gpus = 8 cluster . per_experiment_nb_nodes = 5 # we'll request 10GB of memory per node cluster . memory_mb_per_node = 10000 # set a walltime of 10 minues cluster . job_time = '10:00' (3). Make a main function with your model and trainer. Each job will call this function with a particular hparams configuration. 1 2 3 4 5 6 7 8 9 10 from pytorch_lightning import Trainer def train_fx ( trial_hparams , cluster_manager , _ ): # hparams has a specific set of hyperparams my_model = MyLightningModel () # give the trainer the cluster object trainer = Trainer () trainer . fit ( my_model ) (3). Start the grid/random search 1 2 3 4 5 6 # run the models on the cluster cluster . optimize_parallel_cluster_gpu ( train_fx , nb_trials = 20 , job_name = 'my_grid_search_exp_name' , job_display_name = 'my_exp' ) NOTE nb_trials specifies how many of the possible permutations to use. If using grid_search it will use the depth first ordering. If using random_search it will use the first k shuffled options. FYI, random search has been shown to be just as good as any Bayesian optimization method when using a reasonable number of samples (60), see this paper for more information . Walltime auto-resubmit Lightning automatically resubmits jobs when they reach the walltime. Make sure to set the SIGUSR1 signal in your SLURM script. 1 2 # 90 seconds before training ends #SBATCH --signal=SIGUSR1@90 When lightning receives the SIGUSR1 signal it will: 1. save a checkpoint with 'hpc_ckpt' in the name. 2. resubmit the job using the SLURM_JOB_ID When the script starts again, Lightning will: 1. search for a 'hpc_ckpt' checkpoint. 2. restore the model, optimizers, schedulers, epoch, etc...","title":"SLURM Managed Cluster"},{"location":"Trainer/SLURM Managed Cluster/#running-grid-search-on-a-cluster","text":"To use lightning to run a hyperparameter search (grid-search or random-search) on a cluster do 4 things: (1). Define the parameters for the grid search 1 2 3 4 5 6 7 8 9 10 from test_tube import HyperOptArgumentParser # subclass of argparse parser = HyperOptArgumentParser ( strategy = 'random_search' ) parser . add_argument ( '--learning_rate' , default = 0.002 , type = float , help = 'the learning rate' ) # let's enable optimizing over the number of layers in the network parser . opt_list ( '--nb_layers' , default = 2 , type = int , tunable = True , options = [ 2 , 4 , 8 ]) hparams = parser . parse_args () NOTE You must set Tunable=True for that argument to be considered in the permutation set. Otherwise test-tube will use the default value. This flag is useful when you don't want to search over an argument and want to use the default instead. (2). Define the cluster options in the SlurmCluster object (over 5 nodes and 8 gpus) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from test_tube.hpc import SlurmCluster # hyperparameters is a test-tube hyper params object # see https://williamfalcon.github.io/test-tube/hyperparameter_optimization/HyperOptArgumentParser/ hyperparams = args . parse () # init cluster cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = '/path/to/log/results/to' , python_cmd = 'python3' ) # let the cluster know where to email for a change in job status (ie: complete, fail, etc...) cluster . notify_job_status ( email = 'some@email.com' , on_done = True , on_fail = True ) # set the job options. In this instance, we'll run 20 different models # each with its own set of hyperparameters giving each one 1 GPU (ie: taking up 20 GPUs) cluster . per_experiment_nb_gpus = 8 cluster . per_experiment_nb_nodes = 5 # we'll request 10GB of memory per node cluster . memory_mb_per_node = 10000 # set a walltime of 10 minues cluster . job_time = '10:00' (3). Make a main function with your model and trainer. Each job will call this function with a particular hparams configuration. 1 2 3 4 5 6 7 8 9 10 from pytorch_lightning import Trainer def train_fx ( trial_hparams , cluster_manager , _ ): # hparams has a specific set of hyperparams my_model = MyLightningModel () # give the trainer the cluster object trainer = Trainer () trainer . fit ( my_model ) (3). Start the grid/random search 1 2 3 4 5 6 # run the models on the cluster cluster . optimize_parallel_cluster_gpu ( train_fx , nb_trials = 20 , job_name = 'my_grid_search_exp_name' , job_display_name = 'my_exp' ) NOTE nb_trials specifies how many of the possible permutations to use. If using grid_search it will use the depth first ordering. If using random_search it will use the first k shuffled options. FYI, random search has been shown to be just as good as any Bayesian optimization method when using a reasonable number of samples (60), see this paper for more information .","title":"Running grid search on a cluster"},{"location":"Trainer/SLURM Managed Cluster/#walltime-auto-resubmit","text":"Lightning automatically resubmits jobs when they reach the walltime. Make sure to set the SIGUSR1 signal in your SLURM script. 1 2 # 90 seconds before training ends #SBATCH --signal=SIGUSR1@90 When lightning receives the SIGUSR1 signal it will: 1. save a checkpoint with 'hpc_ckpt' in the name. 2. resubmit the job using the SLURM_JOB_ID When the script starts again, Lightning will: 1. search for a 'hpc_ckpt' checkpoint. 2. restore the model, optimizers, schedulers, epoch, etc...","title":"Walltime auto-resubmit"},{"location":"Trainer/Testing loop/","text":"To ensure you don't accidentally use test data to guide training decisions Lightning makes running the test set deliberate. test You have two options to run the test set. First case is where you test right after a full training routine. 1 2 3 4 5 # run full training trainer . fit ( model ) # run test set trainer . test () Second case is where you load a model and run the test set 1 2 3 4 5 6 7 8 9 10 11 12 model = MyLightningModule . load_from_metrics ( weights_path = '/path/to/pytorch_checkpoint.ckpt' , tags_csv = '/path/to/test_tube/experiment/version/meta_tags.csv' , on_gpu = True , map_location = None ) # init trainer with whatever options trainer = Trainer ( ... ) # test (pass in the model) trainer . test ( model ) In this second case, the options you pass to trainer will be used when running the test set (ie: 16-bit, dp, ddp, etc...)","title":"Testing loop"},{"location":"Trainer/Testing loop/#test","text":"You have two options to run the test set. First case is where you test right after a full training routine. 1 2 3 4 5 # run full training trainer . fit ( model ) # run test set trainer . test () Second case is where you load a model and run the test set 1 2 3 4 5 6 7 8 9 10 11 12 model = MyLightningModule . load_from_metrics ( weights_path = '/path/to/pytorch_checkpoint.ckpt' , tags_csv = '/path/to/test_tube/experiment/version/meta_tags.csv' , on_gpu = True , map_location = None ) # init trainer with whatever options trainer = Trainer ( ... ) # test (pass in the model) trainer . test ( model ) In this second case, the options you pass to trainer will be used when running the test set (ie: 16-bit, dp, ddp, etc...)","title":"test"},{"location":"Trainer/Training Loop/","text":"The lightning training loop handles everything except the actual computations of your model. To decide what will happen in your training loop, define the training_step function . Below are all the things lightning automates for you in the training loop. Accumulated gradients Accumulated gradients runs K small batches of size N before doing a backwards pass. The effect is a large effective batch size of size KxN. 1 2 # DEFAULT (ie: no accumulated grads) trainer = Trainer ( accumulate_grad_batches = 1 ) Force training for min or max epochs It can be useful to force training for a minimum number of epochs or limit to a max number 1 2 # DEFAULT trainer = Trainer ( min_nb_epochs = 1 , max_nb_epochs = 1000 ) Early stopping The trainer already sets up default early stopping for you. To modify this behavior, pass in your own EarlyStopping callback. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from pytorch_lightning.callbacks import EarlyStopping # DEFAULTS used by Trainer early_stop_callback = EarlyStopping ( monitor = 'val_loss' , min_delta = 0.00 , patience = 3 , verbose = False , mode = 'min' ) # without passing anything in, uses the default callback above trainer = Trainer () # pass in your own to override the default callback trainer = Trainer ( early_stop_callback = early_stop_callback ) # pass in None to disable it trainer = Trainer ( early_stop_callback = None ) Force disable early stop To disable early stopping pass None to the early_stop_callback 1 2 # DEFAULT trainer = Trainer ( early_stop_callback = None ) Gradient Clipping Gradient clipping may be enabled to avoid exploding gradients. Specifically, this will clip the gradient norm computed over all model parameters together . 1 2 3 4 5 # DEFAULT (ie: don't clip) trainer = Trainer ( gradient_clip_val = 0 ) # clip gradients with norm above 0.5 trainer = Trainer ( gradient_clip_val = 0.5 ) Inspect gradient norms Looking at grad norms can help you figure out where training might be going wrong. 1 2 3 4 5 # DEFAULT (-1 doesn't track norms) trainer = Trainer ( track_grad_norm =- 1 ) # track the LP norm (P=2 here) trainer = Trainer ( track_grad_norm = 2 ) Set how much of the training set to check If you don't want to check 100% of the training set (for debugging or if it's huge), set this flag. train_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( train_percent_check = 1.0 ) # check 10% only trainer = Trainer ( train_percent_check = 0.1 ) Packed sequences as inputs When using PackedSequence, do 2 things: 1. return either a padded tensor in dataset or a list of variable length tensors in the dataloader collate_fn (example above shows the list implementation). 2. Pack the sequence in forward or training and validation steps depending on use case. 1 2 3 4 5 6 7 8 9 10 # For use in dataloader def collate_fn ( batch ): x = [ item [ 0 ] for item in batch ] y = [ item [ 1 ] for item in batch ] return x , y # In module def training_step ( self , batch , batch_nb ): x = rnn . pack_sequence ( batch [ 0 ], enforce_sorted = False ) y = rnn . pack_sequence ( batch [ 1 ], enforce_sorted = False ) Truncated Back Propagation Through Time There are times when multiple backwards passes are needed for each batch. For example, it may save memory to use Truncated Back Propagation Through Time when training RNNs. When this flag is enabled each batch is split into sequences of size truncated_bptt_steps and passed to training_step(...) separately. A default splitting function is provided, however, you can override it for more flexibility. See tbptt_split_batch . 1 2 3 4 5 # DEFAULT (single backwards pass per batch) trainer = Trainer ( truncated_bptt_steps = None ) # (split batch into sequences of size 2) trainer = Trainer ( truncated_bptt_steps = 2 )","title":"Training Loop"},{"location":"Trainer/Training Loop/#accumulated-gradients","text":"Accumulated gradients runs K small batches of size N before doing a backwards pass. The effect is a large effective batch size of size KxN. 1 2 # DEFAULT (ie: no accumulated grads) trainer = Trainer ( accumulate_grad_batches = 1 )","title":"Accumulated gradients"},{"location":"Trainer/Training Loop/#force-training-for-min-or-max-epochs","text":"It can be useful to force training for a minimum number of epochs or limit to a max number 1 2 # DEFAULT trainer = Trainer ( min_nb_epochs = 1 , max_nb_epochs = 1000 )","title":"Force training for min or max epochs"},{"location":"Trainer/Training Loop/#early-stopping","text":"The trainer already sets up default early stopping for you. To modify this behavior, pass in your own EarlyStopping callback. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from pytorch_lightning.callbacks import EarlyStopping # DEFAULTS used by Trainer early_stop_callback = EarlyStopping ( monitor = 'val_loss' , min_delta = 0.00 , patience = 3 , verbose = False , mode = 'min' ) # without passing anything in, uses the default callback above trainer = Trainer () # pass in your own to override the default callback trainer = Trainer ( early_stop_callback = early_stop_callback ) # pass in None to disable it trainer = Trainer ( early_stop_callback = None )","title":"Early stopping"},{"location":"Trainer/Training Loop/#force-disable-early-stop","text":"To disable early stopping pass None to the early_stop_callback 1 2 # DEFAULT trainer = Trainer ( early_stop_callback = None )","title":"Force disable early stop"},{"location":"Trainer/Training Loop/#gradient-clipping","text":"Gradient clipping may be enabled to avoid exploding gradients. Specifically, this will clip the gradient norm computed over all model parameters together . 1 2 3 4 5 # DEFAULT (ie: don't clip) trainer = Trainer ( gradient_clip_val = 0 ) # clip gradients with norm above 0.5 trainer = Trainer ( gradient_clip_val = 0.5 )","title":"Gradient Clipping"},{"location":"Trainer/Training Loop/#inspect-gradient-norms","text":"Looking at grad norms can help you figure out where training might be going wrong. 1 2 3 4 5 # DEFAULT (-1 doesn't track norms) trainer = Trainer ( track_grad_norm =- 1 ) # track the LP norm (P=2 here) trainer = Trainer ( track_grad_norm = 2 )","title":"Inspect gradient norms"},{"location":"Trainer/Training Loop/#set-how-much-of-the-training-set-to-check","text":"If you don't want to check 100% of the training set (for debugging or if it's huge), set this flag. train_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( train_percent_check = 1.0 ) # check 10% only trainer = Trainer ( train_percent_check = 0.1 )","title":"Set how much of the training set to check"},{"location":"Trainer/Training Loop/#packed-sequences-as-inputs","text":"When using PackedSequence, do 2 things: 1. return either a padded tensor in dataset or a list of variable length tensors in the dataloader collate_fn (example above shows the list implementation). 2. Pack the sequence in forward or training and validation steps depending on use case. 1 2 3 4 5 6 7 8 9 10 # For use in dataloader def collate_fn ( batch ): x = [ item [ 0 ] for item in batch ] y = [ item [ 1 ] for item in batch ] return x , y # In module def training_step ( self , batch , batch_nb ): x = rnn . pack_sequence ( batch [ 0 ], enforce_sorted = False ) y = rnn . pack_sequence ( batch [ 1 ], enforce_sorted = False )","title":"Packed sequences as inputs"},{"location":"Trainer/Training Loop/#truncated-back-propagation-through-time","text":"There are times when multiple backwards passes are needed for each batch. For example, it may save memory to use Truncated Back Propagation Through Time when training RNNs. When this flag is enabled each batch is split into sequences of size truncated_bptt_steps and passed to training_step(...) separately. A default splitting function is provided, however, you can override it for more flexibility. See tbptt_split_batch . 1 2 3 4 5 # DEFAULT (single backwards pass per batch) trainer = Trainer ( truncated_bptt_steps = None ) # (split batch into sequences of size 2) trainer = Trainer ( truncated_bptt_steps = 2 )","title":"Truncated Back Propagation Through Time"},{"location":"Trainer/Validation loop/","text":"The lightning validation loop handles everything except the actual computations of your model. To decide what will happen in your validation loop, define the validation_step function . Below are all the things lightning automates for you in the validation loop. Note Lightning will run 5 steps of validation in the beginning of training as a sanity check so you don't have to wait until a full epoch to catch possible validation issues. Check validation every n epochs If you have a small dataset you might want to check validation every n epochs 1 2 # DEFAULT trainer = Trainer ( check_val_every_n_epoch = 1 ) Set how much of the validation set to check If you don't want to check 100% of the validation set (for debugging or if it's huge), set this flag val_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( val_percent_check = 1.0 ) # check 10% only trainer = Trainer ( val_percent_check = 0.1 ) Set how much of the test set to check If you don't want to check 100% of the test set (for debugging or if it's huge), set this flag test_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( test_percent_check = 1.0 ) # check 10% only trainer = Trainer ( test_percent_check = 0.1 ) Set validation check frequency within 1 training epoch For large datasets it's often desirable to check validation multiple times within a training loop. Pass in a float to check that often within 1 training epoch. Pass in an int k to check every k training batches. Must use an int if using an IterableDataset. 1 2 3 4 5 6 7 8 # DEFAULT trainer = Trainer ( val_check_interval = 0.95 ) # check every .25 of an epoch trainer = Trainer ( val_check_interval = 0.25 ) # check every 100 train batches (ie: for IterableDatasets or fixed frequency) trainer = Trainer ( val_check_interval = 100 ) Set the number of validation sanity steps Lightning runs a few steps of validation in the beginning of training. This avoids crashing in the validation loop sometime deep into a lengthy training loop. 1 2 # DEFAULT trainer = Trainer ( nb_sanity_val_steps = 5 ) You can use Trainer(nb_sanity_val_steps=0) to skip the sanity check.","title":"Validation loop"},{"location":"Trainer/Validation loop/#check-validation-every-n-epochs","text":"If you have a small dataset you might want to check validation every n epochs 1 2 # DEFAULT trainer = Trainer ( check_val_every_n_epoch = 1 )","title":"Check validation every n epochs"},{"location":"Trainer/Validation loop/#set-how-much-of-the-validation-set-to-check","text":"If you don't want to check 100% of the validation set (for debugging or if it's huge), set this flag val_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( val_percent_check = 1.0 ) # check 10% only trainer = Trainer ( val_percent_check = 0.1 )","title":"Set how much of the validation set to check"},{"location":"Trainer/Validation loop/#set-how-much-of-the-test-set-to-check","text":"If you don't want to check 100% of the test set (for debugging or if it's huge), set this flag test_percent_check will be overwritten by overfit_pct if overfit_pct > 0 1 2 3 4 5 # DEFAULT trainer = Trainer ( test_percent_check = 1.0 ) # check 10% only trainer = Trainer ( test_percent_check = 0.1 )","title":"Set how much of the test set to check"},{"location":"Trainer/Validation loop/#set-validation-check-frequency-within-1-training-epoch","text":"For large datasets it's often desirable to check validation multiple times within a training loop. Pass in a float to check that often within 1 training epoch. Pass in an int k to check every k training batches. Must use an int if using an IterableDataset. 1 2 3 4 5 6 7 8 # DEFAULT trainer = Trainer ( val_check_interval = 0.95 ) # check every .25 of an epoch trainer = Trainer ( val_check_interval = 0.25 ) # check every 100 train batches (ie: for IterableDatasets or fixed frequency) trainer = Trainer ( val_check_interval = 100 )","title":"Set validation check frequency within 1 training epoch"},{"location":"Trainer/Validation loop/#set-the-number-of-validation-sanity-steps","text":"Lightning runs a few steps of validation in the beginning of training. This avoids crashing in the validation loop sometime deep into a lengthy training loop. 1 2 # DEFAULT trainer = Trainer ( nb_sanity_val_steps = 5 ) You can use Trainer(nb_sanity_val_steps=0) to skip the sanity check.","title":"Set the number of validation sanity steps"},{"location":"Trainer/debugging/","text":"These flags are useful to help debug a model. Fast dev run This flag is meant for debugging a full train/val/test loop. It'll activate callbacks, everything but only with 1 training and 1 validation batch. Use this to debug a full run of your program quickly 1 2 # DEFAULT trainer = Trainer ( fast_dev_run = False ) Inspect gradient norms Looking at grad norms can help you figure out where training might be going wrong. 1 2 3 4 5 # DEFAULT (-1 doesn't track norms) trainer = Trainer ( track_grad_norm =- 1 ) # track the LP norm (P=2 here) trainer = Trainer ( track_grad_norm = 2 ) Make model overfit on subset of data A useful debugging trick is to make your model overfit a tiny fraction of the data. setting overfit_pct > 0 will overwrite train_percent_check, val_percent_check, test_percent_check 1 2 3 4 5 # DEFAULT don't overfit (ie: normal training) trainer = Trainer ( overfit_pct = 0.0 ) # overfit on 1% of data trainer = Trainer ( overfit_pct = 0.01 ) Print the parameter count by layer By default lightning prints a list of parameters and submodules when it starts training. 1 2 3 4 5 # DEFAULT print a full list of all submodules and their parameters. trainer = Trainer ( weights_summary = 'full' ) # only print the top-level modules (i.e. the children of LightningModule). trainer = Trainer ( weights_summary = 'top' ) Print which gradients are nan This option prints a list of tensors with nan gradients. 1 2 # DEFAULT trainer = Trainer ( print_nan_grads = False ) Log GPU usage Lightning automatically logs gpu usage to the test tube logs. It'll only do it at the metric logging interval, so it doesn't slow down training.","title":"Debugging"},{"location":"Trainer/debugging/#fast-dev-run","text":"This flag is meant for debugging a full train/val/test loop. It'll activate callbacks, everything but only with 1 training and 1 validation batch. Use this to debug a full run of your program quickly 1 2 # DEFAULT trainer = Trainer ( fast_dev_run = False )","title":"Fast dev run"},{"location":"Trainer/debugging/#inspect-gradient-norms","text":"Looking at grad norms can help you figure out where training might be going wrong. 1 2 3 4 5 # DEFAULT (-1 doesn't track norms) trainer = Trainer ( track_grad_norm =- 1 ) # track the LP norm (P=2 here) trainer = Trainer ( track_grad_norm = 2 )","title":"Inspect gradient norms"},{"location":"Trainer/debugging/#make-model-overfit-on-subset-of-data","text":"A useful debugging trick is to make your model overfit a tiny fraction of the data. setting overfit_pct > 0 will overwrite train_percent_check, val_percent_check, test_percent_check 1 2 3 4 5 # DEFAULT don't overfit (ie: normal training) trainer = Trainer ( overfit_pct = 0.0 ) # overfit on 1% of data trainer = Trainer ( overfit_pct = 0.01 )","title":"Make model overfit on subset of data"},{"location":"Trainer/debugging/#print-the-parameter-count-by-layer","text":"By default lightning prints a list of parameters and submodules when it starts training. 1 2 3 4 5 # DEFAULT print a full list of all submodules and their parameters. trainer = Trainer ( weights_summary = 'full' ) # only print the top-level modules (i.e. the children of LightningModule). trainer = Trainer ( weights_summary = 'top' )","title":"Print the parameter count by layer"},{"location":"Trainer/debugging/#print-which-gradients-are-nan","text":"This option prints a list of tensors with nan gradients. 1 2 # DEFAULT trainer = Trainer ( print_nan_grads = False )","title":"Print which gradients are nan"},{"location":"Trainer/debugging/#log-gpu-usage","text":"Lightning automatically logs gpu usage to the test tube logs. It'll only do it at the metric logging interval, so it doesn't slow down training.","title":"Log GPU usage"},{"location":"Trainer/hooks/","text":"Hooks [ Github Code ] There are cases when you might want to do something different at different parts of the training/validation loop. To enable a hook, simply override the method in your LightningModule and the trainer will call it at the correct time. Contributing If there's a hook you'd like to add, simply: 1. Fork PyTorchLightning. 2. Add the hook here . 3. Add the correct place in the Trainer where it should be called. on_epoch_start Called in the training loop at the very beginning of the epoch. 1 2 def on_epoch_start ( self ): # do something when the epoch starts on_epoch_end Called in the training loop at the very end of the epoch. 1 2 def on_epoch_end ( self ): # do something when the epoch ends on_batch_start Called in the training loop before anything happens for that batch. 1 2 def on_batch_start ( self ): # do something when the batch starts on_batch_end Called in the training loop after the batch. 1 2 def on_batch_end ( self ): # do something when the batch ends on_pre_performance_check Called at the very beginning of the validation loop. 1 2 def on_pre_performance_check ( self ): # do something before validation starts on_post_performance_check Called at the very end of the validation loop. 1 2 def on_post_performance_check ( self ): # do something before validation end optimizer_step Calls .step() and .zero_grad for each optimizer. You can override this method to adjust how you do the optimizer step for each optimizer Called once per optimizer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # DEFAULT def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): optimizer . step () optimizer . zero_grad () # Alternating schedule for optimizer steps (ie: GANs) def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): # update generator opt every 2 steps if optimizer_i == 0 : if batch_nb % 2 == 0 : optimizer . step () optimizer . zero_grad () # update discriminator opt every 4 steps if optimizer_i == 1 : if batch_nb % 4 == 0 : optimizer . step () optimizer . zero_grad () # ... # add as many optimizers as you want This step allows you to do a lot of non-standard training tricks such as learning-rate warm-up: 1 2 3 4 5 6 7 8 9 10 11 # learning rate warm-up def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): # warm up lr if self . trainer . global_step < 500 : lr_scale = min ( 1. , float ( self . trainer . global_step + 1 ) / 500. ) for pg in optimizer . param_groups : pg [ 'lr' ] = lr_scale * self . hparams . learning_rate # update params optimizer . step () optimizer . zero_grad () on_before_zero_grad Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated. Called once per optimizer 1 2 def on_before_zero_grad ( self , optimizer ): # do something with the optimizer or inspect it. backward Called to perform backward step. Feel free to override as needed. The loss passed in has already been scaled for accumulated gradients if requested. 1 2 3 4 5 6 7 8 9 10 11 12 13 def backward ( self , use_amp , loss , optimizer ): \"\"\" Override backward with your own implementation if you need to :param use_amp: Whether amp was requested or not :param loss: Loss is already scaled by accumulated grads :param optimizer: Current optimizer being used :return: \"\"\" if use_amp : with amp . scale_loss ( loss , optimizer ) as scaled_loss : scaled_loss . backward () else : loss . backward () on_after_backward Called in the training loop after model.backward() This is the ideal place to inspect or log gradient information 1 2 3 4 5 6 7 8 def on_after_backward ( self ): # example to inspect gradient information in tensorboard if self . trainer . global_step % 25 == 0 : # don't make the tf file huge params = self . state_dict () for k , v in params . items (): grads = v name = k self . logger . experiment . add_histogram ( tag = name , values = grads , global_step = self . trainer . global_step ) tbptt_split_batch Called in the training loop after on_batch_start if truncated_bptt_steps > 0 . Each returned batch split is passed separately to training_step(...). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def tbptt_split_batch ( self , batch , split_size ): splits = [] for t in range ( 0 , time_dims [ 0 ], split_size ): batch_split = [] for i , x in enumerate ( batch ): if isinstance ( x , torch . Tensor ): split_x = x [:, t : t + split_size ] elif isinstance ( x , collections . Sequence ): split_x = [ None ] * len ( x ) for batch_idx in range ( len ( x )): split_x [ batch_idx ] = x [ batch_idx ][ t : t + split_size ] batch_split . append ( split_x ) splits . append ( batch_split ) return splits configure_apex Overwrite to define your own Apex implementation init. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def configure_apex ( self , amp , model , optimizers , amp_level ): \"\"\" Override to init AMP your own way Must return a model and list of optimizers :param amp: :param model: :param optimizers: :param amp_level: :return: Apex wrapped model and optimizers \"\"\" model , optimizers = amp . initialize ( model , optimizers , opt_level = amp_level , ) return model , optimizers configure_ddp Overwrite to define your own DDP implementation init. The only requirement is that: 1. On a validation batch the call goes to model.validation_step. 2. On a training batch the call goes to model.training_step. 3. On a testing batch, the call goes to model.test_step 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def configure_ddp ( self , model , device_ids ): \"\"\" Override to init DDP in a different way or use your own wrapper. Must return model. :param model: :param device_ids: :return: DDP wrapped model \"\"\" # Lightning DDP simply routes to test_step, val_step, etc... model = LightningDistributedDataParallel ( model , device_ids = device_ids , find_unused_parameters = True ) return model init_ddp_connection Override to init DDP in your own way. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def init_ddp_connection ( self ): \"\"\" Connect all procs in the world using the env:// init Use the first node as the root address \"\"\" # use slurm job id for the port number # guarantees unique ports across jobs from same grid search try : # use the last 4 numbers in the job id as the id default_port = os . environ [ 'SLURM_JOB_ID' ] default_port = default_port [ - 4 :] # all ports should be in the 10k+ range default_port = int ( default_port ) + 15000 except Exception as e : default_port = 12910 # if user gave a port number, use that one instead try : default_port = os . environ [ 'MASTER_PORT' ] except Exception : os . environ [ 'MASTER_PORT' ] = str ( default_port ) # figure out the root node addr try : root_node = os . environ [ 'SLURM_NODELIST' ] . split ( ' ' )[ 0 ] except Exception : root_node = '127.0.0.2' root_node = self . trainer . resolve_root_node_address ( root_node ) os . environ [ 'MASTER_ADDR' ] = root_node dist . init_process_group ( 'nccl' , rank = self . proc_rank , world_size = self . world_size )","title":"Hooks"},{"location":"Trainer/hooks/#hooks","text":"[ Github Code ] There are cases when you might want to do something different at different parts of the training/validation loop. To enable a hook, simply override the method in your LightningModule and the trainer will call it at the correct time. Contributing If there's a hook you'd like to add, simply: 1. Fork PyTorchLightning. 2. Add the hook here . 3. Add the correct place in the Trainer where it should be called.","title":"Hooks"},{"location":"Trainer/hooks/#on_epoch_start","text":"Called in the training loop at the very beginning of the epoch. 1 2 def on_epoch_start ( self ): # do something when the epoch starts","title":"on_epoch_start"},{"location":"Trainer/hooks/#on_epoch_end","text":"Called in the training loop at the very end of the epoch. 1 2 def on_epoch_end ( self ): # do something when the epoch ends","title":"on_epoch_end"},{"location":"Trainer/hooks/#on_batch_start","text":"Called in the training loop before anything happens for that batch. 1 2 def on_batch_start ( self ): # do something when the batch starts","title":"on_batch_start"},{"location":"Trainer/hooks/#on_batch_end","text":"Called in the training loop after the batch. 1 2 def on_batch_end ( self ): # do something when the batch ends","title":"on_batch_end"},{"location":"Trainer/hooks/#on_pre_performance_check","text":"Called at the very beginning of the validation loop. 1 2 def on_pre_performance_check ( self ): # do something before validation starts","title":"on_pre_performance_check"},{"location":"Trainer/hooks/#on_post_performance_check","text":"Called at the very end of the validation loop. 1 2 def on_post_performance_check ( self ): # do something before validation end","title":"on_post_performance_check"},{"location":"Trainer/hooks/#optimizer_step","text":"Calls .step() and .zero_grad for each optimizer. You can override this method to adjust how you do the optimizer step for each optimizer Called once per optimizer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # DEFAULT def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): optimizer . step () optimizer . zero_grad () # Alternating schedule for optimizer steps (ie: GANs) def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): # update generator opt every 2 steps if optimizer_i == 0 : if batch_nb % 2 == 0 : optimizer . step () optimizer . zero_grad () # update discriminator opt every 4 steps if optimizer_i == 1 : if batch_nb % 4 == 0 : optimizer . step () optimizer . zero_grad () # ... # add as many optimizers as you want This step allows you to do a lot of non-standard training tricks such as learning-rate warm-up: 1 2 3 4 5 6 7 8 9 10 11 # learning rate warm-up def optimizer_step ( self , current_epoch , batch_nb , optimizer , optimizer_i , second_order_closure = None ): # warm up lr if self . trainer . global_step < 500 : lr_scale = min ( 1. , float ( self . trainer . global_step + 1 ) / 500. ) for pg in optimizer . param_groups : pg [ 'lr' ] = lr_scale * self . hparams . learning_rate # update params optimizer . step () optimizer . zero_grad ()","title":"optimizer_step"},{"location":"Trainer/hooks/#on_before_zero_grad","text":"Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated. Called once per optimizer 1 2 def on_before_zero_grad ( self , optimizer ): # do something with the optimizer or inspect it.","title":"on_before_zero_grad"},{"location":"Trainer/hooks/#backward","text":"Called to perform backward step. Feel free to override as needed. The loss passed in has already been scaled for accumulated gradients if requested. 1 2 3 4 5 6 7 8 9 10 11 12 13 def backward ( self , use_amp , loss , optimizer ): \"\"\" Override backward with your own implementation if you need to :param use_amp: Whether amp was requested or not :param loss: Loss is already scaled by accumulated grads :param optimizer: Current optimizer being used :return: \"\"\" if use_amp : with amp . scale_loss ( loss , optimizer ) as scaled_loss : scaled_loss . backward () else : loss . backward ()","title":"backward"},{"location":"Trainer/hooks/#on_after_backward","text":"Called in the training loop after model.backward() This is the ideal place to inspect or log gradient information 1 2 3 4 5 6 7 8 def on_after_backward ( self ): # example to inspect gradient information in tensorboard if self . trainer . global_step % 25 == 0 : # don't make the tf file huge params = self . state_dict () for k , v in params . items (): grads = v name = k self . logger . experiment . add_histogram ( tag = name , values = grads , global_step = self . trainer . global_step )","title":"on_after_backward"},{"location":"Trainer/hooks/#tbptt_split_batch","text":"Called in the training loop after on_batch_start if truncated_bptt_steps > 0 . Each returned batch split is passed separately to training_step(...). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def tbptt_split_batch ( self , batch , split_size ): splits = [] for t in range ( 0 , time_dims [ 0 ], split_size ): batch_split = [] for i , x in enumerate ( batch ): if isinstance ( x , torch . Tensor ): split_x = x [:, t : t + split_size ] elif isinstance ( x , collections . Sequence ): split_x = [ None ] * len ( x ) for batch_idx in range ( len ( x )): split_x [ batch_idx ] = x [ batch_idx ][ t : t + split_size ] batch_split . append ( split_x ) splits . append ( batch_split ) return splits","title":"tbptt_split_batch"},{"location":"Trainer/hooks/#configure_apex","text":"Overwrite to define your own Apex implementation init. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def configure_apex ( self , amp , model , optimizers , amp_level ): \"\"\" Override to init AMP your own way Must return a model and list of optimizers :param amp: :param model: :param optimizers: :param amp_level: :return: Apex wrapped model and optimizers \"\"\" model , optimizers = amp . initialize ( model , optimizers , opt_level = amp_level , ) return model , optimizers","title":"configure_apex"},{"location":"Trainer/hooks/#configure_ddp","text":"Overwrite to define your own DDP implementation init. The only requirement is that: 1. On a validation batch the call goes to model.validation_step. 2. On a training batch the call goes to model.training_step. 3. On a testing batch, the call goes to model.test_step 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def configure_ddp ( self , model , device_ids ): \"\"\" Override to init DDP in a different way or use your own wrapper. Must return model. :param model: :param device_ids: :return: DDP wrapped model \"\"\" # Lightning DDP simply routes to test_step, val_step, etc... model = LightningDistributedDataParallel ( model , device_ids = device_ids , find_unused_parameters = True ) return model","title":"configure_ddp"},{"location":"Trainer/hooks/#init_ddp_connection","text":"Override to init DDP in your own way. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def init_ddp_connection ( self ): \"\"\" Connect all procs in the world using the env:// init Use the first node as the root address \"\"\" # use slurm job id for the port number # guarantees unique ports across jobs from same grid search try : # use the last 4 numbers in the job id as the id default_port = os . environ [ 'SLURM_JOB_ID' ] default_port = default_port [ - 4 :] # all ports should be in the 10k+ range default_port = int ( default_port ) + 15000 except Exception as e : default_port = 12910 # if user gave a port number, use that one instead try : default_port = os . environ [ 'MASTER_PORT' ] except Exception : os . environ [ 'MASTER_PORT' ] = str ( default_port ) # figure out the root node addr try : root_node = os . environ [ 'SLURM_NODELIST' ] . split ( ' ' )[ 0 ] except Exception : root_node = '127.0.0.2' root_node = self . trainer . resolve_root_node_address ( root_node ) os . environ [ 'MASTER_ADDR' ] = root_node dist . init_process_group ( 'nccl' , rank = self . proc_rank , world_size = self . world_size )","title":"init_ddp_connection"},{"location":"examples/Examples/","text":"Template model definition In 99% of cases you want to just copy one of the examples to start a new lightningModule and change the core of what your model is actually trying to do. 1 2 # get a copy of the module template wget https://raw.githubusercontent.com/williamFalcon/pytorch-lightning/master/pl_examples/new_project_templates/lightning_module_template.py Trainer Example __main__ function Normally, we want to let the __main__ function start the training. Inside the main we parse training arguments with whatever hyperparameters we want. Your LightningModule will have a chance to add hyperparameters. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from test_tube import HyperOptArgumentParser if __name__ == '__main__' : # use default args given by lightning root_dir = os . path . split ( os . path . dirname ( sys . modules [ '__main__' ] . __file__ ))[ 0 ] parent_parser = HyperOptArgumentParser ( strategy = 'random_search' , add_help = False ) add_default_args ( parent_parser , root_dir ) # allow model to overwrite or extend args parser = ExampleModel . add_model_specific_args ( parent_parser ) hyperparams = parser . parse_args () # train model main ( hyperparams ) Main Function The main function is your entry into the program. This is where you init your model, checkpoint directory, and launch the training. The main function should have 3 arguments: - hparams: a configuration of hyperparameters. - slurm_manager: Slurm cluster manager object (can be None) - dict: for you to return any values you want (useful in meta-learning, otherwise set to _) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def main ( hparams , cluster , results_dict ): \"\"\" Main training routine specific for this project :param hparams: :return: \"\"\" # build model model = MyLightningModule ( hparams ) # configure trainer trainer = Trainer () # train model trainer . fit ( model ) The main function will start training on your main function. If you use the HyperParameterOptimizer in hyper parameter optimization mode, this main function will get one set of hyperparameters. If you use it as a simple argument parser you get the default arguments in the argument parser. So, calling main(hyperparams) runs the model with the default argparse arguments. 1 main ( hyperparams ) CPU hyperparameter search 1 2 3 4 5 6 # run a grid search over 20 hyperparameter combinations. hyperparams . optimize_parallel_cpu ( main_local , nb_trials = 20 , nb_workers = 1 ) Hyperparameter search on a single or multiple GPUs 1 2 3 4 5 6 7 # run a grid search over 20 hyperparameter combinations. hyperparams . optimize_parallel_gpu ( main_local , nb_trials = 20 , nb_workers = 1 , gpus = [ 0 , 1 , 2 , 3 ] ) Hyperparameter search on a SLURM HPC cluster 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def optimize_on_cluster ( hyperparams ): # enable cluster training cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = hyperparams . tt_save_path , test_tube_exp_name = hyperparams . tt_name ) # email for cluster coms cluster . notify_job_status ( email = 'add_email_here' , on_done = True , on_fail = True ) # configure cluster cluster . per_experiment_nb_gpus = hyperparams . per_experiment_nb_gpus cluster . job_time = '48:00:00' cluster . gpu_type = '1080ti' cluster . memory_mb_per_node = 48000 # any modules for code to run in env cluster . add_command ( 'source activate pytorch_lightning' ) # name of exp job_display_name = hyperparams . tt_name . split ( '_' )[ 0 ] job_display_name = job_display_name [ 0 : 3 ] # run hopt logging . info ( 'submitting jobs...' ) cluster . optimize_parallel_cluster_gpu ( main , nb_trials = hyperparams . nb_hopt_trials , job_name = job_display_name ) # run cluster hyperparameter search optimize_on_cluster ( hyperparams )","title":"Examples"},{"location":"examples/Examples/#template-model-definition","text":"In 99% of cases you want to just copy one of the examples to start a new lightningModule and change the core of what your model is actually trying to do. 1 2 # get a copy of the module template wget https://raw.githubusercontent.com/williamFalcon/pytorch-lightning/master/pl_examples/new_project_templates/lightning_module_template.py","title":"Template model definition"},{"location":"examples/Examples/#trainer-example","text":"__main__ function Normally, we want to let the __main__ function start the training. Inside the main we parse training arguments with whatever hyperparameters we want. Your LightningModule will have a chance to add hyperparameters. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from test_tube import HyperOptArgumentParser if __name__ == '__main__' : # use default args given by lightning root_dir = os . path . split ( os . path . dirname ( sys . modules [ '__main__' ] . __file__ ))[ 0 ] parent_parser = HyperOptArgumentParser ( strategy = 'random_search' , add_help = False ) add_default_args ( parent_parser , root_dir ) # allow model to overwrite or extend args parser = ExampleModel . add_model_specific_args ( parent_parser ) hyperparams = parser . parse_args () # train model main ( hyperparams ) Main Function The main function is your entry into the program. This is where you init your model, checkpoint directory, and launch the training. The main function should have 3 arguments: - hparams: a configuration of hyperparameters. - slurm_manager: Slurm cluster manager object (can be None) - dict: for you to return any values you want (useful in meta-learning, otherwise set to _) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def main ( hparams , cluster , results_dict ): \"\"\" Main training routine specific for this project :param hparams: :return: \"\"\" # build model model = MyLightningModule ( hparams ) # configure trainer trainer = Trainer () # train model trainer . fit ( model ) The main function will start training on your main function. If you use the HyperParameterOptimizer in hyper parameter optimization mode, this main function will get one set of hyperparameters. If you use it as a simple argument parser you get the default arguments in the argument parser. So, calling main(hyperparams) runs the model with the default argparse arguments. 1 main ( hyperparams )","title":"Trainer Example"},{"location":"examples/Examples/#cpu-hyperparameter-search","text":"1 2 3 4 5 6 # run a grid search over 20 hyperparameter combinations. hyperparams . optimize_parallel_cpu ( main_local , nb_trials = 20 , nb_workers = 1 )","title":"CPU hyperparameter search"},{"location":"examples/Examples/#hyperparameter-search-on-a-single-or-multiple-gpus","text":"1 2 3 4 5 6 7 # run a grid search over 20 hyperparameter combinations. hyperparams . optimize_parallel_gpu ( main_local , nb_trials = 20 , nb_workers = 1 , gpus = [ 0 , 1 , 2 , 3 ] )","title":"Hyperparameter search on a single or multiple GPUs"},{"location":"examples/Examples/#hyperparameter-search-on-a-slurm-hpc-cluster","text":"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def optimize_on_cluster ( hyperparams ): # enable cluster training cluster = SlurmCluster ( hyperparam_optimizer = hyperparams , log_path = hyperparams . tt_save_path , test_tube_exp_name = hyperparams . tt_name ) # email for cluster coms cluster . notify_job_status ( email = 'add_email_here' , on_done = True , on_fail = True ) # configure cluster cluster . per_experiment_nb_gpus = hyperparams . per_experiment_nb_gpus cluster . job_time = '48:00:00' cluster . gpu_type = '1080ti' cluster . memory_mb_per_node = 48000 # any modules for code to run in env cluster . add_command ( 'source activate pytorch_lightning' ) # name of exp job_display_name = hyperparams . tt_name . split ( '_' )[ 0 ] job_display_name = job_display_name [ 0 : 3 ] # run hopt logging . info ( 'submitting jobs...' ) cluster . optimize_parallel_cluster_gpu ( main , nb_trials = hyperparams . nb_hopt_trials , job_name = job_display_name ) # run cluster hyperparameter search optimize_on_cluster ( hyperparams )","title":"Hyperparameter search on a SLURM HPC cluster"}]}
\ No newline at end of file
diff --git a/sitemap.xml b/sitemap.xml
index 1ad1cb4f..c11d0ad4 100644
--- a/sitemap.xml
+++ b/sitemap.xml
@@ -2,77 +2,77 @@
None
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06dailyNone
- 2019-10-19
+ 2019-11-06daily
\ No newline at end of file
diff --git a/sitemap.xml.gz b/sitemap.xml.gz
index fa8ab0fc29d19b7e3f81ab2306a436bc3efa5da4..4c55d0e5aad620fdc236607aaf15181f8e5f7999 100644
GIT binary patch
literal 205
zcmV;;05bm{iwFoTD8pR>|8r?{Wo=<_E_iKh0PWSi4#FT12k^a5LDpK1_SQO2kmSPDIyRkD_yH?SHtt^Q0`#E3wHA+
zs0h-q4K?gz9QPPc(}aSKY7k>U&UZM-K3xJ{LrhQwc>&UyKUg}zjFbH6tYUcXKA{M4
za4p{uT9uTRWSgGXY#ouku${Vib>*$l=E?9+vMBh=WH5sn%wPsH_#b?iwA}a$S}$g%
H3`8jl%&FZgVLElSUSXvll$>1kh6!