Skip to content

Instantly share code, notes, and snippets.

@tchaton
Created August 10, 2023 11:41
Show Gist options
  • Save tchaton/5cb02da1799d5724a8a98ca4864638ba to your computer and use it in GitHub Desktop.
Save tchaton/5cb02da1799d5724a8a98ca4864638ba to your computer and use it in GitHub Desktop.
Lightning Script
# main.py
# ! pip install torchvision
import torch, torch.nn as nn, torch.utils.data as data, torchvision as tv, torch.nn.functional as F
import lightning as L
# --------------------------------
# Step 1: Define a LightningModule
# --------------------------------
# A LightningModule (nn.Module subclass) defines a full *system*
# (ie: an LLM, diffusion model, autoencoder, or simple image classifier).
class LitAutoEncoder(L.LightningModule):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(nn.Linear(28 * 28, 128), nn.ReLU(), nn.Linear(128, 3))
self.decoder = nn.Sequential(nn.Linear(3, 128), nn.ReLU(), nn.Linear(128, 28 * 28))
def forward(self, x):
# in lightning, forward defines the prediction/inference actions
embedding = self.encoder(x)
return embedding
def training_step(self, batch, batch_idx):
# training_step defines the train loop. It is independent of forward
x, y = batch
x = x.view(x.size(0), -1)
z = self.encoder(x)
x_hat = self.decoder(z)
loss = F.mse_loss(x_hat, x)
self.log("train_loss", loss)
return loss
def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
return optimizer
# -------------------
# Step 2: Define data
# -------------------
def prepare_data(self):
tv.datasets.MNIST(".", download=True)
def setup(self, stage):
dataset = tv.datasets.MNIST(".", transform=tv.transforms.ToTensor())
self.train_dataset, self.val_dataset = data.random_split(dataset, [55000, 5000])
def train_dataloader(self):
return data.DataLoader(self.train_dataset)
def val_dataloader(self):
return data.DataLoader(self.val_dataset)
# -------------------
# Step 3: Train
# -------------------
autoencoder = LitAutoEncoder()
trainer = L.Trainer()
trainer.fit(autoencoder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment