Package: lightning
The deep learning framework to pretrain, finetune and deploy AI models.NEW- Lightning 2.0 features a clean and stable API!!Lightning.ai•PyTorch Lightning•Fabric•Lightning Apps•Docs•Community•Contribute•Install LightningSimple installation from PyPIpipinstalllightningLightning has 3 core packagesPyTorch Lightning: Train and deploy PyTorch at scale.Lightning Fabric: Expert control.Lightning Apps: Build AI products and ML workflows.Lightning gives you granular control over how much abstraction you want to add over PyTorch.PyTorch Lightning: Train and Deploy PyTorch at ScalePyTorch Lightning is just organized PyTorch - Lightning disentangles PyTorch code to decouple the science from the engineering.Hello simple model# main.py# ! pip install torchvisionimporttorch,torch.nnasnn,torch.utils.dataasdata,torchvisionastv,torch.nn.functionalasFimportlightningasL# --------------------------------# Step 1: Define a LightningModule# --------------------------------# A LightningModule (nn.Module subclass) defines a full *system*# (ie: an LLM, diffusion model, autoencoder, or simple image classifier).classLitAutoEncoder(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))defforward(self,x):# in lightning, forward defines the prediction/inference actionsembedding=self.encoder(x)returnembeddingdeftraining_step(self,batch,batch_idx):# training_step defines the train loop. It is independent of forwardx,y=batchx=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)returnlossdefconfigure_optimizers(self):optimizer=torch.optim.Adam(self.parameters(),lr=1e-3)returnoptimizer# -------------------# Step 2: Define data# -------------------dataset=tv.datasets.MNIST(".",download=True,transform=tv.transforms.ToTensor())train,val=data.random_split(dataset,[55000,5000])# -------------------# Step 3: Train# -------------------autoencoder=LitAutoEncoder()trainer=L.Trainer()trainer.fit(autoencoder,data.DataLoader(train),data.DataLoader(val))Run the model on your terminalpipinstalltorchvision
pythonmain.pyAdvanced featuresLightning has over40+ advanced featuresdesigned for professional AI research at scale.Here are some examples:Train on 1000s of GPUs without code changes# 8 GPUs# no code changes neededtrainer=Trainer(accelerator="gpu",devices=8)# 256 GPUstrainer=Trainer(accelerator="gpu",devices=8,num_nodes=32)Train on other accelerators like TPUs without code changes# no code changes neededtrainer=Trainer(accelerator="tpu",devices=8)16-bit precision# no code changes neededtrainer=Trainer(precision=16)Experiment managersfromlightningimportloggers# tensorboardtrainer=Trainer(logger=TensorBoardLogger("logs/"))# weights and biasestrainer=Trainer(logger=loggers.WandbLogger())# comettrainer=Trainer(logger=loggers.CometLogger())# mlflowtrainer=Trainer(logger=loggers.MLFlowLogger())# neptunetrainer=Trainer(logger=loggers.NeptuneLogger())# ... and dozens moreEarly Stoppinges=EarlyStopping(monitor="val_loss")trainer=Trainer(callbacks=[es])Checkpointingcheckpointing=ModelCheckpoint(monitor="val_loss")trainer=Trainer(callbacks=[checkpointing])Export to torchscript (JIT) (production use)# torchscriptautoencoder=LitAutoEncoder()torch.jit.save(autoencoder.to_torchscript(),"model.pt")Export to ONNX (production use)# onnxwithtempfile.NamedTemporaryFile(suffix=".onnx",delete=False)astmpfile:autoencoder=LitAutoEncoder()input_sample=torch.randn((1,64))autoencoder.to_onnx(tmpfile.name,input_sample,export_params=True)os.path.isfile(tmpfile.name)Advantages over unstructured PyTorchModels become hardware agnosticCode is clear to read because engineering code is abstracted awayEasier to reproduceMake fewer mistakes because lightning handles the tricky engineeringKeeps all the flexibility (LightningModules are still PyTorch modules), but removes a ton of boilerplateLightning has dozens of integrations with popular machine learning tools.Tested rigorously with every new PR. We test every combination of PyTorch and Python supported versions, every OS, multi GPUs and even TPUs.Minimal running speed overhead (about 300 ms per epoch compared with pure PyTorch).Read the PyTorch Lightning docsLightning Fabric: Expert control.Run on any device at any scale with expert-level control over PyTorch training loop and scaling strategy. You can even write your own Trainer.Fabric is designed for the most complex models like foundation model scaling, LLMs, diffusion, transformers, reinforcement learning, active learning. Of any size.What to changeResulting Fabric Code (copy me!)+ import lightning as Limport torch; import torchvision as tvdataset = tv.datasets.CIFAR10("data", download=True,train=True,transform=tv.transforms.ToTensor())+ fabric = L.Fabric()+ fabric.launch()model = tv.models.resnet18()optimizer = torch.optim.SGD(model.parameters(), lr=0.001)- device = "cuda" if torch.cuda.is_available() else "cpu"- model.to(device)+ model, optimizer = fabric.setup(model, optimizer)dataloader = torch.utils.data.DataLoader(dataset, batch_size=8)+ dataloader = fabric.setup_dataloaders(dataloader)model.train()num_epochs = 10for epoch in range(num_epochs):for batch in dataloader:inputs, labels = batch-         inputs, labels = inputs.to(device), labels.to(device)optimizer.zero_grad()outputs = model(inputs)loss = torch.nn.functional.cross_entropy(outputs, labels)-         loss.backward()+         fabric.backward(loss)optimizer.step()print(loss.data)importlightningasLimporttorch;importtorchvisionastvdataset=tv.datasets.CIFAR10("data",download=True,train=True,transform=tv.transforms.ToTensor())fabric=L.Fabric()fabric.launch()model=tv.models.resnet18()optimizer=torch.optim.SGD(model.parameters(),lr=0.001)model,optimizer=fabric.setup(model,optimizer)dataloader=torch.utils.data.DataLoader(dataset,batch_size=8)dataloader=fabric.setup_dataloaders(dataloader)model.train()num_epochs=10forepochinrange(num_epochs):forbatchindataloader:inputs,labels=batchoptimizer.zero_grad()outputs=model(inputs)loss=torch.nn.functional.cross_entropy(outputs,labels)fabric.backward(loss)optimizer.step()print(loss.data)Key featuresEasily switch from running on CPU to GPU (Apple Silicon, CUDA, …), TPU, multi-GPU or even multi-node training# Use your available hardware# no code changes neededfabric=Fabric()# Run on GPUs (CUDA or MPS)fabric=Fabric(accelerator="gpu")# 8 GPUsfabric=Fabric(accelerator="gpu",devices=8)# 256 GPUs, multi-nodefabric=Fabric(accelerator="gpu",devices=8,num_nodes=32)# Run on TPUsfabric=Fabric(accelerator="tpu")Use state-of-the-art distributed training strategies (DDP, FSDP, DeepSpeed) and mixed precision out of the box# Use state-of-the-art distributed training techniquesfabric=Fabric(strategy="ddp")fabric=Fabric(strategy="deepspeed")fabric=Fabric(strategy="fsdp")# Switch the precisionfabric=Fabric(precision="16-mixed")fabric=Fabric(precision="64")All the device logic boilerplate is handled for you# no more of this!- model.to(device)- batch.to(device)Build your own custom Trainer using Fabric primitives for training checkpointing, logging, and moreimportlightningasLclassMyCustomTrainer:def__init__(self,accelerator="auto",strategy="auto",devices="auto",precision="32-true"):self.fabric=L.Fabric(accelerator=accelerator,strategy=strategy,devices=devices,precision=precision)deffit(self,model,optimizer,dataloader,max_epochs):self.fabric.launch()model,optimizer=self.fabric.setup(model,optimizer)dataloader=self.fabric.setup_dataloaders(dataloader)model.train()forepochinrange(max_epochs):forbatchindataloader:input,target=batchoptimizer.zero_grad()output=model(input)loss=loss_fn(output,target)self.fabric.backward(loss)optimizer.step()You can find a more extensive example in ourexamplesRead the Lightning Fabric docsLightning Apps: Build AI products and ML workflowsLightning Apps remove the cloud infrastructure boilerplate so you can focus on solving the research or business problems. Lightning Apps can run on the Lightning Cloud, your own cluster or a private cloud.Hello Lightning app world# app.pyimportlightningasLclassTrainComponent(L.LightningWork):defrun(self,x):print(f"train a model on{x}")classAnalyzeComponent(L.LightningWork):defrun(self,x):print(f"analyze model on{x}")classWorkflowOrchestrator(L.LightningFlow):def__init__(self)->None:super().__init__()self.train=TrainComponent(cloud_compute=L.CloudCompute("cpu"))self.analyze=AnalyzeComponent(cloud_compute=L.CloudCompute("gpu"))defrun(self):self.train.run("CPU machine 1")self.analyze.run("GPU machine 2")app=L.LightningApp(WorkflowOrchestrator())Run on the cloud or locally# run on the cloudlightningrunappapp.py--setup--cloud# run locallylightningrunappapp.pyRead the Lightning Apps docsExamplesSelf-supervised LearningCPC transformsMoco v2 transformsSimCLR transformsConvolutional ArchitecturesGPT-2UNetReinforcement LearningDQN LossDouble DQN LossPer DQN LossGANsBasic GANDCGANClassic MLLogistic RegressionLinear RegressionContinuous IntegrationLightning is rigorously tested across multiple CPUs, GPUs and TPUs and against major Python and PyTorch versions.*Codecov is > 90%+ but build delays may show lessCurrent build statusesSystem / PyTorch ver.1.132.02.1Linux py3.9 [GPUs]Linux py3.9 [TPUs]Linux (multiple Python versions)OSX (multiple Python versions)Windows (multiple Python versions)CommunityThe lightning community is maintained by10+ core contributorswho are all a mix of professional engineers, Research Scientists, and Ph.D. students from top AI labs.800+ community contributors.Want to help us build Lightning and reduce boilerplate for thousands of researchers?Learn how to make your first contribution hereLightning is also part of thePyTorch ecosystemwhich requires projects to have solid testing, documentation and support.Asking for helpIf you have any questions please:Read the docs.Search through existing Discussions, oradd a new questionJoin our discord.