Top Related Projects
PyTorch implementation of SwAV https//arxiv.org/abs/2006.09882
SimCLRv2 - Big Self-Supervised Models are Strong Semi-Supervised Learners
solo-learn: a library of self-supervised methods for visual representation learning powered by Pytorch Lightning
Toolbox of models, callbacks, and datasets for AI/ML researchers.
Quick Overview
Lightly is an open-source Python library for self-supervised learning and active learning. It provides tools for efficient dataset curation, model training, and data selection, with a focus on computer vision tasks. Lightly aims to help developers and researchers build better machine learning models with less labeled data.
Pros
- Offers a wide range of self-supervised learning methods and active learning strategies
- Integrates well with popular deep learning frameworks like PyTorch
- Provides both a high-level API and low-level components for flexibility
- Includes a web app for easy dataset exploration and curation
Cons
- Primarily focused on computer vision tasks, limiting its applicability to other domains
- May have a steeper learning curve for users new to self-supervised learning concepts
- Documentation could be more comprehensive for some advanced features
- Performance may vary depending on the specific use case and dataset
Code Examples
- Creating a self-supervised model:
from lightly import loss, models
from torch import nn
# Create a SimCLR model
backbone = models.ResNet18()
model = models.SimCLR(backbone, num_ftrs=512, out_dim=128)
# Define the loss function
criterion = loss.NTXentLoss()
- Training a self-supervised model:
from lightly.data import LightlyDataset
from lightly.models.utils import update_momentum
from torch.utils.data import DataLoader
# Create dataset and dataloader
dataset = LightlyDataset(input_dir='path/to/dataset')
dataloader = DataLoader(dataset, batch_size=256, shuffle=True)
# Train the model
for epoch in range(100):
for (x0, x1), _, _ in dataloader:
z0 = model(x0)
z1 = model(x1)
loss = criterion(z0, z1)
loss.backward()
optimizer.step()
optimizer.zero_grad()
- Performing active learning:
from lightly.active_learning.agents import ActiveLearningAgent
from lightly.active_learning.config import ActiveLearningConfig
from lightly.active_learning.scorers import ScorerClassification
# Create an active learning agent
config = ActiveLearningConfig(n_samples=100, method='entropy')
scorer = ScorerClassification(model, device='cuda')
agent = ActiveLearningAgent(config, scorer)
# Select samples for labeling
selected_samples = agent.query(dataset)
Getting Started
To get started with Lightly, install it using pip:
pip install lightly
Then, import the necessary modules and create a simple self-supervised learning pipeline:
import torch
from lightly import loss, models
from lightly.data import LightlyDataset
from torch.utils.data import DataLoader
# Create a SimCLR model
backbone = models.ResNet18()
model = models.SimCLR(backbone, num_ftrs=512, out_dim=128)
# Define the loss function and optimizer
criterion = loss.NTXentLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
# Create dataset and dataloader
dataset = LightlyDataset(input_dir='path/to/dataset')
dataloader = DataLoader(dataset, batch_size=256, shuffle=True)
# Train the model
model.train()
for epoch in range(10):
for (x0, x1), _, _ in dataloader:
z0 = model(x0)
z1 = model(x1)
loss = criterion(z0, z1)
loss.backward()
optimizer.step()
optimizer.zero_grad()
This example sets up a basic SimCLR model and trains it on your dataset for 10 epochs.
Competitor Comparisons
PyTorch implementation of SwAV https//arxiv.org/abs/2006.09882
Pros of SwAV
- Implements a state-of-the-art self-supervised learning method for computer vision
- Provides pre-trained models and extensive documentation for reproducibility
- Designed for large-scale distributed training on multiple GPUs
Cons of SwAV
- Focused solely on the SwAV algorithm, offering less flexibility for other approaches
- Requires more computational resources and expertise to run effectively
- Less user-friendly for beginners or those seeking a quick implementation
Code Comparison
SwAV:
loss = swav_loss(output, queue, args)
loss.backward()
optimizer.step()
Lightly:
model = lightly.models.SimCLR(backbone)
criterion = lightly.loss.NTXentLoss()
loss = criterion(out0, out1)
Summary
SwAV is a specialized repository for the SwAV self-supervised learning algorithm, offering high-performance implementations and pre-trained models. Lightly, on the other hand, provides a more versatile toolkit for various self-supervised learning methods, with a focus on ease of use and integration. While SwAV may be preferred for cutting-edge research and large-scale projects, Lightly is more suitable for quick experimentation and smaller-scale applications.
SimCLRv2 - Big Self-Supervised Models are Strong Semi-Supervised Learners
Pros of SimCLR
- Developed by Google Research, backed by extensive resources and expertise
- Focuses specifically on contrastive learning for visual representations
- Provides detailed implementation of the SimCLR algorithm
Cons of SimCLR
- Less user-friendly, primarily aimed at researchers and advanced practitioners
- Limited to SimCLR algorithm, less versatile for other self-supervised learning approaches
- Requires more setup and configuration compared to Lightly
Code Comparison
SimCLR:
# Define the contrastive loss function
def nt_xent_loss(hidden1, hidden2, temperature):
# Implementation of NT-Xent loss
pass
# Training loop
for epoch in range(num_epochs):
for batch in data_loader:
loss = nt_xent_loss(model(batch), model(augment(batch)), temperature)
loss.backward()
optimizer.step()
Lightly:
# Define a self-supervised model
model = lightly.models.SimCLR(backbone)
# Create a dataloader for self-supervised learning
dataloader = lightly.data.SimCLRDataLoader(dataset)
# Train the model
for epoch in range(num_epochs):
for (x0, x1), _, _ in dataloader:
loss = criterion(model(x0), model(x1))
loss.backward()
optimizer.step()
solo-learn: a library of self-supervised methods for visual representation learning powered by Pytorch Lightning
Pros of solo-learn
- Focuses specifically on self-supervised learning methods
- Includes a wider variety of self-supervised algorithms
- More active development and frequent updates
Cons of solo-learn
- Less comprehensive documentation compared to Lightly
- Lacks some of the data management and curation features of Lightly
- May have a steeper learning curve for beginners
Code Comparison
solo-learn example:
from solo.methods import SimCLR
model = SimCLR(backbone, num_classes, proj_hidden_dim=2048, proj_output_dim=128)
Lightly example:
from lightly.models import SimCLR
model = SimCLR(backbone, num_ftrs=2048, out_dim=128)
Both libraries offer similar functionality for implementing self-supervised learning methods, but solo-learn provides more options and flexibility in algorithm selection. Lightly, on the other hand, offers a more user-friendly interface and additional tools for data handling and curation. The choice between the two depends on the specific needs of the project and the user's experience level with self-supervised learning techniques.
Toolbox of models, callbacks, and datasets for AI/ML researchers.
Pros of lightning-bolts
- Broader scope, covering various ML tasks beyond self-supervised learning
- Tighter integration with PyTorch Lightning ecosystem
- More extensive collection of pre-implemented models and techniques
Cons of lightning-bolts
- Less focused on self-supervised and semi-supervised learning
- May have a steeper learning curve for users not familiar with PyTorch Lightning
- Potentially more complex setup for simple self-supervised learning tasks
Code Comparison
lightly:
from lightly.models import SimCLR
from lightly.loss import NTXentLoss
model = SimCLR()
criterion = NTXentLoss()
lightning-bolts:
from pl_bolts.models.self_supervised import SimCLR
from pl_bolts.models.self_supervised.simclr.simclr_module import SimCLRTrainDataTransform
model = SimCLR(num_samples=args.num_samples, batch_size=args.batch_size)
train_transform = SimCLRTrainDataTransform(input_height=args.image_size)
Both repositories provide implementations for self-supervised learning techniques, but lightning-bolts offers a wider range of ML tools and models. lightly focuses more specifically on self-supervised and semi-supervised learning, potentially offering a more streamlined experience for these tasks. The code examples show that both libraries provide similar functionality, but with slightly different approaches to implementation and configuration.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
LightlySSL is a computer vision framework for self-supervised learning.
- Documentation
- Github
- Discord (We have weekly paper sessions!)
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:
- Modular framework, which exposes low-level building blocks such as loss functions and model heads.
- Easy to use and written in a PyTorch like style.
- Supports custom backbone models for self-supervised pre-training.
- Support for distributed training using PyTorch Lightning.
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:
- AIM, 2024 paper docs
- Barlow Twins, 2021 paper docs
- BYOL, 2020 paper docs
- DCL & DCLW, 2021 paper docs
- DenseCL, 2021 paper docs
- DINO, 2021 paper docs
- MAE, 2021 paper docs
- MSN, 2022 paper docs
- MoCo, 2019 paper docs
- NNCLR, 2021 paper docs
- PMSN, 2022 paper docs
- SimCLR, 2020 paper docs
- SimMIM, 2021 paper docs
- SimSiam, 2021 paper docs
- SMoG, 2022 paper docs
- SwaV, 2020 paper docs
- TiCo, 2022 paper docs
- VICReg, 2022 paper docs
- VICRegL, 2022 paper docs
Tutorials
Want to jump to the tutorials and see Lightly in action?
- Train MoCo on CIFAR-10
- Train SimCLR on Clothing Data
- Train SimSiam on Satellite Images
- Use Lightly with Custom Augmentations
- Pre-train a Detectron2 Backbone with Lightly
- Finetuning Lightly Checkpoints
- Using timm Models as Backbones
Community and partner projects:
Quick Start
Lightly requires Python 3.7+. We recommend installing Lightly in a Linux or OSX environment. Python 3.12 is not yet supported, as PyTorch itself lacks Python 3.12 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:
- PyTorch>=1.11.0
- Torchvision>=0.12.0
- PyTorch Lightning>=1.7.1
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 that you install Lightly in a dedicated virtualenv, to avoid conflicting 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 different 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
Note: Evaluation settings are based on these papers:
See the benchmarking scripts for details.
Model | Backbone | Batch Size | Epochs | Linear Top1 | Finetune Top1 | kNN Top1 | Tensorboard | Checkpoint |
---|---|---|---|---|---|---|---|---|
BarlowTwins | Res50 | 256 | 100 | 62.9 | 72.6 | 45.6 | link | link |
BYOL | Res50 | 256 | 100 | 62.5 | 74.5 | 46.0 | link | link |
DINO | Res50 | 128 | 100 | 68.2 | 72.5 | 49.9 | link | link |
MAE | ViT-B/16 | 256 | 100 | 46.0 | 81.3 | 11.2 | link | link |
MoCoV2 | Res50 | 256 | 100 | 61.5 | 74.3 | 41.8 | link | link |
SimCLR* | Res50 | 256 | 100 | 63.2 | 73.9 | 44.8 | link | link |
SimCLR* + DCL | Res50 | 256 | 100 | 65.1 | 73.5 | 49.6 | link | link |
SimCLR* + DCLW | Res50 | 256 | 100 | 64.5 | 73.2 | 48.5 | link | link |
SwAV | Res50 | 256 | 100 | 67.2 | 75.4 | 49.5 | link | link |
TiCo | Res50 | 256 | 100 | 49.7 | 72.7 | 26.6 | link | link |
VICReg | Res50 | 256 | 100 | 63.0 | 73.7 | 46.3 | link | link |
*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.
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:
- Have a look at our #papers channel on discord for the newest self-supervised learning papers.
- A Cookbook of Self-Supervised Learning, 2023
- Masked Autoencoders Are Scalable Vision Learners, 2021
- Emerging Properties in Self-Supervised Vision Transformers, 2021
- Unsupervised Learning of Visual Features by Contrasting Cluster Assignments, 2021
- What Should Not Be Contrastive in Contrastive Learning, 2020
- A Simple Framework for Contrastive Learning of Visual Representations, 2020
- Momentum Contrast for Unsupervised Visual Representation Learning, 2020
FAQ
-
Why should I care about self-supervised learning? Aren't pre-trained models from ImageNet much better for transfer learning?
- Self-supervised learning has become increasingly popular among scientists over the last years because the learned representations perform extraordinarily well on downstream tasks. This means that they capture the important information in an image better than other types of pre-trained models. By training a self-supervised model on your dataset, you can make sure that the representations have all the necessary information about your images.
-
How can I contribute?
- Create an issue if you encounter bugs or have ideas for features we should implement. You can also add your own code by forking this repository and creating a PR. More details about how to contribute with code is in our contribution guide.
-
Is this framework for free?
- Yes, this framework is completely free to use and we provide the source code. We believe that we need to make training deep learning models more data efficient to achieve widespread adoption. One step to achieve this goal is by leveraging self-supervised learning. The company behind Lightly is committed to keep this framework open-source.
-
If this framework is free, how is the company behind Lightly making money?
- Training self-supervised models is only one part of our solution. The company behind Lightly focuses on processing and analyzing embeddings created by self-supervised models. By building, what we call a self-supervised active learning loop we help companies understand and work with their data more efficiently. As the Lightly Solution is a freemium product, you can try it out for free. However, we will charge for some features.
- In any case this framework will always be free to use, even for commercial purposes.
Lightly in Research
- Reverse Engineering Self-Supervised Learning, 2023
- Learning Visual Representations via Language-Guided Sampling, 2023
- Self-Supervised Learning Methods for Label-Efficient Dental Caries Classification, 2022
- DPCL: Constrative Representation Learning with Differential Privacy, 2022
- Decoupled Contrastive Learning, 2021
- solo-learn: A Library of Self-supervised Methods for Visual Representation Learning, 2021
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:
Top Related Projects
PyTorch implementation of SwAV https//arxiv.org/abs/2006.09882
SimCLRv2 - Big Self-Supervised Models are Strong Semi-Supervised Learners
solo-learn: a library of self-supervised methods for visual representation learning powered by Pytorch Lightning
Toolbox of models, callbacks, and datasets for AI/ML researchers.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot