Hello, everybody! Today I am going to show how you how to convert my model from Pytorch to Pytorch Lightning. Pytorch Lightning is a light-weight deep learning framework built upon Pytorch. It removes a lot of boilerplate code (standard code that can be found in almost any deep learning pipeline) and adds in many functions that helps to interfere training at a specific position.
Firstly, I import the libraries.
pip install pytorch-lightning
import pytorch_lightning as pl
Pytorch LightningModule resembles nn.Module. Forward function can be defined in a pl class.
# an nn class can be converted to a pl class by replacing nn with pl
class NeuralNet(nn.Module):
# --> class NeuralNet(pl.LightningModule):
def __init__(self, input_size, num_classes):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size, 50)
self.fc2 = nn.Linear(50, num_classes)
# --> specific functions belong to nn class should not be changed!
def forward(self, x):
out = self.fc1(x)
out = torch.sigmoid(out)
out = self.fc2(out)
return out
Pretrained models could be passed into the class through a parameter. Changes to the models such as transfer learning could be made outside.
class FruitsClassification(pl.LightningModule):
def __init__(self, model, learning_rate=0.01):
super(FruitsClassification, self).__init__()
self.model = model
Conversion of the training loop requires positional matching of the hooks with the loop.

For example, a training_step() usually consists of these lines.
def training_step(self, batch, batch_idx):
x, y = batch
y_hat = self(x)
loss = F.cross_entropy(y_hat, y)
return loss
Calculating backwards and updating weights no longer requires as they are automatically integrated under the hood. Declaration of cuda devices follow the same convention, thus can be omitted.
print(f'Epoch {epoch+1}/{num_epochs}')
print(f'Step {idx1+1}/{n_iters1}, train Loss = {epoch_loss:.2f}, train Acc = {epoch_acc:.2f}')
print(f'Step {idx2+1}/{n_iters2}, val loss = {epoch_loss_val:.2f}, val acc = {epoch_acc_val:.2f}')
Displaying loss and accuracy can be made through the callback functions belonging to the callback module.
def validation_epoch_end(self, outputs):
avg_val_loss = torch.tensor([x['val_loss'].item() for x in outputs]).mean()
avg_val_acc = torch.tensor([x['val_acc'].item() for x in outputs]).mean()
print(f'Epoch {self.current_epoch + 1} ' \
f'Val Loss: {avg_val_loss:.3f}, Val Acc: {avg_val_acc:.2f}')
self.val_loss.append(avg_val_loss.item())
self.val_acc.append(avg_val_acc.item())
if avg_val_acc.item() > self.best_acc:
self.best_acc = avg_val_acc.item()
It should be noted that Lightning considers a training loop as training and validation. Therefore, displaying metrics of pure training could be made right at the start of validation.
def on_validation_epoch_start(self, trainer, pl_module):
avg_train_loss = torch.tensor(pl_module.train_losses).mean()
avg_train_acc = torch.tensor(pl_module.train_accs).mean()
pl_module.train_loss.append(avg_train_loss.item())
pl_module.train_acc.append(avg_train_acc.item())
print(f'Epoch {pl_module.current_epoch + 1} ' \
f'Train Loss: {avg_train_loss:.3f}, Train Acc: {avg_train_acc:.2f}')
Single metrics values could be concatenated through an attribute in the lightning module. Epoch metric values could be displayed on the progress bar.
class FruitsClassification(pl.LightningModule):
def __init__(self, model, learning_rate=0.01):
super(FruitsClassification, self).__init__()
...
self.train_losses = list()
self.train_accs = list()
self.train_loss = list()
self.train_acc = list()
...
def training_step(self, batch, batch_idx):
loss, acc = self._shared_eval_step(batch, batch_idx)
self.train_losses.append(loss.item())
self.train_accs.append(acc.item())
metrics = {'loss': loss, 'train_acc': acc}
pbar = {'train_loss': loss, 'train_acc': acc}
self.log_dict(pbar, on_epoch=True, on_step=False, prog_bar=True, logger=True)
return metrics
The callback hooks could be written within the module class or separately for the sake of readability.
from pytorch_lightning.callbacks import Callback
class MyPrintingCallback(Callback):
def __init__(self, cb_dir, test_dir):
super().__init__()
self.epoch_start = None
self.start = None
...
def on_train_start(self, trainer, pl_module):
self.start = time.time()
def on_train_epoch_start(self, trainer, pl_module):
print('In training...')
self.epoch_start = time.time()
Accuracy could be calculated conveniently with a built-in function.
from torchmetrics.functional import accuracy
def _shared_eval_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = self.criterion(logits, y)
acc = accuracy(logits, y)
return loss, acc
It is very efficient to load a model either for resumed training or inference. The epoch would be continued from the last train. Specify the an already trained max_epochs would not initiate training.
checkpoint_callback = ModelCheckpoint(
monitor='val_acc',
mode='max',
every_n_train_steps=0,
every_n_epochs=1,
train_time_interval=None,
save_on_train_epoch_end=True,
save_top_k=1,
dirpath='/content/drive/MyDrive/outputs',
filename='resumed-sample-fruits-{epoch}-{val_acc:.2f}'
)
It should be noted that the callback used for saving checkpoints has the same saved folder as in training. The new checkpoint file name should be different from the old one and the file would be updated.

Metric loss and accuracy are automatically put up in Tensorboard. However, each pair of metrics either for train or validation does not come up in the same graph. Nonetheless, manual visualization could still be made through the saved parameters in the lightning module during the notebook session. It should be noted that loading those values for inference after the session requires them to be saved.
def on_train_end(self, trainer, pl_module):
self.end = time.time()
duration = self.start - self.end
print(f'Training completes in -----> {int(duration // 60)}m {int(duration % 60)}s')
print(f'Best Validation Accuracy is {pl_module.best_acc:.3f}')
torch.save({
'train_loss': pl_module.train_loss,
'train_acc': pl_module.train_acc,
'val_loss': pl_module.val_loss,
'val_acc': pl_module.val_acc,
'best_acc':pl_module.best_acc,
'targets': self.targets,
'preds': self.preds,
'absent_class': self.absent_class,
'accdict': self.accdict,
'corrects': self.corrects
}, self.path)
Bao Ca Ca
HCM 27.02.22 5:22 p.m.
GitHub Page: https://qbaocaca.github.io/fruits_clf_lightning/












