Home

Awesome

<a name="top"></a> LightlySSL self-supervised learning Logo

GitHub Unit Tests PyPI Downloads Code style: black Discord

LightlySSL is a computer vision framework for self-supervised learning.

For a commercial version with more features, including Docker support and pretraining models for embedding, classification, detection, and segmentation tasks with a single command, please contact sales@lightly.ai.

We've also built a whole platform on top, with additional features for active learning and data curation. If you're interested in the Lightly Worker Solution to easily process millions of samples and run powerful algorithms on your data, check out lightly.ai. It's free to get started!

Features

This self-supervised learning framework offers the following features:

Supported Models

You can find sample code for all the supported models here. We provide PyTorch, PyTorch Lightning, and PyTorch Lightning distributed examples for all models to kickstart your project.

Models:

ModelYearPaperDocsColab (PyTorch)Colab (PyTorch Lightning)
AIM2024paperdocsOpen In ColabOpen In Colab
Barlow Twins2021paperdocsOpen In ColabOpen In Colab
BYOL2020paperdocsOpen In ColabOpen In Colab
DCL & DCLW2021paperdocsOpen In ColabOpen In Colab
DenseCL2021paperdocsOpen In ColabOpen In Colab
DINO2021paperdocsOpen In ColabOpen In Colab
MAE2021paperdocsOpen In ColabOpen In Colab
MSN2022paperdocsOpen In ColabOpen In Colab
MoCo2019paperdocsOpen In ColabOpen In Colab
NNCLR2021paperdocsOpen In ColabOpen In Colab
PMSN2022paperdocsOpen In ColabOpen In Colab
SimCLR2020paperdocsOpen In ColabOpen In Colab
SimMIM2022paperdocsOpen In ColabOpen In Colab
SimSiam2021paperdocsOpen In ColabOpen In Colab
SwaV2020paperdocsOpen In ColabOpen In Colab
VICReg2021paperdocsOpen In ColabOpen In Colab

Tutorials

Want to jump to the tutorials and see Lightly in action?

Community and partner projects:

Quick Start

Lightly requires Python 3.7+. We recommend installing Lightly in a Linux or OSX environment. Python 3.13 is not yet supported, as PyTorch itself lacks Python 3.13 compatibility.

Dependencies

Due to the modular nature of the Lightly package some modules can be used with older versions of dependencies. However, to use all features as of today lightly requires the following dependencies:

Lightly is compatible with PyTorch and PyTorch Lightning v2.0+!

Installation

You can install Lightly and its dependencies from PyPI with:

pip3 install lightly

We strongly recommend installing Lightly in a dedicated virtualenv to avoid conflicts with your system packages.

Lightly in Action

With Lightly, you can use the latest self-supervised learning methods in a modular way using the full power of PyTorch. Experiment with various backbones, models, and loss functions. The framework has been designed to be easy to use from the ground up. Find more examples in our docs.

import torch
import torchvision

from lightly import loss
from lightly import transforms
from lightly.data import LightlyDataset
from lightly.models.modules import heads


# Create a PyTorch module for the SimCLR model.
class SimCLR(torch.nn.Module):
    def __init__(self, backbone):
        super().__init__()
        self.backbone = backbone
        self.projection_head = heads.SimCLRProjectionHead(
            input_dim=512,  # Resnet18 features have 512 dimensions.
            hidden_dim=512,
            output_dim=128,
        )

    def forward(self, x):
        features = self.backbone(x).flatten(start_dim=1)
        z = self.projection_head(features)
        return z


# Use a resnet backbone from torchvision.
backbone = torchvision.models.resnet18()
# Ignore the classification head as we only want the features.
backbone.fc = torch.nn.Identity()

# Build the SimCLR model.
model = SimCLR(backbone)

# Prepare transform that creates multiple random views for every image.
transform = transforms.SimCLRTransform(input_size=32, cj_prob=0.5)


# Create a dataset from your image folder.
dataset = LightlyDataset(input_dir="./my/cute/cats/dataset/", transform=transform)

# Build a PyTorch dataloader.
dataloader = torch.utils.data.DataLoader(
    dataset,  # Pass the dataset to the dataloader.
    batch_size=128,  # A large batch size helps with the learning.
    shuffle=True,  # Shuffling is important!
)

# Lightly exposes building blocks such as loss functions.
criterion = loss.NTXentLoss(temperature=0.5)

# Get a PyTorch optimizer.
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, weight_decay=1e-6)

# Train the model.
for epoch in range(10):
    for (view0, view1), targets, filenames in dataloader:
        z0 = model(view0)
        z1 = model(view1)
        loss = criterion(z0, z1)
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()
        print(f"loss: {loss.item():.5f}")

You can easily use another model like SimSiam by swapping the model and the loss function.

# PyTorch module for the SimSiam model.
class SimSiam(torch.nn.Module):
    def __init__(self, backbone):
        super().__init__()
        self.backbone = backbone
        self.projection_head = heads.SimSiamProjectionHead(512, 512, 128)
        self.prediction_head = heads.SimSiamPredictionHead(128, 64, 128)

    def forward(self, x):
        features = self.backbone(x).flatten(start_dim=1)
        z = self.projection_head(features)
        p = self.prediction_head(z)
        z = z.detach()
        return z, p


model = SimSiam(backbone)

# Use the SimSiam loss function.
criterion = loss.NegativeCosineSimilarity()

You can find a more complete example for SimSiam here.

Use PyTorch Lightning to train the model:

from pytorch_lightning import LightningModule, Trainer

class SimCLR(LightningModule):
    def __init__(self):
        super().__init__()
        resnet = torchvision.models.resnet18()
        resnet.fc = torch.nn.Identity()
        self.backbone = resnet
        self.projection_head = heads.SimCLRProjectionHead(512, 512, 128)
        self.criterion = loss.NTXentLoss()

    def forward(self, x):
        features = self.backbone(x).flatten(start_dim=1)
        z = self.projection_head(features)
        return z

    def training_step(self, batch, batch_index):
        (view0, view1), _, _ = batch
        z0 = self.forward(view0)
        z1 = self.forward(view1)
        loss = self.criterion(z0, z1)
        return loss

    def configure_optimizers(self):
        optim = torch.optim.SGD(self.parameters(), lr=0.06)
        return optim


model = SimCLR()
trainer = Trainer(max_epochs=10, devices=1, accelerator="gpu")
trainer.fit(model, dataloader)

See our docs for a full PyTorch Lightning example.

Or train the model on 4 GPUs:


# Use distributed version of loss functions.
criterion = loss.NTXentLoss(gather_distributed=True)

trainer = Trainer(
    max_epochs=10,
    devices=4,
    accelerator="gpu",
    strategy="ddp",
    sync_batchnorm=True,
    use_distributed_sampler=True,  # or replace_sampler_ddp=True for PyTorch Lightning <2.0
)
trainer.fit(model, dataloader)

We provide multi-GPU training examples with distributed gather and synchronized BatchNorm. Have a look at our docs regarding distributed training.

Benchmarks

Implemented models and their performance on various datasets. Hyperparameters are not tuned for maximum accuracy. For detailed results and more information about the benchmarks click here.

ImageNet1k

ImageNet1k benchmarks

Note: Evaluation settings are based on these papers:

See the benchmarking scripts for details.

ModelBackboneBatch SizeEpochsLinear Top1Finetune Top1kNN Top1TensorboardCheckpoint
BarlowTwinsRes5025610062.972.645.6linklink
BYOLRes5025610062.574.546.0linklink
DINORes5012810068.272.549.9linklink
MAEViT-B/1625610046.081.311.2linklink
MoCoV2Res5025610061.574.341.8linklink
SimCLR*Res5025610063.273.944.8linklink
SimCLR* + DCLRes5025610065.173.549.6linklink
SimCLR* + DCLWRes5025610064.573.248.5linklink
SwAVRes5025610067.275.449.5linklink
TiCoRes5025610049.772.726.6linklink
VICRegRes5025610063.073.746.3linklink

*We use square root learning rate scaling instead of linear scaling as it yields better results for smaller batch sizes. See Appendix B.1 in the SimCLR paper.

ImageNet100

ImageNet100 benchmarks detailed results

Imagenette

Imagenette benchmarks detailed results

CIFAR-10

CIFAR-10 benchmarks detailed results

Terminology

Below you can see a schematic overview of the different concepts in the package. The terms in bold are explained in more detail in our documentation.

<img src="/docs/source/getting_started/images/lightly_overview.png" alt="Overview of the Lightly pip package"/></a>

Next Steps

Head to the documentation and see the things you can achieve with Lightly!

Development

To install dev dependencies (for example to contribute to the framework) you can use the following command:

pip3 install -e ".[dev]"

For more information about how to contribute have a look here.

Running Tests

Unit tests are within the tests directory and we recommend running them using pytest. There are two test configurations available. By default, only a subset will be run:

make test-fast

To run all tests (including the slow ones) you can use the following command:

make test

To test a specific file or directory use:

pytest <path to file or directory>

Code Formatting

To format code with black and isort run:

make format

Further Reading

Self-Supervised Learning:

FAQ

Lightly in Research

Company behind this Open Source Framework

Lightly is a spin-off from ETH Zurich that helps companies build efficient active learning pipelines to select the most relevant data for their models.

You can find out more about the company and it's services by following the links below:

Back to top🚀