pip install lightning★Imports asimport lightning as L. The standalonepip install pytorch-lightningstill works (import pytorch_lightning as pl).class LitModel(L.LightningModule): ...★Your model + training logic live here (the "science"). No manual.backward(),.zero_grad(),.to(device), or.eval().trainer = L.Trainer(...); trainer.fit(model, dm)★The Trainer owns the loop, devices, precision, logging & checkpoints (the "engineering").L.seed_everything(42, workers=True)Seed Python/NumPy/PyTorch (and DataLoader workers) for reproducibility.
def __init__(self): super().__init__(); self.save_hyperparameters()★save_hyperparameters()stores ctor args inself.hparamsand the checkpoint — enables clean reload.def training_step(self, batch, batch_idx): loss = ...; self.log("train_loss", loss); return loss★Define one step and return the loss — Lightning does backward + optimizer.step for you.def validation_step(self, batch, idx): ... # + test_step, predict_step★Same shape as training_step; no grad needed.predict_steppowerstrainer.predict().def forward(self, x): return self.net(x)Optional — defines whatmodel(x)does for inference. Keep training logic in the*_stephooks.on_train_epoch_end() · on_validation_epoch_end() ...Epoch-level hooks for aggregating metrics; there's a hook for nearly every point in the loop.
def configure_optimizers(self): return torch.optim.AdamW(self.parameters(), lr=self.hparams.lr)★Return an optimizer (or several). Lightning calls it after the model is on the right device.return {"optimizer": opt, "lr_scheduler": {"scheduler": sch, "monitor": "val_loss"}}Attach an LR scheduler;monitordrivesReduceLROnPlateau.interval:"step"to step per-batch.self.automatic_optimization = FalseOpt out to hand-code multiple optimizers (GANs, RL): useopt = self.optimizers(),self.manual_backward(loss),opt.step().