lightly

A python library for self-supervised learning on images.

https://github.com/lightly-ai/lightly

Science Score: 64.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
    Found CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
    Links to: arxiv.org, mdpi.com
  • Committers with academic emails
    1 of 66 committers (1.5%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (19.3%) to scientific vocabulary

Keywords

computer-vision contrastive-learning contributions-welcome deep-learning embeddings hacktoberfest machine-learning pytorch self-supervised-learning

Keywords from Contributors

optimizer transformer medical-imaging monai medical-image-processing medical-image-computing healthcare-imaging cryptocurrency multi-agents agents
Last synced: 6 months ago · JSON representation ·

Repository

A python library for self-supervised learning on images.

Basic Info
Statistics
  • Stars: 3,500
  • Watchers: 29
  • Forks: 305
  • Open Issues: 78
  • Releases: 135
Topics
computer-vision contrastive-learning contributions-welcome deep-learning embeddings hacktoberfest machine-learning pytorch self-supervised-learning
Created over 5 years ago · Last pushed 6 months ago
Metadata Files
Readme Contributing License Citation

README.md

LightlySSL self-supervised learning Logo

GitHub Unit Tests PyPI Downloads Code style: black Discord codecov.io

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!

Big News (April 15th, 2025) 🚀

We are excited to announce that you can now leverage SSL and distillation pretraining in just a few lines of code! We've worked hard to make self-supervised learning even more accessible with our new project LightlyTrain. Head over there to get started and supercharge your models! ⚡️

LightlyTrain

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:

| Model | Year | Paper | Docs | Colab (PyTorch) | Colab (PyTorch Lightning) | |----------------|------|-------|------|-----------------|----------------------------| | AIM | 2024 | paper | docs | Open In Colab | Open In Colab | | Barlow Twins | 2021 | paper | docs | Open In Colab | Open In Colab | | BYOL | 2020 | paper | docs | Open In Colab | Open In Colab | | DCL & DCLW | 2021 | paper | docs | Open In Colab | Open In Colab | | DenseCL | 2021 | paper | docs | Open In Colab | Open In Colab | | DINO | 2021 | paper | docs | Open In Colab | Open In Colab | | DINOv2 | 2023 | paper | docs | Open In Colab | Open In Colab | | iBOT | 2021 | paper | docs | Open In Colab | Open In Colab | | MAE | 2021 | paper | docs | Open In Colab | Open In Colab | | MSN | 2022 | paper | docs | Open In Colab | Open In Colab | | MoCo | 2019 | paper | docs | Open In Colab | Open In Colab | | NNCLR | 2021 | paper | docs | Open In Colab | Open In Colab | | PMSN | 2022 | paper | docs | Open In Colab | Open In Colab | | SimCLR | 2020 | paper | docs | Open In Colab | Open In Colab | | SimMIM | 2022 | paper | docs | Open In Colab | Open In Colab | | SimSiam | 2021 | paper | docs | Open In Colab | Open In Colab | | SwaV | 2020 | paper | docs | Open In Colab | Open In Colab | | VICReg | 2021 | paper | docs | Open In Colab | Open 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.

```python 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.projectionhead = heads.SimCLRProjectionHead( inputdim=512, # Resnet18 features have 512 dimensions. hiddendim=512, outputdim=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(inputsize=32, cjprob=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.

```python

PyTorch module for the SimSiam model.

class SimSiam(torch.nn.Module): def init(self, backbone): super().init() self.backbone = backbone self.projectionhead = heads.SimSiamProjectionHead(512, 512, 128) self.predictionhead = 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:

```python 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:

```python

Use distributed version of loss functions.

criterion = loss.NTXentLoss(gather_distributed=True)

trainer = Trainer( maxepochs=10, devices=4, accelerator="gpu", strategy="ddp", syncbatchnorm=True, usedistributedsampler=True, # or replacesamplerddp=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.

| 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 | | DINO | ViT-S/16 | 128 | 100 | 73.3 | 79.8 | 67.5 | link | link | | iBOT | ViT-S/16 | 128 | 100 | 72.2 | 78.3 | 65.4 | 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.

Overview of the Lightly pip package

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

  • 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

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🚀

Owner

  • Name: Lightly
  • Login: lightly-ai
  • Kind: organization
  • Email: info@lightly.ai
  • Location: Switzerland

Citation (CITATION.cff)

cff-version: 1.2.0
message: "If you use this software, please cite it as below."
authors:
  - family-names: Susmelj
    given-names: Igor
  - family-names: Heller
    given-names: Matthias
  - family-names: Wirth
    given-names: Philipp
  - family-names: Prescott
    given-names: Jeremy
  - family-names: Ebner
    given-names: Malte
  - name: "et al."
title: "Lightly"
type: software
url: "https://github.com/lightly-ai/lightly"
date-released: 2020

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 1,282
  • Total Committers: 66
  • Avg Commits per committer: 19.424
  • Development Distribution Score (DDS): 0.768
Past Year
  • Commits: 188
  • Committers: 34
  • Avg Commits per committer: 5.529
  • Development Distribution Score (DDS): 0.803
Top Committers
Name Email Commits
Philipp Wirth 6****h 298
guarin 4****n 242
IgorSusmelj i****9@h****m 211
MalteEbner m****r@g****m 194
Jeremy A. Prescott j****y@l****i 66
huan-lightly-0 1****0 33
michal-lightly 1****y 30
Shaun Daley s****9@g****m 28
Lionel Peer l****l@l****i 23
Ra1Nik n****o@l****i 21
Saurav Maheshkar s****r@g****m 16
Yutong Xiang 2****7 14
busycalibrating d****e@g****m 11
Vladislav Tumko 5****p 7
ersi-lightly 1****y 6
Adam J. Stewart a****6@g****m 5
John Sutor j****3@g****m 4
Ibrahim Hadzic i****5@g****m 4
ayush22iitbhu a****5@g****m 4
Chirag Aggarwal c****k@g****m 3
George 5****n 3
Antonios P. Sarikas 1****r 3
Radi Radev r****k@g****m 3
Snehil Chatterjee 1****e 3
Prathamesh Gawas p****7@g****m 2
Shikhar Mohan 4****n 2
Piyus Kumar Rout 3****1 2
stegmuel 3****l 2
yuki 1****e 2
Jing Zhang j****r@g****m 2
and 36 more...
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 206
  • Total pull requests: 340
  • Average time to close issues: 9 months
  • Average time to close pull requests: 2 days
  • Total issue authors: 68
  • Total pull request authors: 50
  • Average comments per issue: 2.78
  • Average comments per pull request: 1.14
  • Merged pull requests: 282
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 51
  • Pull requests: 221
  • Average time to close issues: 19 days
  • Average time to close pull requests: 2 days
  • Issue authors: 29
  • Pull request authors: 39
  • Average comments per issue: 2.94
  • Average comments per pull request: 1.29
  • Merged pull requests: 174
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • guarin (78)
  • philippmwirth (24)
  • IgorSusmelj (21)
  • MalteEbner (5)
  • JAVARSHA (4)
  • ramdhan1989 (4)
  • CharisWg (4)
  • adamjstewart (3)
  • SauravMaheshkar (3)
  • bryanbocao (2)
  • siemdejong (2)
  • 0x1orz (2)
  • hmf (2)
  • laurenmoos (2)
  • busycalibrating (2)
Pull Request Authors
  • guarin (86)
  • philippmwirth (85)
  • liopeer (51)
  • japrescott (46)
  • yutong-xiang-97 (36)
  • MalteEbner (35)
  • SauravMaheshkar (27)
  • IgorSusmelj (25)
  • vectorvp (12)
  • ishaanagw (10)
  • ersi-lightly (10)
  • ayush22iitbhu (8)
  • yvesyue (7)
  • ChiragAgg5k (6)
  • snehilchatterjee (5)
Top Labels
Issue Labels
good first issue (20) feature (14) enhancement (14) package (10) documentation (9) hacktoberfest (8) feature request (8) type: enhancement (7) type: feature (6) type: idea (6) type: documentation (6) question (2) bug (2) status: needs information (1) type: bug (1) help wanted (1)
Pull Request Labels
hacktoberfest-accepted (19) documentation (9) type: documentation (8) type: enhancement (7) enhancement (5) feature (4) type: feature (2)

Packages

  • Total packages: 3
  • Total downloads:
    • pypi 107,475 last-month
  • Total dependent packages: 7
    (may contain duplicates)
  • Total dependent repositories: 83
    (may contain duplicates)
  • Total versions: 273
  • Total maintainers: 1
pypi.org: lightly

A deep learning package for self-supervised learning

  • Homepage: https://www.lightly.ai
  • Documentation: https://docs.lightly.ai
  • License: Copyright (c) 2018 The Python Packaging Authority Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  • Latest release: 1.5.22
    published 7 months ago
  • Versions: 136
  • Dependent Packages: 6
  • Dependent Repositories: 58
  • Downloads: 59,078 Last month
  • Docker Downloads: 0
Rankings
Dependent packages count: 1.6%
Downloads: 1.8%
Dependent repos count: 1.9%
Average: 2.4%
Docker downloads count: 4.1%
Maintainers (1)
Last synced: 6 months ago
pypi.org: lightly-utils

A utility package for lightly

  • Versions: 2
  • Dependent Packages: 1
  • Dependent Repositories: 25
  • Downloads: 48,397 Last month
  • Docker Downloads: 0
Rankings
Downloads: 2.4%
Dependent repos count: 2.9%
Average: 3.6%
Docker downloads count: 4.1%
Dependent packages count: 4.8%
Maintainers (1)
Last synced: 6 months ago
proxy.golang.org: github.com/lightly-ai/lightly
  • Versions: 135
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent packages count: 9.0%
Average: 9.6%
Dependent repos count: 10.2%
Last synced: 6 months ago

Dependencies

.github/workflows/release_pypi.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • rtCamp/action-slack-notify v2 composite
.github/workflows/test.yml actions
  • actions/cache v2 composite
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • codecov/codecov-action v3 composite
.github/workflows/test_code_format.yml actions
  • actions/cache v2 composite
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
.github/workflows/test_setup.yml actions
  • actions/cache v2 composite
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
.github/workflows/tests_unmocked.yml actions
  • actions/cache v2 composite
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
.github/workflows/weekly_dependency_test.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • rtCamp/action-slack-notify v2 composite
pyproject.toml pypi
requirements/base.txt pypi
  • certifi >=14.05.14
  • hydra-core >=1.0.0
  • lightly_utils *
  • numpy >=1.18.1
  • python_dateutil >=2.5.3
  • requests >=2.23.0
  • six >=1.10
  • tqdm >=4.44
  • urllib3 >=1.15.1
requirements/dev.txt pypi
  • black ==23.1.0 development
  • docutils <=0.16 development
  • isort ==5.11.5 development
  • lightning-bolts * development
  • matplotlib * development
  • mypy ==1.4.1 development
  • opencv-python * development
  • pandas * development
  • pre-commit * development
  • pylint * development
  • pytest * development
  • pytest-forked * development
  • pytest-mock * development
  • pytest-xdist * development
  • responses * development
  • scikit-learn * development
  • sphinx * development
  • sphinx-copybutton * development
  • sphinx-design * development
  • sphinx-gallery * development
  • sphinx-reredirects * development
  • sphinx-tabs * development
  • sphinx_rtd_theme * development
  • torchmetrics * development
  • tox * development
requirements/openapi.txt pypi
  • aenum >=3.1.11
  • pydantic >=1.10.5,<2
  • python_dateutil >=2.5.3
  • setuptools >=21.0.0
  • urllib3 >=1.25.3
requirements/torch.txt pypi
  • pytorch_lightning >=1.0.4
  • torch *
  • torchvision *
requirements/video.txt pypi
  • av >=8.0.2
  • torchvision >=0.8.0
setup.py pypi