Package: lightning-fabric
Fabric is the fast and lightweight way to scale PyTorch models without boilerplateWebsite•Docs•Getting started•FAQ•Help•DiscordLightning 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()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()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 docsContinuous IntegrationLightning is rigorously tested across multiple CPUs and GPUs and against major Python and PyTorch versions.*Codecov is > 90%+ but build delays may show lessCurrent build statusesSystem / PyTorch ver.1.121.132.02.1Linux py3.9 [GPUs]Linux (multiple Python versions)OSX (multiple Python versions)Windows (multiple Python versions)Getting startedInstall LightningPrerequisitesTIP: We strongly recommend creating a virtual environment first.
Don’t know what this is? Follow ourbeginner guide here.Python 3.8.x or later (3.8.x, 3.9.x, 3.10.x, ...)pipinstall-UlightningConvert your PyTorch to FabricCreate theFabricobject at the beginning of your training code.import Lightning as L

fabric = L.Fabric()Callsetup()on each model and optimizer pair andsetup_dataloaders()on all your data loaders.model, optimizer = fabric.setup(model, optimizer)
dataloader = fabric.setup_dataloaders(dataloader)Remove all.toand.cudacalls -> Fabric will take care of it.- model.to(device)- batch.to(device)Replaceloss.backward()byfabric.backward(loss).- loss.backward()+ fabric.backward(loss)Run the script from the terminal withlightningrunmodelpath/to/train.pyor use the launch() method in a notebook. Learn more aboutlaunching distributed training.FAQWhen to use Fabric?Minimum code changes- You want to scale your PyTorch model to use multi-GPU or use advanced strategies like DeepSpeed without having to refactor. You don’t care about structuring your code- you just want to scale it as fast as possible.Maximum control- Write your own training and/or inference logic down to the individual optimizer calls. You aren’t forced to conform to a standardized epoch-based training loop like the one in Lightning Trainer. You can do flexible iteration based training, meta-learning, cross-validation and other types of optimization algorithms without digging into framework internals. This also makes it super easy to adopt Fabric in existing PyTorch projects to speed-up and scale your models without the compromise on large refactors. Just remember: With great power comes a great responsibility.Maximum flexibility- You want to have full control over your entire training- in Fabric all features are opt-in, and it provides you with a tool box of primitives so you can build your own Trainer.When to use theLightning Trainer?You want to have all the engineering boilerplate handled for you - dozens of features like checkpointing, logging and early stopping out of the box. Less hassle, less error prone, easy to try different techniques and features.You want to have good defaults chosen for you - so you can have a better starting point.You want your code to be modular, readable and well structured - easy to share between projects and with collaborators.Can I use Fabric with my LightningModule or Lightning Callback?Yes :) Fabric works with PyTorch LightningModules and Callbacks, so you can choose how to structure your code and reuse existing models and callbacks as you wish. Read morehere.ExamplesGANMeta learningReinforcement learningK-Fold cross validationAsking for helpIf you have any questions please:Read the docs.Ask a question in our forum.Join our discord community.