Scalable AI Models with PyTorch Lightning
Sergiy Tkachuk
Director, GenAI Productivity
import lightning.pytorch as pl
import torch.nn as nn
class ClassificationModel(pl.LightningModule):
def __init__(self, input_dim,
hidden_dim, num_class):
# Initialize parent class
super().__init__()
# First layer
self.layer1 = nn.Linear(input_dim,
hidden_dim)
# Activation function
self.relu = nn.ReLU()
# Output layer
self.layer2 = nn.Linear(hidden_dim,
num_class)
from lightning.pytorch import Trainer
from lightning.pytorch.callbacks import EarlyStopping, ModelCheckpoint
checkpoint = ModelCheckpoint(
monitor='val_accuracy',
save_top_k=2,
mode='max')
early_stopping = EarlyStopping(
monitor='val_accuracy',
patience=5,
mode='max')
import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def forward(self, x):
return x * 2
scripted_model = torch.jit.script(SimpleModel())
torch.jit.save(scripted_mod,"model.pt") # Save the model
loaded_model=torch.jit.load("model.pt") # Load the model
Scalable AI Models with PyTorch Lightning